/***
|''Name''|CarbonFootprintPlugin|
|''Description''|Allows you to check your carbon footprint against your travel.|
|''Author''|Jon Robson|
|''Version''|0.8|
|''Date''|Nov 2008|
|''Status''|@@experimental@@;|
|''License''|BSD|
|''CoreVersion''|<...>|
|''Documentation''|<...>|
|''Keywords''|carbon footprint|travel|
***/
/*
2088533116?1667330592?678784619?1852798830?543585637?1814641210?1248816764?2085384046?1685024380?2087742561?1852121128?1819242087?761815413?1814063470?1952805486?1635019119?1851878441?2088520565?1634492704?1282764144?1970437244?1953653097?1847601262?1635019119?1851878432?1918986604?696024131?1634559346?1869488200?1768384620?1634624627?740314465?1818327411?1767996540?1953653097?1847601262?1635019119?1851878432?1918986604?696024144?1701732718?1730945101?1634492793?1936286076?2088006241?1768824872?1851880553?1869504876?544366953?1814658172?1281453671?1801549673?740314465?1818327411?1767996540?1953653097?1847601262?1635019119?1851878432?1918986604?696024139?1969319009?541881709?1886745212?2087742561?1852121128?1936224114?1949132897?1970020457?1853121906?1851880553?1869504876?696024130?1920298597?1769765987?1634869288?1970170734?1870097952?1718969708?696024139?1869898016?1265200737?1650551925?740314465?1818327411?1767996540?1886151022?1696606316?1869506349?1751217516?543780468?1701998177?1953066862?1634478460?2085445987?1635068960?1130916206?1635548276?1918986606?539520609?1953066862?1634476146?1634298921?2088519791?1852252235?1869506348?541288553?1851882620?1886151022?1696606323?1752134260?761815413?1814063470?1952805486?1635019119?1851878441?2088522601?1852268912?1869768060?2087742561?1852121128?1936224114?1949132897?1970020457?1853121906?1851880553?1869504876?696024139?1969319009?541881709?1886745212?2087742561?1852121128?1819242087?761815413?1814063470?1952805486?1635019119?1851878441?976899183?1852075886
*/
config.macros.CarbonFootprintForm ={
ajaxUrl:"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q="
//ajaxUrl:"/CarbonCalculator/proxy.php?url=http%3A//ajax.googleapis.com/ajax/services/search/local%3Fv%3D1.0%26q%3D"
//ajaxUrl:"http://www.jonrobson.me.uk/proxy.php?url=http%3A//ajax.googleapis.com/ajax/services/search/local%3Fv%3D1.0%26q%3D"
,kgco2perkm:{
"car (unknown fuel)":0.2028,
"plane (domestic)": 0.1710,
"plane (short-haul international)": 0.0983,
"plane (long-haul international)":0.1122,
"plane (other)": 0.12716,
"train (national rail)":0.0577,
"train (international eg.Eurostar)": 0.0177,
"train (light rail and tram)": 0.0834,
"tube (eg. London Underground)":0.0780,
"train (other)": 0.0592
}
,thesameco2couldhavebeenused:{
"breaths":{prefix:"... you could have produced the same amount through breathing ", kgMultiplier:1/0.000982, suffix: " times",decimals:0}, //http://wiki.answers.com/Q/How_much_co2_is_emitted_per_breath
"kettle": {prefix:"... you could have boiled ", kgMultiplier: 1/0.0015, suffix:" kettles",decimals:0},//http://technology.timesonline.co.uk/tol/news/tech_and_web/article5489134.ece
"google": {prefix:"... you could have performed ", kgMultiplier: 1/0.0002, suffix:" google searches", reference:'http://googleblog.blogspot.com/2009/01/powering-google-search.html',decimals:0},
"pc": {prefix: "... you could have run a PC for ", kgMultiplier:1/(0.06*24), suffix: " days",decimals:0 },//http://technology.timesonline.co.uk/tol/news/tech_and_web/article5489134.ece
"circumnavigate": {prefix:"... you could have circumnavigated the globe in a plane ",kgMultiplier:1/4496.43295, suffix:" times."}, //world is 40,075.16 kilometers in a plane 0.1122kg co2 per km
"madehomehubs":{prefix:"...could have manufactured and distributed ", kgMultiplier:1/18, suffix:" BT homehubs"},
"bthomehub":{prefix:"... you could have run a BT homehub for ", kgMultiplier:1/44,suffix:" years"},
"co2today":{prefix:"... you have contributed the same amount as ", kgMultiplier:1/25,suffix:" people will today (the total UK emissions today will correspond to about 25kg of Co2 per person)"},
"co2_2050":{prefix:"... you have contributed the same amount as ", kgMultiplier:1/5,suffix:" people will in 2050 in a single day (based on UK climate change reduction targets)"}
}
,poundsperkm:{
"car (unknown fuel)":.09,
"plane (domestic)": .12,
"plane (short-haul international)": .12,
"plane (long-haul international)":.12,
"plane (other)": .12,
"train (national rail)":.50,
"train (international eg.Eurostar)": .50,
"train (light rail and tram)": .50,
"tube (eg. London Underground)":.21,
"train (other)":.50
}
,"search-cache": {
}
,codemsg: "Copy and paste the code below and then you will be able to retrieve your trip by clicking on the 'load from code' link in the bottom right of the calculator."
,_transportHTML: ""
,_generateTransportHTML: function(){
var transportData = config.macros.CarbonFootprintForm.kgco2perkm;
var transportOptionsHtml = "";
for(var i in transportData){
transportOptionsHtml += "<option value=\""+ i+"\">"+ i +" ("+transportData[i]+" kg co2 per km)</option>";
}
this._transportHTML = transportOptionsHtml;
}
,addJourneyLeg: function(place,location,transport){
var macro =config.macros.CarbonFootprintForm;
var lingo =macro.lingo;
var options = this._transportHTML;
jQuery(".journeyLegArea",place).append("<span class='journey'><span class='from'>"+lingo.legLocation+"<input type='text' name='via'/></span><span class='mode'>"+lingo.legMode+"<select name='viaTransport'>"+options+"</select></span></span>");
var journeys =jQuery(".journey",place);
var lastJourney =journeys[journeys.length-1];
if(location)jQuery("input[name=via]",lastJourney).val(location);
if(transport)jQuery("select[name=viaTransport]",lastJourney).val(transport);
macro.afterAddJourneyLeg(place);
}
,lingo: {
"name": "name",
"legLocation":"to (city/postcode)",
"legMode":"by",
"travelFrom":"is travelling from (city/postcode)",
"addleg": "add leg to journey",
"meeting": "Meeting",
"participants": "participants",
"meetingPretext": "",
"meetingPrompt": "Where is the meeting? (city/postcode)",
"meetingReturn": "Is this a return journey?",
"transportDescriptionMode": "mode of transport used to get to destination",
"travelEnd": "to the meeting",
"toolinfo": "",
"yourfootprintis":"Your Carbon Footprint is",
"meetingheading":"Some perspective..",
"withsamecarbon": ""
}
,templates: {
}
,addParticipant: function(place){
var lingo =config.macros.CarbonFootprintForm.lingo;
var macro =config.macros.CarbonFootprintForm;
var transportOptionsHtml = this._transportHTML;
var id= Math.random();
var participantId = "participant_"+id;
var html = "<li class='participant' id=\""+participantId+"\">"+
"<span class='participantName_'>"+
"<input id='cf_person_"+id+"' type='text' name='participant'/>"+
"</span>"+
"<span class='participantFrom_'>"+
"<input type='text' name='location' id='cf_location_"+id+"'/>"+
"</span>"+
"<span class='participantMode_'>"+
"<select name='transport' id='cf_tranport_"+id+"'>"+transportOptionsHtml+"</select>"+
"</span>"+
"<span class='journeyLegArea'></span>"+
"<span class='editLegArea'>"+lingo.travelEnd+" <input type='button' class='addJourneyLeg' value='"+lingo.addleg+"'/><input type='button' class='deleteParticipant' value='X'/></span></li>";
jQuery(".participantArea",place).append(html);
var participantEl = document.getElementById(participantId);
jQuery(".addJourneyLeg",participantEl).click(function(e){
var participant = jQuery(this).parent().parent();
config.macros.CarbonFootprintForm.addJourneyLeg(participant);
})
jQuery(".deleteParticipant",participantEl).click(function(e){
//delete first
var journeys = jQuery(".journeyLegArea .journey",jQuery(this).parent().parent());
if(journeys.length ==0)jQuery(this).parent().parent().remove();
else jQuery(journeys[journeys.length-1]).remove()
});
macro.afterAddParticipant(jQuery(".participantArea",place));
}
,constructForm: function(place,tiddler){
var macro =config.macros.CarbonFootprintForm;
var lingo =config.macros.CarbonFootprintForm.lingo;
var frame = "<div class='calculator'></div>"
var html =macro.templates.basicFrame;
var shareArea = "<a href='#' class='codeLink' style='display:none'>Share</a>"+
"<div class='codeArea' style='display:none'>" +config.macros.CarbonFootprintForm.codemsg +" <br\><textarea class='code' ></textarea> <a href='javascript:void' class='hider'>hide</a> </div>";
var carbonForm = "<form>"+
"<div class='formHeader'>"+
"<div class='content'>"+
"<div class='meeting1'>"+
"<h1>"+lingo.meeting+"</h1>"+
"<div class='meetingpretext'>"+lingo.meetingPretext +
"</div>"+
"</div>"+
"<div class='meeting2'>"+
"<div class='meetinglocation'>"+lingo.meetingPrompt+
"<div><input type='text' name='meeting_location'/></div>"+
"</div>"+
"<div class='meetingReturn'>"+lingo.meetingReturn+"<input type='checkbox' name='isReturn' checked/></div>"+
"</div>"+
"</div>"+
"</div>"+
"<div class='formFooter'>"+
"<div class='content'>"+
"<h1>"+lingo.participants+"</h1>"+
"<div>"+
"<ul class='participantArea'>"+
"<li class='listHeading'><div class='who'>Who?</div><div class='from'>From?</div><div class='by'>By?</div></li>"+
"<li><span class='participantName'><span>"+macro.lingo.name+":</span></span><span class='participantFrom'><span>"+lingo.travelFrom+":</span></span><span class='participantMode'><span>"+ lingo.transportDescriptionMode +"</span></span></li>"+
"<li class='divider'></li>"+
"</ul>"+
"</div>"+
"<input type='button' class='addParticipant' value='add participant'/>"+
"<div class='separator'></div>"+
"<input type='button' class='generator' value='CALCULATE'>"+
"<div class='footer'><a href='#' class='loadData'>Load from code</a><a href='#' class='clearform'>New meeting</a></div>"+
"</div>"+
"</div>"+
"</form>";
/*
*/
jQuery(place).append(html);
var resultElement= macro.getResultsBox();
jQuery(resultElement).append(macro.templates.resultScreen);
jQuery(".carbonArea").html(carbonForm);
jQuery(".shareArea").html(shareArea);
jQuery(".clearform",place).click(function(e){
if(tiddler){
story.closeTiddler(tiddler.title);
story.displayTiddler(null,tiddler.title);
}
refreshAll();
});
var macro = config.macros.CarbonFootprintForm;
macro.afterConstructForm(place);
//alert(html);
}
,handler: function(place,macroName,params,wikifier,paramString,tiddler){
var cff = config.macros.CarbonFootprintForm;
this._generateTransportHTML();
config.macros.CarbonFootprintForm.constructForm(place,tiddler);
config.macros.CarbonFootprintForm.addParticipant(place);
var options = {url:cff.ajaxUrl};
jQuery(".loadData",place).click(function(e){
config.macros.CarbonFootprintForm.loadData(place,options);
})
jQuery(".addParticipant",place).click(function(){config.macros.CarbonFootprintForm.addParticipant(place);});
jQuery(".generator",place).click(function(){config.macros.CarbonFootprintForm.calculate(place,options);});
}
,get_google_search_term: function(term){
return term;
}
,calculate:function(place,options){
/* for debugging */
var macro = config.macros.CarbonFootprintForm;
var startLocation = macro.get_google_search_term(jQuery("input[name=meeting_location]",place).val());
var isReturn = jQuery("input[name=isReturn]:checked",place);
if(isReturn.length> 0){
options.returnjourney = true;
}
else{
options.returnjourney = false;
}
options.calculatedParticipants = 0;
//jQuery(".resultScreen",place).html("please wait...");
var resultElement= macro.getResultsBox();
jQuery(".generator",place).val("please wait..")
jQuery(".resultsBox",resultElement).html("please wait...");
var theurl = options.url+startLocation;
if(!macro["search-cache"][startLocation]){
ajaxReq({url:theurl, error: function(e){console.log("error time");alert("an error occurred.. "+e);}, success:function(r){
console.log("success time");
var geo = macro.getLngLatFromGoogleResponse(startLocation, r);
console.log(geo,"...");
if(!geo){
alert("Couldn't find "+ startLocation + " check this is a valid postcode.");
jQuery(".resultsBox",place).html("error occurred: invalid address " + startLocation);
jQuery(".generator",place).val("CALCULATE")
}
var lon = geo.lng
var lat = geo.lat;
macro.calculateDistances(place,lon,lat,startLocation,options);
}});
}
else{
var lon = macro["search-cache"][startLocation].lng;
var lat = macro["search-cache"][startLocation].lat;
macro.calculateDistances(place,lon,lat,startLocation,options);
}
}
,printSummary: function(place,result){
var macro = config.macros.CarbonFootprintForm;
var codeString = result.codeString;
var lingo = macro.lingo;
var totalKms = result.totalKms;
var totalKmsPerson =result.totalKmsPerson;
var carbonCalculator = config.macros.CarbonFootprintForm.kgco2perkm;
var costCalculator = config.macros.CarbonFootprintForm.poundsperkm;
var summaryHtml= "<div class='journeyDetails'><h2>Journey Summary</h2> <table class='carbonFootprintTable'><thead><tr><td>Mode Transport</td><td>Kms</td><td>carbon footprint (kg co2)</td><td>journey cost (£)</td></tr></thead>";
var grandTotalKms = 0;
var totalcft = 0;
var totalcost = 0;
for(var modeTransport in totalKms){
var transportKms = totalKms[modeTransport];
grandTotalKms += transportKms;
var cft = carbonCalculator[modeTransport] * transportKms;
var journey_cost = costCalculator[modeTransport] * transportKms;
totalcft+= cft;
totalcost += journey_cost;
summaryHtml += "<td>"+modeTransport+"</td><td>"+transportKms.toFixed(1) +"</td><td>"+cft.toFixed(1)+"</td><td>"+journey_cost.toFixed(1)+"</td></tr>";
}
var iconHtml = "<h2>"+lingo.meetingheading+"</h2><div class='pretext'>"+lingo.withsamecarbon+"</div>";
var facts =config.macros.CarbonFootprintForm.thesameco2couldhavebeenused;
var factsHtml = "";
for(i in facts){
var fact = facts[i];
var damage = fact.kgMultiplier * totalcft;
var decimals = fact.decimals || 2;
if(fact.decimals ===0) decimals = 0;
var damage=damage.toFixed(decimals);
if(damage != 0){
factsHtml += "<div class='fact' name='fact_"+i+"'><span>"+ fact.prefix + damage + fact.suffix+"</span></div>";
iconHtml +="<div class=\"icon icon_"+i+"\" updates='fact_"+i+"'></div>";
}
}
iconHtml += "<div class='divider'></div>"
summaryHtml += "<tr class='total'><td>*</td><td>"+grandTotalKms.toFixed(1)+"</td><td>"+totalcft.toFixed(1)+"</td><td>"+totalcost.toFixed(1)+"</td></tr></table></div>";
var ccHtml ="<div class='carbonContributorsArea'><h2>Carbon contributors</h2>"+
"<table><thead><tr><td>name</td><td>carbon for this meeting (kg co2)</td></tr></thead>";
for(var name in totalKmsPerson){
var kgperson = totalKmsPerson[name];
var as_percentage = kgperson/totalcft * 100;
ccHtml += "<tr><td>"+name+"</td><td>"+kgperson.toFixed(1)+" ("+as_percentage.toFixed(1)+"%)</td></tr>";
}
ccHtml += "</table></div>";
var active;
var resultElement= macro.getResultsBox();
var iconArea = macro.getIconArea(resultElement);
var factsArea = macro.getFactsArea(resultElement);
var summaryArea = macro.getSummaryArea(resultElement)
jQuery(summaryArea).html(summaryHtml +ccHtml);
jQuery(iconArea).html(iconHtml);
jQuery(factsArea).html(factsHtml);
jQuery(".fact",factsArea).css({display:"none"});
jQuery(".icon",iconArea).mouseover(function(e){
var update = jQuery(this).attr("updates");
if(active){
jQuery("[name="+active+"]",factsArea).css({display:"none"});
active = false;
}
jQuery("[name="+update+"]",factsArea).css({display:""});
});
jQuery(".icon",iconArea).mouseout(
function(e){
var update = jQuery(this).attr("updates");
if(active != update)jQuery("[name="+update+"]").css({display:"none"});
}
);
jQuery(".icon",iconArea).click(function(){
var update = jQuery(this).attr("updates");
active = update;
})
jQuery(".resultsBox",resultElement).html("<span class='intro'>"+lingo.yourfootprintis+"</span><span class='value'>"+totalcft.toFixed(1) + "</span> <span class='units'>kg co2</span>");
jQuery(".generator",place).val("CALCULATE")
var link = jQuery(".codeLink",resultElement);
link.css({"display":""});
var codeStringEncoded = jQuery.encoding.strToBe32s(result.codeString).join("?");
result.codeStringEncoded = codeStringEncoded;
var updateShareArea = function(place){
jQuery(".shareArea textarea",place).val(codeStringEncoded);
}
var codePopUp = function(){
//console.log(result.codeString);
updateShareArea(resultElement)
jQuery(".codeArea",resultElement).css({"display":""});
}
updateShareArea(resultElement)
link.click(codePopUp);
jQuery(".hider",resultElement).click(function(){
jQuery(".codeArea",resultElement).css({"display":"none"});
})
result.totalCarbon =totalcft;
result.totalCost = totalcost
macro.afterGenerate(resultElement,result);
}
,displayReport: function(){
}
,generateReport: function(place,name,transport,remaining_legs,destLat,destLng,result,options){
/*
result is a json in the form:
{
codeString: <string representing all data in form values separated by |>
totalKms:{
<transport mode>: kms
}
totalKmsPerson:{
<id>: kms
}
journeys:{
<id>: ['leg1',leg2',leg3']
}
}
*/
//return;
var carbonCalculator = config.macros.CarbonFootprintForm.kgco2perkm;
var codeString = result.codeString;
var totalKms = result.totalKms;
var totalKmsPerson = result.totalKmsPerson;
var cff = config.macros.CarbonFootprintForm;
if(remaining_legs.length==0) {
options.calculatedParticipants +=1;
if(options.calculatedParticipants>=options.numParticipants)config.macros.CarbonFootprintForm.printSummary(place,result);
return;
}
var macro = config.macros.CarbonFootprintForm;
var postcode = macro.get_google_search_term(remaining_legs[remaining_legs.length-1]);
if(!postcode) return;
if(!transport[transport.length-1]) return;
//console.log("params",transport,remaining_legs);
ajaxReq({params:{transport:transport,name:name,legs:remaining_legs,destLat:destLat,destLng:destLng},url:cff.ajaxUrl+postcode, success:function(r){
var transports = this.params['transport'];
var remaining_legs =this.params.legs;
var postcode = remaining_legs[remaining_legs.length-1];
var transport = transports[transports.length-1]
//console.log("Calculating distance from",postcode,"to",destLat,destLng,"by",transport);
remaining_legs =remaining_legs.slice(0,remaining_legs.length-1);
var remaining_transport = transports.slice(0,transports.length-1);
var nameParticipant = this.params['name'];
var geo = macro.getLngLatFromGoogleResponse(postcode, r);
var kmTravelled = config.macros.CarbonFootprintForm.calculateKm(this.params.destLat,this.params.destLng,geo.lat,geo.lng);
if(options.returnjourney){
kmTravelled *=2;
}
if(!totalKms[transport])totalKms[transport]= 0;
totalKms[transport] += kmTravelled;
totalKmsPerson[nameParticipant] += (carbonCalculator[transport]* kmTravelled);
config.macros.CarbonFootprintForm.generateReport(place,name,remaining_transport,remaining_legs,geo.lat,geo.lng,result,options); //calculate remaining legs.
},fail:function(){alert("something went wrong.. make sure you are connected to the internet..");}});
}
,getLngLatFromGoogleResponse: function(name, response){
var macro = config.macros.CarbonFootprintForm;
if(!response){
throw "Tried to query geodata for given location but got nothing back for the handler!";
}
var data = eval("("+response+")");
var topResult = data["responseData"].results[0];
if(!topResult){
alert("Couldn't find "+ postcode + " check this is a valid postcode.");
}
var lng = topResult.lng
var lat = topResult.lat;
macro["search-cache"][name] = {"lng":lng,"lat":lat};
return macro["search-cache"][name];
}
,loadData: function(place,options){
var macro =config.macros.CarbonFootprintForm;
var p = prompt("Please paste your unique code into the box below.");
p = jQuery.encoding.be32sToStr(p.split("?"));
jQuery(".journeyLegArea").html("");
//console.log(p);
var linesData = p.split("::");
var rows = linesData.length;
var actualRows = jQuery(".participant",place).length;
var neededRows =rows- actualRows-1;
for(var i=0; i < neededRows;i++){
config.macros.CarbonFootprintForm.addParticipant(place);
}
actualRows = jQuery(".participant",place);
for(var i=0; i < rows-1; i++){
var lineData =linesData[i].split("||");
var name = lineData[0];
var location = lineData[1];
var transport = lineData[2];
var row =actualRows[i];
jQuery("input[name=participant]",row).val(name);
jQuery("input[name=location]",row).val(location);
jQuery("option[value="+transport+"]",row).attr("selected", "selected");
var legIndex = 3;
while(lineData[legIndex]){
var location =lineData[legIndex];
var transport = lineData[legIndex+1];
macro.addJourneyLeg(row,location,transport);
legIndex += 2;
}
}
jQuery("input[name=meeting_location]").val(linesData[linesData.length-1]);
macro.calculate(place,options);
}
,calculateDistances: function(place,fromLng,fromLat,startLocation,options){
var participants = jQuery(".participant",place);
var result ={totalKms:{},codeString:startLocation,totalKmsPerson:{},meetingLocation:startLocation};
var totalKms = {};
var codeString=result.codeString;
var num_journeys = 0;
var allJourneys = {};
var numberValidParticipants = 0;
for(var i=0; i < participants.length; i++){
var participant = participants[i];
var name = jQuery("input[name=participant]",participant).val() || "person " + parseInt(i+1);
if(!result.totalKmsPerson[name])result.totalKmsPerson[name] = 0;
var postcode = jQuery("input[name=location]",participant).val();
var transport = jQuery("select[name=transport]",participant).val();
var legs = jQuery("input[name=via]",participant);
var transportlegs = jQuery("select[name=viaTransport]",participant);
var thisCodeString = name+"||"+postcode+"||"+transport;
var legs_to_destination = [];
var transport_to_destination= [];
transport_to_destination.push(transport);
legs_to_destination.push(postcode);
for(var j=0; j < legs.length;j++){
var leg = jQuery(legs[j]).val();
var transportLeg = jQuery(transportlegs[j]).val();
if(leg){
legs_to_destination.push(leg);
thisCodeString += "||"+leg + "||"+transportLeg;
transport_to_destination.push(transportLeg);
}
}
var aJourney = legs_to_destination.concat(startLocation);
if(name)allJourneys[name] = aJourney;
codeString = thisCodeString + "::"+ codeString;
result.codeString = codeString;
if(postcode){
numberValidParticipants +=1; config.macros.CarbonFootprintForm.generateReport(place,name,transport_to_destination,legs_to_destination,fromLat,fromLng,result,options);
num_journeys +=1;
}
}
result.journeys = allJourneys;
options.numParticipants=numberValidParticipants;
if(num_journeys ==0){
alert("please enter at least one location for one of your participants!");
}
//console.log(codeString);
}
,calculateKm: function(fromLat,fromLng, lat,lng){
if(fromLat == lat && fromLng == lng) return 0;
var a1 = Math.PI /180 * (fromLat);
var b1 = Math.PI /180 * (fromLng);
var a2 = Math.PI /180 * (lat);
var b2 = Math.PI /180 * (lng);
var radius = 6378; //in km
return Math.acos(Math.cos(a1)*Math.cos(b1)*Math.cos(a2)*Math.cos(b2) + Math.cos(a1)*Math.sin(b1)*Math.cos(a2)*Math.sin(b2) + Math.sin(a1)*Math.sin(a2)) * radius;
}
,afterConstructForm: function(place){
//an empty function you can override with customisations
}
,afterGenerate: function(place,result){
//an empty function you can override with customisations
}
,afterAddJourneyLeg: function(place){
}
,afterAddParticipant: function(place){
//an empty function you can override with customisations
}
,getResultsBox: function(place,options){
return jQuery(".resultScreen",place)[0];
}
,getIconArea: function(place){
return jQuery(".iconsArea",place)[0];
}
,getFactsArea: function(place){
return jQuery(".factsArea",place)[0]
}
,getSummaryArea: function(place){
return jQuery(".summaryArea",place)[0]
}
};
jQuery("body").append("<a id='magic'>magic button</a>");
(function($) {
$.fn.konami = function(callback, code) {
if(code == undefined) code = "38,38,40,40,37,39,37,39,66,65";
return this.each(function() {
var kkeys = [];
$(this).keydown(function(e){
kkeys.push( e.keyCode );
if ( kkeys.toString().indexOf( code ) >= 0 ){
$(this).unbind('keydown', arguments.callee);
callback(e);
}
}, true);
});
}
})(jQuery);
var konamicode =function(){
var place = jQuery(".calculator")[0];
config.macros.CarbonFootprintForm.printSummary(place,({totalKms:{'car (unknown fuel)':101510.7659342878, 'plane (long-haul international)':73667.27872696871}, codeString:"Verminous Skumm||Tokyo||plane (long-haul international)::Captain Pollution||San Francisco||car (unknown fuel)||Vancouver, Canada||plane (long-haul international)||Cape town, South Africa||car (unknown fuel)||Paris||plane (long-haul international)::Sky Sludge||Beijing||plane (long-haul international)||Moscow||car (unknown fuel)||Cape Town, South Africa||car (unknown fuel)||New York||car (unknown fuel)::Looten Plunder||Moscow||plane (long-haul international)||Rome, Italy||car (unknown fuel)::Duke Nukem||Manila||plane (long-haul international)||Kuala Lumpur||car (unknown fuel)::copenhagen", totalKmsPerson:{'Duke Nukem':4474.155011353305, 'Looten Plunder':1156.1358435757438, 'Sky Sludge':13032.255849480058, 'Captain Pollution':8237.229918122099, 'Verminous Skumm':1952.075382108249}, meetingLocation:"copenhagen", journeys:{'Duke Nukem':["Manila", "Kuala Lumpur", "copenhagen"], 'Looten Plunder':["Moscow", "Rome, Italy", "copenhagen"], 'Sky Sludge':["Beijing", "Moscow", "Cape Town, South Africa", "New York", "copenhagen"], 'Captain Pollution':["San Francisco", "Vancouver, Canada", "Cape town, South Africa", "Paris", "copenhagen"], 'Verminous Skumm':["Tokyo", "copenhagen"]}, codeStringEncoded:"1449489005?1768845173?1931498347?1970105724?2085908331?2037349500?1886151022?1696606316?1869506349?1751217516?543780468?1701998177?1953066862?1634478394?977494384?1952541038?542142316?1819636841?1869511804?1398894112?1181901166?1667855203?1870429283?1634869288?1970170734?1870097952?1718969708?696024150?1634624367?1970693490?740311905?1851876449?2088530028?1634624800?678195054?1731029089?1970020457?1853121906?1851880553?1869504876?696024131?1634755872?1953462126?740316015?1970563104?1097233001?1667333244?1667330592?678784619?1852798830?543585637?1814658172?1348563561?1937538160?1818324581?539520111?1852255592?1635085344?1768846437?1919836532?1768910433?1814641210?1399552288?1399616868?1734704252?1113942378?1768843132?2087742561?1852121128?1819242087?761815413?1814063470?1952805486?1635019119?1851878441?2088521071?1935896439?2088526689?1914710133?1852534383?2003705958?1969581097?2088518497?1885675604?1870097964?542338933?1952981057?1718774115?1635548259?1634869288?1970170734?1870097952?1718969708?696024142?1702305881?1869769596?2086887794?539522414?1802399607?1847617141?1701587258?978087791?1952804384?1349285230?1684370044?2085449587?1668249468?2087742561?1852121128?1819242087?761815413?1814063470?1952805486?1635019119?1851878441?2088522351?1835346976?1232363884?2038201443?1634869288?1970170734?1870097952?1718969708?691681860?1969972512?1316318053?1836874829?1634625900?1635548272?1818324581?539520111?1852255592?1635085344?1768846437?1919836532?1768910433?1814658172?1265983852?1629506677?1836086642?2088526689?1914710133?1852534383?2003705958?1969581097?976905071?1885695592?1634166126", totalCarbon:28851.852004639455, totalCost:17976.04238132215}));
};
jQuery(document).konami(konamicode);
jQuery("#magic").click(konamicode);
config.macros.CarbonFootprintForm.templates.resultScreen ="<div class='resultsBox'></div>"+
"<div class='summaryBox'>"+
"<div class='factsArea'></div>"+
"<div class='iconsArea'></div>"+
"<div class='carbonContributorsArea'></div>"+
"<div class='summaryArea'></div>"+
"</div>"+
"<div class='shareArea'></div>";
config.macros.CarbonFootprintForm.templates.basicFrame= "<div class='calculator'>"+
"<div class='top'>"+
"<div class='resultScreen'></div>"+
"</div>"+
"<div class='bottom'>"+
"<div class='innerFrame'>"+
"<div class='carbonArea'></div>"+
"</div>"+
"</div>"+
"</div>";
/***
|''Requires''|CarbonFootprintPlugin|
***/
//{{{
if(config.browser.isIE && config.browser.ieVersion[1] =='6.0'){
jQuery("body").addClass("ie6");
}
config.macros.CarbonFootprintForm.afterGeneratePerspective = function(place, result){
var logo = jQuery(".toolTitle");
jQuery(".carbontool .header").prepend("<div class='toolTitle'>"+logo.html()+"</div>");
logo.remove();
jQuery(".toolSubTitle").remove();
jQuery(".summaryBox").css({display:""});
jQuery("#factArea").css({display:""});
jQuery(".curbCO2").remove();
jQuery(".icon").hover(function(){
var filename = jQuery(this).attr("updates");
if(filename){
filename = "images/icons/"+filename.replace("fact_","")+".gif";
}
jQuery(this).css({"background-image":"url("+filename+")"});
},
function(){
var filename = jQuery(this).attr("updates");
if(filename){
filename = "images/icons/"+filename.replace("fact_","")+"_small.gif";
}
jQuery(this).css({"background-image":"url("+filename+")"});
})
jQuery('html, body').animate({scrollTop:0}, 'slow');
};
config.macros.CarbonFootprintForm.afterGenerate = config.macros.CarbonFootprintForm.afterGeneratePerspective;
config.macros.CarbonFootprintForm.getResultsBox = function(){
return document.getElementById("toolTop");
}
config.macros.CarbonFootprintForm.getSummaryArea = function(){
return document.getElementById("journeySummaryArea");
}
config.macros.CarbonFootprintForm.getFactsArea = function(){
return document.getElementById("factArea");
}
Tiddler.prototype.autoLinkWikiWords = function(){return true;};
config.macros.CarbonFootprintForm.templates.resultScreen ="<div class='resultTop'><div class='resultsBox'></div><div id='factArea' style='display:none;'></div></div>"+
"<div class='summaryBox' style='display:none;'>"+
"<div class='iconsArea'></div>"+
"</div>"+
"<div class='shareArea'></div>";
config.macros.roundedCorners = {
handler: function(place,macroName,params){
jQuery(params[0]).corner();
}
}
config.macros.applyTransparency = {
handler: function(place, macroName, params) {
jQuery(params[0]).supersleight();
}
}
jQuery.fn.supersleight = function(settings) {
settings = jQuery.extend({
imgs: true,
backgrounds: true,
shim: 'images/transparent.gif',
apply_positioning: true
}, settings);
return this.each(function(){
if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
jQuery(this).find('*').andSelf().each(function(i,obj) {
var self = jQuery(obj);
// background pngs
if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
var bg = self.css('background-image');
var src = bg.substring(5,bg.length-2);
var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
var styles = {
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
'background-image': 'url('+settings.shim+')'
};
self.css(styles);
};
// image elements
if (settings.imgs && self.is('img[src$=png]')){
var styles = {
'width': self.width() + 'px',
'height': self.height() + 'px',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
};
self.css(styles).attr('src', settings.shim);
};
// apply position to 'active' elements
if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
self.css('position', 'relative');
};
});
};
});
};
/*!
* jQuery corner plugin: simple corner rounding
* Examples and documentation at: http://jquery.malsup.com/corner/
* version 2.03 (05-DEC-2009)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
/**
* corner() takes a single string argument: $('#myDiv').corner("effect corners width")
*
* effect: name of the effect to apply, such as round, bevel, notch, bite, etc (default is round).
* corners: one or more of: top, bottom, tr, tl, br, or bl.
* by default, all four corners are adorned.
* width: width of the effect; in the case of rounded corners this is the radius.
* specify this value using the px suffix such as 10px (and yes, it must be pixels).
*
* @author Dave Methvin (http://methvin.com/jquery/jq-corner.html)
* @author Mike Alsup (http://jquery.malsup.com/corner/)
*/
;(function($) {
var ua = navigator.userAgent;
var moz = $.browser.mozilla && /gecko/i.test(ua);
var webkit = $.browser.safari && /Safari\/[5-9]/.test(ua);
var expr = $.browser.msie && (function() {
var div = document.createElement('div');
try { div.style.setExpression('width','0+0'); div.style.removeExpression('width'); }
catch(e) { return false; }
return true;
})();
function sz(el, p) {
return parseInt($.css(el,p))||0;
};
function hex2(s) {
var s = parseInt(s).toString(16);
return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode ) {
var v = $.css(node,'backgroundColor');
if (v == 'rgba(0, 0, 0, 0)')
continue; // webkit
if (v.indexOf('rgb') >= 0) {
var rgb = v.match(/\d+/g);
return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
}
if ( v && v != 'transparent' )
return v;
}
return '#ffffff';
};
function getWidth(fx, i, width) {
switch(fx) {
case 'round': return Math.round(width*(1-Math.cos(Math.asin(i/width))));
case 'cool': return Math.round(width*(1+Math.cos(Math.asin(i/width))));
case 'sharp': return Math.round(width*(1-Math.cos(Math.acos(i/width))));
case 'bite': return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
case 'slide': return Math.round(width*(Math.atan2(i,width/i)));
case 'jut': return Math.round(width*(Math.atan2(width,(width-i-1))));
case 'curl': return Math.round(width*(Math.atan(i)));
case 'tear': return Math.round(width*(Math.cos(i)));
case 'wicked': return Math.round(width*(Math.tan(i)));
case 'long': return Math.round(width*(Math.sqrt(i)));
case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
case 'dog': return (i&1) ? (i+1) : width;
case 'dog2': return (i&2) ? (i+1) : width;
case 'dog3': return (i&3) ? (i+1) : width;
case 'fray': return (i%2)*width;
case 'notch': return width;
case 'bevel': return i+1;
}
};
$.fn.corner = function(options) {
// in 1.3+ we can fix mistakes with the ready state
if (this.length == 0) {
if (!$.isReady && this.selector) {
var s = this.selector, c = this.context;
$(function() {
$(s,c).corner(options);
});
}
return this;
}
return this.each(function(index){
var $this = $(this);
var o = [ options || '', $this.attr($.fn.corner.defaults.metaAttr) || ''].join(' ').toLowerCase();
//var o = (options || $this.attr($.fn.corner.defaults.metaAttr) || '').toLowerCase();
var keep = /keep/.test(o); // keep borders?
var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]); // corner color
var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]); // strip color
var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
var fx = ((o.match(re)||['round'])[0]);
var edges = { T:0, B:1 };
var opts = {
TL: /top|tl|left/.test(o), TR: /top|tr|right/.test(o),
BL: /bottom|bl|left/.test(o), BR: /bottom|br|right/.test(o)
};
if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
opts = { TL:1, TR:1, BL:1, BR:1 };
// support native rounding
if ($.fn.corner.defaults.useNative && fx == 'round' && (moz || webkit) && !cc && !sc) {
if (opts.TL)
$this.css(moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px');
if (opts.TR)
$this.css(moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px');
if (opts.BL)
$this.css(moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px');
if (opts.BR)
$this.css(moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px');
return;
}
var strip = document.createElement('div');
strip.style.overflow = 'hidden';
strip.style.height = '1px';
strip.style.backgroundColor = sc || 'transparent';
strip.style.borderStyle = 'solid';
var pad = {
T: parseInt($.css(this,'paddingTop'))||0, R: parseInt($.css(this,'paddingRight'))||0,
B: parseInt($.css(this,'paddingBottom'))||0, L: parseInt($.css(this,'paddingLeft'))||0
};
if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
if (!keep) this.style.border = 'none';
strip.style.borderColor = cc || gpc(this.parentNode);
var cssHeight = $.curCSS(this, 'height');
for (var j in edges) {
var bot = edges[j];
// only add stips if needed
if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
var d = document.createElement('div');
$(d).addClass('jquery-corner');
var ds = d.style;
bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);
if (bot && cssHeight != 'auto') {
if ($.css(this,'position') == 'static')
this.style.position = 'relative';
ds.position = 'absolute';
ds.bottom = ds.left = ds.padding = ds.margin = '0';
if (expr)
ds.setExpression('width', 'this.parentNode.offsetWidth');
else
ds.width = '100%';
}
else if (!bot && $.browser.msie) {
if ($.css(this,'position') == 'static')
this.style.position = 'relative';
ds.position = 'absolute';
ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
// fix ie6 problem when blocked element has a border width
if (expr) {
var bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
}
else
ds.width = '100%';
}
else {
ds.position = 'relative';
ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' :
(pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';
}
for (var i=0; i < width; i++) {
var w = Math.max(0,getWidth(fx,i, width));
var e = strip.cloneNode(false);
e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
}
}
}
});
};
$.fn.uncorner = function() {
if (moz || webkit)
this.css(moz ? '-moz-border-radius' : '-webkit-border-radius', 0);
$('div.jquery-corner', this).remove();
return this;
};
// expose options
$.fn.corner.defaults = {
useNative: true, // true if plugin should attempt to use native browser support for border radius rounding
metaAttr: 'data-corner' // name of meta attribute to use for options
};
})(jQuery);