<commit_before>$(document).ready(function(){
  $("#locationbtn").click(function(){
    if($("#location").hasClass("notselected")){
     $("#location").removeClass("notselected").addClass("selected");
     $("#manual").removeClass("selected").addClass("notselected");
     $("#manualview").css("z-index","-1");
     $("#locationview").css("z-index","1");
    }
  });

  $("#manualbtn").click(function(){
    if($("#manual").hasClass("notselected")){
     $("#manual").removeClass("notselected").addClass("selected");
     $("#location").removeClass("selected").addClass("notselected");
     $("#locationview").css("z-index","-1");
     $("#manualview").css("z-index","1");
    }
  });

   $("#backbtnAdd").click({
        param: 'route_view'
    }, showView);

	 $("#changeIconAdd").click({
				param: 'chooseIcon_view'
		},showView);

	$("#trackLocation").click(function(){
		findStops();
	});

  $("#addStop-add").click(function(){
    $("#stoplist-add").append('

<input class="stopname" type="text" placeholder="Haltestellenname" />

')
  });

   $("#deleteStop-add").click(function(){
    if($("#stoplist-add").children().last().attr("id")!="first"){
      $("#stoplist-add").children().last().remove();
    }
  });
		// for now you can only manually add favorites
		// before adding it to localforage check if there is already an entry with same referencename
		// if the list wasn't already initialised it gets initialised
$("#addbtn").click(function(){
			if($("#stopname").val()!== "" && $("#stopname").val() !== "" && $("#reference").val() !== ""){
				var obj = new Object();
				obj.stopname = $("#stopname").val();
				obj.town = $("#town").val();
				obj.icon = $("#icon-add").attr("name");
				obj.reference = $("#reference").val();

				localforage.getItem("favList",function(err,value){
					var favList = value;
					if(favList === null){
						favList = [];
						favList.push(obj);
						localforage.setItem("favList",favList,function(err){location.reload();});
					}else{
						var contains = false;
						for(var i = 0;i < favList.length; i++){
							if(favList[i].reference === obj.reference){
								contains = true;
							}
						}
						if(!contains){
							favList.push(obj);
							localforage.setItem("favList",favList,function(err){location.reload();});
						}
					}
				});

			}

		});

	$("#changeIconAdd").click(function(){
		$('.view').each(function(index) {
    	if($(this).attr('id') == 'chooseIcon_view') {
      	$(this).show();
      }else {
      	$(this).hide();
      }
		});
		$(".iconDiv").click(function(event){
			var icon = event.target.id;
			if(icon!=""){
				$("#icon-add").remove();
				$("#iconContainer-add").append('

');

				$('.view').each(function(index) {
    			if($(this).attr('id') == 'routeAdd_view') {
      			$(this).show();
      		}else {
      			$(this).hide();
      		}
				});
			}
		});
	});

});

//Globals
var range=200.0;

function findStops(){
  //Normale Lösung
  /*
  if ("geolocation" in navigator) {
  // geolocation is available
  navigator.geolocation.getCurrentPosition(function(position) {
    getTownNamesByPosition(position.coords.latitude, position.coords.longitude);
  });
  } else {
  // geolocation IS NOT available
  console.log("Sorry but your geolocation is not available!");
  }
  */

  //TEST Version
  getStopAndTownByPosition(50.3611643, 7.559261);
}

function getStopAndTownByPosition(latitude,longitude){
  var request="[out:json];is_in("+latitude+","+longitude+");out;node(around:"+range+","+latitude+","+longitude+");out;"; // Alle Routen mit Haltestellen etc
  var query='http://overpass-api.de/api/interpreter?data='+request;

  var x = new XMLHttpRequest();
  x.open("GET", query);
  x.onload = x.onerror = function(){
      console.log("LOADING COMPLETE");

      var responseObject = JSON.parse(x.responseText);
      var elements = responseObject.elements;
      var town = null;
      var busStops = [];
      for (var i=0; i<elements.length; i++){
        if (elements[i].type === "area"){
          //console.log(JSON.stringify(elements[i].tags));
          if (elements[i].tags['de:place']==="city"){
            town = elements[i].tags.name;
          }
        }
        if (elements[i].type==="node"){
          if (elements[i].tags != null){
            if((elements[i].tags.highway === "bus_stop")||(elements[i].tags.amenity === "bus_station")||(elements[i].tags.public_transport === "platform")){
              if (busStops.indexOf(elements[i].tags.name)===-1){
                busStops.push(elements[i].tags.name);
              }
            }
          }
        }
      }
      if (town===null){ //Stadt nicht gefunden -> alert
        console.log("ERROR, STADT NICHT GEFUNDEN!");
        alert("Keine Haltestellen gefunden");
        return;
      }
      if (busStops === []){ //Stops nicht gefunden -> alert
        console.log("NO BUSSTOPS IN YOUR AREA!");
        alert("Keine Haltestellen gefunden");
        return;
      }
      if (busStops.length===1){ // 1 Ergebnis -> Trage ein
        console.log("1 BUSSTOPS IN YOUR AREA!");
        if($("#manual").hasClass("notselected")){
           $("#manual").removeClass("notselected").addClass("selected");
           $("#location").removeClass("selected").addClass("notselected");
           $("#locationview").css("z-index","-1");
           $("#manualview").css("z-index","1");
        }

        $("#town").val(town);
        $("#firststop").val(busStops[0]);

      } else{ // mehrere Ergebnisse -> Auswahlbildschirm -> Trage ein

        console.log("MULTIPLE BUSSTOPS IN YOUR AREA!");
        $('.view').each(function(index) {
	        if ($(this).attr('id') == 'stopSelection_view') {
	            $(this).show();
	        } else {
	            $(this).hide();
        	}
        });

        $("#stops").empty();
        //Fülle mit Liste
		for (var n=0; n<busStops.length;n++){
	          $("#stops").append("
<button class='stopselect-btn' id='btn"+n+"'>"+busStops[n]+"</button>
");
	          $("#btn"+n).click(function(){
                if($(this).hasClass('clicked')){
                  $(this).removeClass('clicked');
                }else{
                  $(this).toggleClass('clicked');
                }
       		  });
	    }
      $("#stops").append("
<button id='continue-track'>Weiter</button>
");
      $("#continue-track").click(function(){
                //All checked in an Array -> Fill Add
                var selectedButtons =[];
                $(".stopselect-btn").each(function(){
                  if($(this).hasClass('clicked')){
                    selectedButtons.push($(this).text());
                  }
                });

                //Zurück zu RouteAdd
                $('.view').each(function(index) {
                if ($(this).attr('id') == 'routeAdd_view') {
                   $(this).show();
                } else {
                    $(this).hide();
                }
              });
              //Switch auf manual
              if($("#manual").hasClass("notselected")){
                 $("#manual").removeClass("notselected").addClass("selected");
                 $("#location").removeClass("selected").addClass("notselected");
                 $("#locationview").css("z-index","-1");
                 $("#manualview").css("z-index","1");
              }
              $("#town").val(town);

              for (var n=0;n<selectedButtons.length;n++){
                if (n===0){
                  $("#firststop").val(selectedButtons[0]);
                } else {
                  $("#stoplist-add").append('

<input class="stopname" type="text" placeholder="Haltestellenname" value="'+selectedButtons[n]+'" />

');
                }

              }

            });
      }

      console.log(town);
      console.log(JSON.stringify(busStops));

    };
  x.send();
}
<commit_msg>fixed search<commit_after>$(document).ready(function(){
  $("#locationbtn").click(function(){
    if($("#location").hasClass("notselected")){
     $("#location").removeClass("notselected").addClass("selected");
     $("#manual").removeClass("selected").addClass("notselected");
     $("#manualview").css("z-index","-1");
     $("#locationview").css("z-index","1");
    }
  });

  $("#manualbtn").click(function(){
    if($("#manual").hasClass("notselected")){
     $("#manual").removeClass("notselected").addClass("selected");
     $("#location").removeClass("selected").addClass("notselected");
     $("#locationview").css("z-index","-1");
     $("#manualview").css("z-index","1");
    }
  });

   $("#backbtnAdd").click({
        param: 'route_view'
    }, showView);

	 $("#changeIconAdd").click({
				param: 'chooseIcon_view'
		},showView);

	$("#trackLocation").click(function(){
		findStops();
	});

  $("#addStop-add").click(function(){
    $("#stoplist-add").append('

<input class="stopname" type="text" placeholder="Haltestellenname" />

')
  });

   $("#deleteStop-add").click(function(){
    if($("#stoplist-add").children().last().attr("id")!="first"){
      $("#stoplist-add").children().last().remove();
    }
  });
		// for now you can only manually add favorites
		// before adding it to localforage check if there is already an entry with same referencename
		// if the list wasn't already initialised it gets initialised
$("#addbtn").click(function(){
			if($("#stopname").val()!== "" && $("#stopname").val() !== "" && $("#reference").val() !== ""){
				var obj = new Object();
        obj.stopname = [];

        //Find stopnames by lookibg for class
        $('.stopname').each(function(index) {
          obj.stopname.push($(this).val());
        });

				obj.town = $("#town").val();
				obj.icon = $("#icon-add").attr("name");
				obj.reference = $("#reference").val();

				localforage.getItem("favList",function(err,value){
					var favList = value;
					if(favList === null){
						favList = [];
						favList.push(obj);
						localforage.setItem("favList",favList,function(err){location.reload();});
					}else{
						var contains = false;
						for(var i = 0;i < favList.length; i++){
							if(favList[i].reference === obj.reference){
								contains = true;
							}
						}
						if(!contains){
							favList.push(obj);
							localforage.setItem("favList",favList,function(err){location.reload();});
						}
					}
				});

			}

		});

	$("#changeIconAdd").click(function(){
		$('.view').each(function(index) {
    	if($(this).attr('id') == 'chooseIcon_view') {
      	$(this).show();
      }else {
      	$(this).hide();
      }
		});
		$(".iconDiv").click(function(event){
			var icon = event.target.id;
			if(icon!=""){
				$("#icon-add").remove();
				$("#iconContainer-add").append('

');

				$('.view').each(function(index) {
    			if($(this).attr('id') == 'routeAdd_view') {
      			$(this).show();
      		}else {
      			$(this).hide();
      		}
				});
			}
		});
	});

});

//Globals
var range=200.0;

function findStops(){
  //Normale Lösung
  /*
  if ("geolocation" in navigator) {
  // geolocation is available
  navigator.geolocation.getCurrentPosition(function(position) {
    getTownNamesByPosition(position.coords.latitude, position.coords.longitude);
  });
  } else {
  // geolocation IS NOT available
  console.log("Sorry but your geolocation is not available!");
  }
  */

  //TEST Version
  getStopAndTownByPosition(50.3611643, 7.559261);
}

function getStopAndTownByPosition(latitude,longitude){
  var request="[out:json];is_in("+latitude+","+longitude+");out;node(around:"+range+","+latitude+","+longitude+");out;"; // Alle Routen mit Haltestellen etc
  var query='http://overpass-api.de/api/interpreter?data='+request;

  var x = new XMLHttpRequest();
  x.open("GET", query);
  x.onload = x.onerror = function(){
      console.log("LOADING COMPLETE");

      var responseObject = JSON.parse(x.responseText);
      var elements = responseObject.elements;
      var town = null;
      var busStops = [];
      for (var i=0; i<elements.length; i++){
        if (elements[i].type === "area"){
          //console.log(JSON.stringify(elements[i].tags));
          if (elements[i].tags['de:place']==="city"){
            town = elements[i].tags.name;
          }
        }
        if (elements[i].type==="node"){
          if (elements[i].tags != null){
            if((elements[i].tags.highway === "bus_stop")||(elements[i].tags.amenity === "bus_station")||(elements[i].tags.public_transport === "platform")){
              if (busStops.indexOf(elements[i].tags.name)===-1){
                busStops.push(elements[i].tags.name);
              }
            }
          }
        }
      }
      if (town===null){ //Stadt nicht gefunden -> alert
        console.log("ERROR, STADT NICHT GEFUNDEN!");
        alert("Keine Haltestellen gefunden");
        return;
      }
      if (busStops === []){ //Stops nicht gefunden -> alert
        console.log("NO BUSSTOPS IN YOUR AREA!");
        alert("Keine Haltestellen gefunden");
        return;
      }
      if (busStops.length===1){ // 1 Ergebnis -> Trage ein
        console.log("1 BUSSTOPS IN YOUR AREA!");
        if($("#manual").hasClass("notselected")){
           $("#manual").removeClass("notselected").addClass("selected");
           $("#location").removeClass("selected").addClass("notselected");
           $("#locationview").css("z-index","-1");
           $("#manualview").css("z-index","1");
        }

        $("#town").val(town);
        $("#firststop").val(busStops[0]);

      } else{ // mehrere Ergebnisse -> Auswahlbildschirm -> Trage ein

        console.log("MULTIPLE BUSSTOPS IN YOUR AREA!");
        $('.view').each(function(index) {
	        if ($(this).attr('id') == 'stopSelection_view') {
	            $(this).show();
	        } else {
	            $(this).hide();
        	}
        });

        $("#stops").empty();
        //Fülle mit Liste
		for (var n=0; n<busStops.length;n++){
	          $("#stops").append("
<button class='stopselect-btn' id='btn"+n+"'>"+busStops[n]+"</button>
");
	          $("#btn"+n).click(function(){
                if($(this).hasClass('clicked')){
                  $(this).removeClass('clicked');
                }else{
                  $(this).toggleClass('clicked');
                }
       		  });
	    }
      $("#stops").append("
<button id='continue-track'>Weiter</button>
");
      $("#continue-track").click(function(){
                //All checked in an Array -> Fill Add
                var selectedButtons =[];
                $(".stopselect-btn").each(function(){
                  if($(this).hasClass('clicked')){
                    selectedButtons.push($(this).text());
                  }
                });

                //Zurück zu RouteAdd
                $('.view').each(function(index) {
                if ($(this).attr('id') == 'routeAdd_view') {
                   $(this).show();
                } else {
                    $(this).hide();
                }
              });
              //Switch auf manual
              if($("#manual").hasClass("notselected")){
                 $("#manual").removeClass("notselected").addClass("selected");
                 $("#location").removeClass("selected").addClass("notselected");
                 $("#locationview").css("z-index","-1");
                 $("#manualview").css("z-index","1");
              }
              $("#town").val(town);

              for (var n=0;n<selectedButtons.length;n++){
                if (n===0){
                  $("#firststop").val(selectedButtons[0]);
                } else {
                  $("#stoplist-add").append('

<input class="stopname" type="text" placeholder="Haltestellenname" value="'+selectedButtons[n]+'" />

');
                }

              }

            });
      }

      console.log(town);
      console.log(JSON.stringify(busStops));

    };
  x.send();
}
<|endoftext|>


<commit_before>/* global $,document,console,Parse */
$(document).ready(function() {

	Parse.initialize("5xLComLHX1pDr9ziaEnsaGLaxAkrHXT1DoOeIr1r", "ZXTQfqtjb33uZOlReHWoEXHwevsosi0djUL3gh0D");
	var CommentObject = Parse.Object.extend("CommentObject");

	$("#contactForm").on("submit", function(e) {
		e.preventDefault();

		console.log("Handling the submit");
		//add error handling here
		//gather the form data

		var name = $("#name").val();
		var email = $("#email").val();

		if name != "" && email != "" {
			var data = {};
			data.name = $("#name").val();
			data.email = $("#email").val();
			data.phone = $("#phone").val();
			data.comments = $("#message").val();

			var comment = new CommentObject();
			comment.save(data, {
				success:function() {
					console.log("Success");
					//Alerts are lame - but quick and easy
					alert("Thanks for filling the form!");
				},
				error:function(e) {
					console.dir(e);
				}
			});
		} else {
			alert("Please enter your name and email!");
			console.log("Fail");
		}

	});

});
<commit_msg>minor fix<commit_after>/* global $,document,console,Parse */
$(document).ready(function() {

	Parse.initialize("5xLComLHX1pDr9ziaEnsaGLaxAkrHXT1DoOeIr1r", "ZXTQfqtjb33uZOlReHWoEXHwevsosi0djUL3gh0D");
	var CommentObject = Parse.Object.extend("CommentObject");

	$("#contactForm").on("submit", function(e) {
		e.preventDefault();

		console.log("Handling the submit");
		//add error handling here
		//gather the form data

		if $("#name").val() != "" && $("#email").val() != "" {
			var data = {};
			data.name = $("#name").val();
			data.email = $("#email").val();
			data.phone = $("#phone").val();
			data.comments = $("#message").val();

			var comment = new CommentObject();
			comment.save(data, {
				success:function() {
					console.log("Success");
					//Alerts are lame - but quick and easy
					alert("Thanks for filling the form!");
				},
				error:function(e) {
					console.dir(e);
				}
			});
		} else {
			alert("Please enter your name and email!");
			console.log("Fail");
		}

	});

});
<|endoftext|>


<commit_before>/* TODO:
- fix mandats repris
- filter time (from bottom histo?)
- handle current mps only?
- by group?
*/
(function (ns){

  ns.ind = "semaines_presence";
  ns.indicateurs = [,
    ["semaines_presence", "Semaines d'activité"],
    ["commission_presences", "Commissions — réunions"],
    ["commission_interventions", "Commissions — interventions"],
    ["hemicycle_interventions", "Hémicycle — interventions longues"],
    ["hemicycle_interventions_courtes", "Hémicycle — interventions courtes"],
    ["amendements_signes", "Amendements signés"],
    ["amendements_adoptes", "Amendements adoptés"],
    ["rapports", "Rapports"],
    ["propositions_ecrites", "Propositions de loi écrites"],
    ["propositions_signees", "Propositions de loi signées"],
    ["questions_orales", "Questions orales"],
    ["questions_ecrites", "Questions écrites"]
  ];

  ns.accentMap = {
    "á": "a", "à": "a", "â": "a",
    "é": "e", "è": "e", "ê": "e", "ë": "e",
    "ç": "c",
    "î": "i", "ï": "i",
    "ô": "o", "ö": "o",
    "ù": "u", "û": "u", "ü": "u"
  };
  ns.clean_accents = function(term){
    var ret = "";
    for (var i = 0; i < term.length; i++)
      ret += ns.accentMap[term.charAt(i)] || term.charAt(i);
    return ret;
  };

  ns.readdate = function(d){
    return d ? d3.time.format("%Y-%m-%d").parse(d) : new Date();
  };
  ns.fmtfloat = function(f){
    return d3.format(".1f")(f).replace('.', ',');
  };

  ns.deputes = {};
  ns.downloadDeputes = function(){
    d3.json("http://www.nosdeputes.fr/deputes/json", function(error, data){
      data.deputes.forEach(function(d){
        d.depute.months = (ns.readdate(d.depute.mandat_fin) - ns.readdate(d.depute.mandat_debut)) / 2628000000;
        if (ns.deputes[d.depute.id] == undefined)
          ns.deputes[d.depute.id] = d.depute;
        else for (var key in d.depute)
          ns.deputes[d.depute.id][key] = d.depute[key];
        ns.deputes[d.depute.id].photo = (d.depute.url_nosdeputes + '/100')
          .replace('.fr/', '.fr/depute/photo/');
      });
    });
  };

  ns.allmonths = [];
  ns.downloadMonthApi = function(start, timeout, last){
    var m = "20" + start[1] +
            (String(start[0]).length < 2 ? "0" : "") + start[0];
    ns.allmonths.push(m);
    setTimeout(function(){
      d3.json("http://www.nosdeputes.fr/synthese/"+m+"/json", function(e, data){
        data.deputes.forEach(function(d){
          if (ns.deputes[d.depute.id] == undefined)
            ns.deputes[d.depute.id] = {};
          Object.keys(d.depute).forEach(function(k){
            if (k != "id" && k != "nom" && k != "groupe") {
              if (ns.deputes[d.depute.id][k] == undefined)
                ns.deputes[d.depute.id][k] = {
                  total: 0,
                  months: {}
                };
              var v = parseInt(d.depute[k]);
              ns.deputes[d.depute.id][k].total += v;
              ns.deputes[d.depute.id][k].months[m] = v;
            }
          });
        });
        // Enable interface after last load
        if (last) {
          ns.deputesAr = Object.keys(ns.deputes).map(function(d){
            return ns.deputes[d];
          });
          ns.dep = ns.deputesAr[parseInt(Math.random() * ns.deputesAr.length)];
          ns.buildSelectMenu();
        }
      });
    }, timeout);
  };

  ns.downloadSynthese = function(){
    var timeout = 0,
        start = [6, 12],
        end = [(new Date()).getMonth() + 1, (new Date()).getFullYear() - 2000];
    while (start[0] != end[0] || start[1] != end[1]) {
      ns.downloadMonthApi(start, timeout);
      if (start[0] == 12)
        start = [1, start[1]+1];
      else start[0]++;
      timeout += 110;
    }
    ns.downloadMonthApi(start, timeout, true);
  };

  ns.buildSelectMenu = function(){
    $("#deputes").autocomplete({
      source: function(request, response){
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(ns.clean_accents(request.term)), "i");
        response($.grep(
          ns.deputesAr.sort(function(a, b){
            return d3.ascending(a.nom_de_famille, b.nom_de_famille);
          }).map(function(d){
            var name = d.nom_de_famille + ' ' + d.prenom +
                     ' (' + d.groupe_sigle + ')';
            return {
              label: name,
              value: name,
              dep: d
            };
          }),
          function(d){
            return matcher.test(ns.clean_accents(d.label));
          }
        ));
      },
      select: function(event, ui){
        event.preventDefault();
        ns.dep = ui.item.dep;
        ns.displayMP();
      }
    });

    $("#loader").hide();
    $("#content").show();
    ns.displayMP();
  };

  ns.displayMP = function(){
    $("#name").text(ns.dep.prenom + ' ' + ns.dep.nom_de_famille +
      ' (' + ns.dep.groupe_sigle + ')');
    d3.select("#data").html("")
      .append("table")
      .append("tbody")
      .html("
	total	moyenne
mensuelle
")
      .selectAll("tr")
      .data(ns.indicateurs)
      .enter().append('tr')
      .attr('class', 'ind')
      .html(function(d) {
        return '' + d[1] + "	" +
               '' + (ns.dep[d[0]] ? ns.dep[d[0]].total : 0) + "	" +
               '' + (ns.dep[d[0]] ? ns.fmtfloat(ns.dep[d[0]].total / ns.dep.months) : 0) + "	";
      })
      .on("click", function(d){
        ns.ind = d[0];
        $('#data table tr.ind').css("background-color", "white");
        $(this).css("background-color", "yellow");
        ns.drawComparison();
        ns.drawTimeline();
      });
    $("#photo").html(
      '' +
      '' +
      '
NosDéputés.fr' +
      '
' + ns.fmtfloat(ns.dep.months) + ' mois de mandat'
    );
    $("#data table tr")[1].click();
  };

  ns.drawComparison = function(monthly){
    var accessindic = function(d){
        return d[ns.ind] ? d[ns.ind].total / (monthly ? d.months : 1) : 0;
      },
      min = d3.min(ns.deputesAr, accessindic),
      max = d3.max(ns.deputesAr, accessindic),
      data = d3.layout.histogram()
        .bins(
          d3.scale.linear()
          .domain([min, max])
          .range([0, 280])
          .ticks(Math.min(Math.round(max - min), 10))
        )(ns.deputesAr.map(accessindic))
        .reverse();

    nv.addGraph(function(){
      var chart = nv.models.multiBarHorizontalChart()
        .x(function(d) { return d.x + " -> " + (d.x + d.dx) })
        .y(function(d) { return Math.sqrt(d.y) })
        .barColor(function(d){
          var depval = accessindic(ns.dep);
          return (depval >= d.x && depval < d.x + d.dx) ? "#00FF00" : "#4444FF";
        })
        .margin({top: 10, right: 20, bottom: 5, left: 110})
        .showYAxis(false)
        .showLegend(false)
        .showControls(false)
        .showValues(true)
        .valueFormat(function(d){
          var real = parseInt(d * d);
          return real + " député" + (real > 1 ? "s" : "");
        });

      d3.select('#comparison svg').html('')
        .datum([
          {key: ' ', values: data}
        ])
        .transition().duration(350)
        .call(chart);

      nv.utils.windowResize(chart.update);
    });
  };

  ns.drawTimeline = function(){
    var data = [], start = false;
    ns.allmonths.forEach(function(d){
      if (ns.dep[ns.ind] != undefined) {
        if (!start && d > ns.dep.mandat_debut.replace(/-/g, '')) start = true;
        if (start)
          data.push({ label: d, value: ns.dep[ns.ind] ? ns.dep[ns.ind].months[d] : 0 });
      } else if (start && (!ns.dep.mandat_fin || d < ns.dep.mandat_fin.replace(/-/g, '')))
        data.push({ label: d, value: 0 });
    });

    $('#timeline svg').empty();
    nv.addGraph(function(){
      var chart = nv.models.discreteBarChart()
        .x(function(d){ return d.label })
        .y(function(d){ return d.value })
        .staggerLabels(true)
        .tooltips(false)
        .showValues(true)
        .valueFormat(function(d){ return parseInt(d) });
      chart.xAxis.tickFormat(function(d){ return d.replace(/^20(..)/, "$1/") });

      d3.select('#timeline svg')
        .datum([
          {key: ' ', values: data}
        ])
        .transition().duration(350)
        .call(chart);
      $("g text:contains(NaN)").remove();
      nv.utils.windowResize(chart.update);
    });
  };

  ns.init = function(){
    ns.downloadDeputes();
    ns.downloadSynthese();
    $("input[name=stats]").change(function(d){
      console.log(d, this);
      ns.drawComparison($(this).val() === "month");
    });
  };

  $(document).ready(ns.init);

})(window.synthese = window.synthese || {});
<commit_msg>keep option<commit_after>/* TODO:
- fix mandats repris
- filter time (from bottom histo?)
- handle current mps only?
- by group?
*/
(function (ns){

  ns.ind = "semaines_presence";
  ns.indicateurs = [,
    ["semaines_presence", "Semaines d'activité"],
    ["commission_presences", "Commissions — réunions"],
    ["commission_interventions", "Commissions — interventions"],
    ["hemicycle_interventions", "Hémicycle — interventions longues"],
    ["hemicycle_interventions_courtes", "Hémicycle — interventions courtes"],
    ["amendements_signes", "Amendements signés"],
    ["amendements_adoptes", "Amendements adoptés"],
    ["rapports", "Rapports"],
    ["propositions_ecrites", "Propositions de loi écrites"],
    ["propositions_signees", "Propositions de loi signées"],
    ["questions_orales", "Questions orales"],
    ["questions_ecrites", "Questions écrites"]
  ];

  ns.accentMap = {
    "á": "a", "à": "a", "â": "a",
    "é": "e", "è": "e", "ê": "e", "ë": "e",
    "ç": "c",
    "î": "i", "ï": "i",
    "ô": "o", "ö": "o",
    "ù": "u", "û": "u", "ü": "u"
  };
  ns.clean_accents = function(term){
    var ret = "";
    for (var i = 0; i < term.length; i++)
      ret += ns.accentMap[term.charAt(i)] || term.charAt(i);
    return ret;
  };

  ns.readdate = function(d){
    return d ? d3.time.format("%Y-%m-%d").parse(d) : new Date();
  };
  ns.fmtfloat = function(f){
    return d3.format(".1f")(f).replace('.', ',');
  };

  ns.deputes = {};
  ns.downloadDeputes = function(){
    d3.json("http://www.nosdeputes.fr/deputes/json", function(error, data){
      data.deputes.forEach(function(d){
        d.depute.months = (ns.readdate(d.depute.mandat_fin) - ns.readdate(d.depute.mandat_debut)) / 2628000000;
        if (ns.deputes[d.depute.id] == undefined)
          ns.deputes[d.depute.id] = d.depute;
        else for (var key in d.depute)
          ns.deputes[d.depute.id][key] = d.depute[key];
        ns.deputes[d.depute.id].photo = (d.depute.url_nosdeputes + '/100')
          .replace('.fr/', '.fr/depute/photo/');
      });
    });
  };

  ns.allmonths = [];
  ns.downloadMonthApi = function(start, timeout, last){
    var m = "20" + start[1] +
            (String(start[0]).length < 2 ? "0" : "") + start[0];
    ns.allmonths.push(m);
    setTimeout(function(){
      d3.json("http://www.nosdeputes.fr/synthese/"+m+"/json", function(e, data){
        data.deputes.forEach(function(d){
          if (ns.deputes[d.depute.id] == undefined)
            ns.deputes[d.depute.id] = {};
          Object.keys(d.depute).forEach(function(k){
            if (k != "id" && k != "nom" && k != "groupe") {
              if (ns.deputes[d.depute.id][k] == undefined)
                ns.deputes[d.depute.id][k] = {
                  total: 0,
                  months: {}
                };
              var v = parseInt(d.depute[k]);
              ns.deputes[d.depute.id][k].total += v;
              ns.deputes[d.depute.id][k].months[m] = v;
            }
          });
        });
        // Enable interface after last load
        if (last) {
          ns.deputesAr = Object.keys(ns.deputes).map(function(d){
            return ns.deputes[d];
          });
          ns.dep = ns.deputesAr[parseInt(Math.random() * ns.deputesAr.length)];
          ns.buildSelectMenu();
        }
      });
    }, timeout);
  };

  ns.downloadSynthese = function(){
    var timeout = 0,
        start = [6, 12],
        end = [(new Date()).getMonth() + 1, (new Date()).getFullYear() - 2000];
    while (start[0] != end[0] || start[1] != end[1]) {
      ns.downloadMonthApi(start, timeout);
      if (start[0] == 12)
        start = [1, start[1]+1];
      else start[0]++;
      timeout += 110;
    }
    ns.downloadMonthApi(start, timeout, true);
  };

  ns.buildSelectMenu = function(){
    $("#deputes").autocomplete({
      source: function(request, response){
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(ns.clean_accents(request.term)), "i");
        response($.grep(
          ns.deputesAr.sort(function(a, b){
            return d3.ascending(a.nom_de_famille, b.nom_de_famille);
          }).map(function(d){
            var name = d.nom_de_famille + ' ' + d.prenom +
                     ' (' + d.groupe_sigle + ')';
            return {
              label: name,
              value: name,
              dep: d
            };
          }),
          function(d){
            return matcher.test(ns.clean_accents(d.label));
          }
        ));
      },
      select: function(event, ui){
        event.preventDefault();
        ns.dep = ui.item.dep;
        ns.displayMP();
      }
    });

    $("#loader").hide();
    $("#content").show();
    ns.displayMP();
  };

  ns.displayMP = function(){
    $("#name").text(ns.dep.prenom + ' ' + ns.dep.nom_de_famille +
      ' (' + ns.dep.groupe_sigle + ')');
    d3.select("#data").html("")
      .append("table")
      .append("tbody")
      .html("
	total	moyenne
mensuelle
")
      .selectAll("tr")
      .data(ns.indicateurs)
      .enter().append('tr')
      .attr('class', 'ind')
      .html(function(d) {
        return '' + d[1] + "	" +
               '' + (ns.dep[d[0]] ? ns.dep[d[0]].total : 0) + "	" +
               '' + (ns.dep[d[0]] ? ns.fmtfloat(ns.dep[d[0]].total / ns.dep.months) : 0) + "	";
      })
      .on("click", function(d){
        ns.ind = d[0];
        $('#data table tr.ind').css("background-color", "white");
        $(this).css("background-color", "yellow");
        ns.drawComparison();
        ns.drawTimeline();
      });
    $("#photo").html(
      '' +
      '' +
      '
NosDéputés.fr' +
      '
' + ns.fmtfloat(ns.dep.months) + ' mois de mandat'
    );
    $("#data table tr")[1].click();
  };

  ns.drawComparison = function(){
    var monthly = $("input[name=stats]:checked").val() === "month",
      accessindic = function(d){
        return d[ns.ind] ? d[ns.ind].total / (monthly ? d.months : 1) : 0;
      },
      min = d3.min(ns.deputesAr, accessindic),
      max = d3.max(ns.deputesAr, accessindic),
      data = d3.layout.histogram()
        .bins(
          d3.scale.linear()
          .domain([min, max])
          .range([0, 280])
          .ticks(Math.min(Math.round(max - min), 10))
        )(ns.deputesAr.map(accessindic))
        .reverse();

    nv.addGraph(function(){
      var chart = nv.models.multiBarHorizontalChart()
        .x(function(d) { return d.x + " -> " + (d.x + d.dx) })
        .y(function(d) { return Math.sqrt(d.y) })
        .barColor(function(d){
          var depval = accessindic(ns.dep);
          return (depval >= d.x && depval < d.x + d.dx) ? "#00FF00" : "#4444FF";
        })
        .margin({top: 10, right: 20, bottom: 5, left: 110})
        .showYAxis(false)
        .showLegend(false)
        .showControls(false)
        .showValues(true)
        .valueFormat(function(d){
          var real = parseInt(d * d);
          return real + " député" + (real > 1 ? "s" : "");
        });

      d3.select('#comparison svg').html('')
        .datum([
          {key: ' ', values: data}
        ])
        .transition().duration(350)
        .call(chart);

      nv.utils.windowResize(chart.update);
    });
  };

  ns.drawTimeline = function(){
    var data = [], start = false;
    ns.allmonths.forEach(function(d){
      if (ns.dep[ns.ind] != undefined) {
        if (!start && d > ns.dep.mandat_debut.replace(/-/g, '')) start = true;
        if (start)
          data.push({ label: d, value: ns.dep[ns.ind] ? ns.dep[ns.ind].months[d] : 0 });
      } else if (start && (!ns.dep.mandat_fin || d < ns.dep.mandat_fin.replace(/-/g, '')))
        data.push({ label: d, value: 0 });
    });

    $('#timeline svg').empty();
    nv.addGraph(function(){
      var chart = nv.models.discreteBarChart()
        .x(function(d){ return d.label })
        .y(function(d){ return d.value })
        .staggerLabels(true)
        .tooltips(false)
        .showValues(true)
        .valueFormat(function(d){ return parseInt(d) });
      chart.xAxis.tickFormat(function(d){ return d.replace(/^20(..)/, "$1/") });

      d3.select('#timeline svg')
        .datum([
          {key: ' ', values: data}
        ])
        .transition().duration(350)
        .call(chart);
      $("g text:contains(NaN)").remove();
      nv.utils.windowResize(chart.update);
    });
  };

  ns.init = function(){
    ns.downloadDeputes();
    ns.downloadSynthese();
    $("input[name=stats]").change(function(d){
      console.log(d, this);
      ns.drawComparison();
    });
  };

  $(document).ready(ns.init);

})(window.synthese = window.synthese || {});
<|endoftext|>


<commit_before>/* global Trello, jQuery, TrelloPowerUp */
var SHARE_ICON = './images/fa-share-alt.svg';
var PRINTER_URL = 'https://awolf81.github.io/TrelloPrinter/?url=';

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

function postJSON(data) {
    return $.ajax('https://jsonblob.com/api/jsonBlob', {
    	method: 'POST',
        crossDomain: true,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

var cardButtonCallback = function(t) {
    return t.card('all')
    .then(function(promiseResult) {
      console.log(promiseResult);
      var url = promiseResult.url;
      return t.popup({
          title: 'Share this card',
          items: [
              {
                text: 'Share card: ' + url,
                url: url,
                callback: function(t){
                  return postJSON(promiseResult).then(
                      function(res, status, jqXHR) {
                          var sharedURL  = jqXHR.getResponseHeader('Location');
                          return t.attach({
                              url: PRINTER_URL + sharedURL,
                              name: 'Shared JSON'

                          })
                          .then(function(){
                            return t.closePopup();
                          })
                      },
                      function(err) {
                          console.log(err); // todo --> show notifcation
                      }
                  )
                }
              }
          ]
      });
    });
}

// share board or panel
function shareCallback(type, t) {
    console.log(window.location.href, t);
    return t.cards('all').then(function(promiseResult) {
            //t.get('/batch/?urls=/boards/' + id +
            //    '/,/boards/'+ id +'/cards').then(function(promiseResult) {
            // always load board data --> needed to post or display selection
            /*console.log(promiseResult);
            data = promiseResult.map(function(item) {
                return item['200']; // status is the key of each item
            });*/

            if (type === 'board') {
                return postJSON(promiseResult).then(function(res, status, jqXHR) {
                    var sharedURL  = jqXHR.getResponseHeader('Location');
                    return t.popup({
                        //url: PRINTER_URL + sharedURL, // url loads html into the popup
                        title: 'Shared board successfully',
                        items: [
                            {
                                text: 'Open share',
                                callback: function(t) {
                                    openInNewTab(PRINTER_URL + sharedURL),
                                    t.closePopup();
                                }
                            },
                            {
                                text: 'Copy URL to clipboard',
                                callback: function(t) {
                                    window.prompt("Copy to clipboard: Ctrl+C, Enter", PRINTER_URL + sharedURL);
                                    t.closePopup();
                                }
                            }
                        ]
                    })
                    /*.then(function(){
                      return t.closePopup();
                  })*/
                },
                function(err) {
                    console.log(err); // todo --> show notifcation
                });
            }
            else {
                // load board bar and display checkboxes with panels to export
                return t.boardBar({
                    url: './board-bar.html',
                    height: 200
                })
                .then(function(){
                    return t.closePopup();
                });
            }
        });
}

// wrapper functions for sharing
var shareBoard = function(t) {
    return shareCallback('board', t);
};

var sharePanel = function(t) {
    return shareCallback('panel', t);
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Share board or panel',
    items: [
        {
            text: 'Board',
            callback: shareBoard
        },
        {
            text: 'Panel',
            callback: sharePanel
        }
    ]
      /*{
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]*/
  });
};

TrelloPowerUp.initialize({
  'card-buttons': function(t, options) {
    return [{
      icon: SHARE_ICON,
      text: 'Share',
      callback: cardButtonCallback
    }];
  },
  'board-buttons': function(t, options){
    return [{
      icon: SHARE_ICON,
      text: 'Share board or panel',
      callback: boardButtonCallback
    }];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>lists query.<commit_after>/* global Trello, jQuery, TrelloPowerUp */
var SHARE_ICON = './images/fa-share-alt.svg';
var PRINTER_URL = 'https://awolf81.github.io/TrelloPrinter/?url=';

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

function postJSON(data) {
    return $.ajax('https://jsonblob.com/api/jsonBlob', {
    	method: 'POST',
        crossDomain: true,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

var cardButtonCallback = function(t) {
    return t.card('all')
    .then(function(promiseResult) {
      console.log(promiseResult);
      var url = promiseResult.url;
      return t.popup({
          title: 'Share this card',
          items: [
              {
                text: 'Share card: ' + url,
                url: url,
                callback: function(t){
                  return postJSON(promiseResult).then(
                      function(res, status, jqXHR) {
                          var sharedURL  = jqXHR.getResponseHeader('Location');
                          return t.attach({
                              url: PRINTER_URL + sharedURL,
                              name: 'Shared JSON'

                          })
                          .then(function(){
                            return t.closePopup();
                          })
                      },
                      function(err) {
                          console.log(err); // todo --> show notifcation
                      }
                  )
                }
              }
          ]
      });
    });
}

// share board or panel
function shareCallback(type, t) {
    console.log(window.location.href, t);
    //return t.cards('all').then(function(promiseResult) { // gets all cards of board
    return t.lists('all').then(function(promiseResult) {
            //t.get('/batch/?urls=/boards/' + id +
            //    '/,/boards/'+ id +'/cards').then(function(promiseResult) {
            // always load board data --> needed to post or display selection
            /*console.log(promiseResult);
            data = promiseResult.map(function(item) {
                return item['200']; // status is the key of each item
            });*/

            if (type === 'board') {
                return postJSON(promiseResult).then(function(res, status, jqXHR) {
                    var sharedURL  = jqXHR.getResponseHeader('Location');
                    return t.popup({
                        //url: PRINTER_URL + sharedURL, // url loads html into the popup
                        title: 'Shared board successfully',
                        items: [
                            {
                                text: 'Open share',
                                callback: function(t) {
                                    openInNewTab(PRINTER_URL + sharedURL),
                                    t.closePopup();
                                }
                            },
                            {
                                text: 'Copy URL to clipboard',
                                callback: function(t) {
                                    window.prompt("Copy to clipboard: Ctrl+C, Enter", PRINTER_URL + sharedURL);
                                    t.closePopup();
                                }
                            }
                        ]
                    })
                    /*.then(function(){
                      return t.closePopup();
                  })*/
                },
                function(err) {
                    console.log(err); // todo --> show notifcation
                });
            }
            else {
                // load board bar and display checkboxes with panels to export
                return t.boardBar({
                    url: './board-bar.html',
                    height: 200
                })
                .then(function(){
                    return t.closePopup();
                });
            }
        });
}

// wrapper functions for sharing
var shareBoard = function(t) {
    return shareCallback('board', t);
};

var sharePanel = function(t) {
    return shareCallback('panel', t);
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Share board or panel',
    items: [
        {
            text: 'Board',
            callback: shareBoard
        },
        {
            text: 'Panel',
            callback: sharePanel
        }
    ]
      /*{
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]*/
  });
};

TrelloPowerUp.initialize({
  'card-buttons': function(t, options) {
    return [{
      icon: SHARE_ICON,
      text: 'Share',
      callback: cardButtonCallback
    }];
  },
  'board-buttons': function(t, options){
    return [{
      icon: SHARE_ICON,
      text: 'Share board or panel',
      callback: boardButtonCallback
    }];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>


<commit_before>/* global TrelloPowerUp */

var WHITE_ICON = './images/icon-white.svg';
var GRAY_ICON = './images/icon-gray.svg';

var boardButtonCallback = function(t, options) {
  var isAuthenticated = true;

  if (isAuthenticated) {
    return boardButtonCallbackAuthenticated(t, options);
  }
  else {
    return boardButtonCallbackUnauthenticated(t, options);
  }
};

var boardButtonCallbackAuthenticated = function(t, options) {

  // @ToDo
  // Even if user is authenticated, we should know if he has created
  // a slideshow for current viewed trello board.
  // If there is no slideshow for this board,
  // we should show suggestion to create a slideshow

  return t.popup({
    title: 'Screenful',
    items: [
      {
        text: 'Lead Time',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=lead-time',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Sprint Burndown',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=current-sprint',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Release Forecast',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=release-forecast',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Cumulative Flow',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=cumulative-flow',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Completed Tasks',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=task-breakdown',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Go to Screenful.me',
        url: 'https://app.screenful.me/slideshow/demo?screens=task-breakdown'
      },
    ]
  });
};

var boardButtonCallbackUnauthenticated = function(t, options) {
  return t.popup({
    title: "Screenful Authorize",
    url: './overlay.html'
  });
};

TrelloPowerUp.initialize({
  'board-buttons': function(t, options){
    return [{
      icon: WHITE_ICON,
      text: 'Screenful',
      callback: boardButtonCallback
    }];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>Update external url<commit_after>/* global TrelloPowerUp */

var WHITE_ICON = './images/icon-white.svg';
var GRAY_ICON = './images/icon-gray.svg';

var boardButtonCallback = function(t, options) {
  var isAuthenticated = true;

  if (isAuthenticated) {
    return boardButtonCallbackAuthenticated(t, options);
  }
  else {
    return boardButtonCallbackUnauthenticated(t, options);
  }
};

var boardButtonCallbackAuthenticated = function(t, options) {

  // @ToDo
  // Even if user is authenticated, we should know if he has created
  // a slideshow for current viewed trello board.
  // If there is no slideshow for this board,
  // we should show suggestion to create a slideshow

  return t.popup({
    title: 'Screenful',
    items: [
      {
        text: 'Lead Time',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=lead-time',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Sprint Burndown',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=current-sprint',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Release Forecast',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=release-forecast',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Cumulative Flow',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=cumulative-flow',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Completed Tasks',
        callback: function(t){
          return t.overlay({
            url: 'https://app.screenful.me/slideshow/demo?screens=task-breakdown',
            width: 960,
            height: 540
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Go to Screenful.me',
        url: 'http://screenful.me'
      },
    ]
  });
};

var boardButtonCallbackUnauthenticated = function(t, options) {
  return t.popup({
    title: "Screenful Authorize",
    url: './overlay.html'
  });
};

TrelloPowerUp.initialize({
  'board-buttons': function(t, options){
    return [{
      icon: WHITE_ICON,
      text: 'Screenful',
      callback: boardButtonCallback
    }];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>


<commit_before>(function($){

    //====================== Timeline class ================================

    window.Timeline = function(cont, ops) {
        var root = $(cont);

        this.cont      = root;
        this.duration  = ops.duration;
        this['px/sec'] = ops.width / ops.duration;
        this.tags      = [];
        this.tagTpl    = root.find('.tag').detach();
        this.frameTpl  = root.find('.frame').detach();
        this.pointer   = root.find('.pointer');

        root.css('width', ops.width + 'px');

        this.resetFrames(ops.framesNumber);
        this.goTo(0);

        if( ops.tags ) {
            for(var i = 0; i < ops.tags.length; i++) {
                this.addTag(ops.tags[i]);
            }
        }

        root.data('timeline', this);
    };
    Timeline.prototype.getRootNode = function(){
        return this.cont;
    };
    Timeline.prototype.goToNextSecond = function(){
        this.pointer.css('left', '+=' + this['px/sec']);
        return this;
    };
    Timeline.prototype.goToPrevSecond = function(){
        this.pointer.css('left', '-=' + this['px/sec']);
        return this;
    };
    Timeline.prototype.goTo = function(sec){
        this.pointer.css('left', sec * this['px/sec'] + 'px');
        return this;
    };
    Timeline.prototype.addTag = function(tag){
        if( tag instanceof TimelineTag == false ) {
            tag['px/sec'] = this['px/sec'];
            tag.tpl = this.tagTpl.clone();
            tag = new TimelineTag(tag);
        }

        tag.addTo(this);

        this.tags.push(tag);

        return this;
    };
    Timeline.prototype.getTags = function(){
        return this.tags;
    };
    Timeline.prototype.resetFrames = function(framesNumber){
        this.cont.find('.frame').remove();
        if( ! framesNumber ) return;

        var pxSec    = this['px/sec'],
            frames   = this.cont.find('.frames'),
            secFrame = this.duration / (framesNumber - 1);

        secFrame = secFrame - secFrame % 5;

        for(var i = 0; i <= this.duration; i += secFrame) {
            this.frameTpl.clone()
                .appendTo(frames)
                .css('left', i * pxSec + 'px')
                .find('.time').html(this.formatTime(i))
            ;
        }

        if( this.duration % secFrame > 0 ) {
            this.frameTpl.clone()
                .appendTo(frames)
                .css('left', this.duration * pxSec + 'px')
            ;
        }
    };
    Timeline.prototype.formatTime = function(seconds){
        function pad(num, size) {
            num = "" + num;
            var s = "000000000" + num;
            return num.length < size ? s.substr(s.length - size) : num;
        }

        var $m = Math.floor(seconds / 60),
            $s = seconds % 60;
        return pad($m, 2) + ':' + pad($s, 2);
    };

    //====================== TimelineTag class =============================

    window.TimelineTag = function(ops){
        this.title  = '';
        this.start  = 0;
        this.length = 1;
        this.line   = null;
        this['px/sec'] = ops['px/sec'];

        var root = $(ops.tpl);
        this.getRootNode = function(){
            return root;
        };

        root.data('tag', this);

        this
            .setTitle(ops.title)
            .setStart(ops.start   || this.start)
            .setLength(ops.length || this.length)
        ;
    };
    TimelineTag.prototype.addTo = function(timeline){
        this.getRootNode().appendTo(
            timeline.cont.find('.tags-lines li').first()
        );

        this.setLine(this.getFreeLine());

        if( ! this.getRootNode().data('initDnD') ) {
            this.getRootNode()
                .draggable({
                    containment: '.tags-lines',
                    axis:        "x",
                    zIndex:      1000,
                    start:       onStart,
                    drag:        onDrag,
                    stop:        onStop
                })
                .resizable({
                    containment: '.tags-lines',
                    handles:     "e",
                    start:       onStart,
                    resize:      onDrag,
                    stop:        onStop
                })
            ;
            this.getRootNode().data('initDnD', true);
        }
    };
    TimelineTag.prototype.setTitle = function(title){
        this.getRootNode().find('.title').html(this.title = title);
        return this;
    };
    TimelineTag.prototype.setStart = function(start){
        this.getRootNode().css('left', (this.start = start) * this['px/sec'] + 'px');
        this.setLine(this.getFreeLine());
        return this;
    };
    TimelineTag.prototype.setLength = function(length){
        this.getRootNode().css('width', (this.length = length) * this['px/sec'] + 'px');
        this.setLine(this.getFreeLine());
        return this;
    };
    TimelineTag.prototype.setLine = function(line){
        if( this.line === line ) return this;

        var lines = this.getRootNode().closest('.tags-lines');

        for(var i = lines.find('li').length; i <= line; i++) {
            lines.append('
');
        }

        this.getRootNode().appendTo( lines.find('li').eq(this.line = line) );

        return this;
    };
    TimelineTag.prototype.getFreeLine = function(){
        var lines = this.getRootNode().closest('.tags-lines');

        return getTagFreeLine(this.getRootNode(), lines.find('.tag'));
    };

    //====================== jQuery plugin =================================

    $.fn.timeline = function(ops){
        if( typeof ops === 'string' ) {
            var args = Array.prototype.slice.call(arguments, 1);

            if( ops.substr(0, 3) === 'get' ) {
                var timeline = this.data('timeline');
                return timeline[ops].apply(timeline, args);
            }

            return this.each(function(){
                var timeline = $(this).data('timeline');
                timeline[ops].apply(timeline, args);
            });
        }

        ops = $.extend({
            width: 600,
            duration: 1,
            framesNumber: 0
        }, ops || {});

        return this.each(function(){
            new Timeline(this, ops);
        });
    };

    //====================== Helpers =======================================

    var helper, helperLine, curTag, tagsList, tagsLines, linesCount, fakeLine;

    function onStart(e, ui){
        curTag = ui.helper;

        helper = curTag.clone()
            .appendTo(curTag.closest('.tags-lines').find('li').first())
            .addClass('helper')
        ;

        tagsLines  = curTag.closest('.tags-lines');
        tagsList   = tagsLines.find('.tag').not(helper);
        linesCount = tagsLines.find('li').length - 1;
        helperLine = 0;
        fakeLine   = false;
    }

    function onDrag(){
        var tag = curTag.data('tag');
        tag.start  = parseInt(curTag.css('left'))  / tag['px/sec'];
        tag.length = parseInt(curTag.css('width')) / tag['px/sec'];

        helperLine = getTagFreeLine(curTag, tagsList);

        if( helperLine == curTag.data('tag').line ) {
            helper.hide();
        }
        else {
            helper
                .css(curTag.css(['left', 'width']))
                .css('top', 30 * helperLine + 'px')
                .show()
            ;
        }

        if( helperLine > linesCount && ! fakeLine ) {
            tagsLines.append('
');
            fakeLine = true;
        }
        else if(helperLine <= linesCount && fakeLine) {
            tagsLines.find('li').last().remove();
            fakeLine = false;
        }
    }

    function onStop(){
        curTag.data('tag').setLine(helperLine);

        helper.remove();

        tagsLines.find('li').not(':first').find('.tag').not(curTag).each(function(){
            var $this = $(this);
            $this.data('tag').setLine( getTagFreeLine($this, tagsList) );
        });

        var lastLi = tagsLines.find('li').last();
        if( lastLi.children().length == 0 ) {
            lastLi.remove();
        }
    }

    var getTagFreeLine = (function(){
        var dummy = $('
').css('opacity', 0);

        function moveHelperOnFreeLine(elem, list, line) {
            for(var i = 0; i < list.length; i++) {
                if( overlaps(elem, list[i]) ) {
                    elem.css('top', 30 * ++line + 'px');
                    return moveHelperOnFreeLine(elem, list, line);
                }
            }

            return line;
        }

        var overlaps = (function(){
            function getPositions(elem) {
                var rect = $(elem).get(0).getBoundingClientRect();
                return [ [ rect.left, rect.left + rect.width ], [ rect.top, rect.top + rect.height ] ];
            }

            function comparePositions(p1, p2) {
                var r1 = p1[0] < p2[0] ? p1 : p2,
                    r2 = p1[0] < p2[0] ? p2 : p1;
                return r1[1] > r2[0] || r1[0] === r2[0];
            }

            return function (a, b) {
                var pos1 = getPositions(a),
                    pos2 = getPositions(b);
                return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
            };
        })();

        return function(tag, list){
            if( list.length === 0 ) return 0;

            dummy
                .appendTo(list.eq(0).closest('ul').children().first())
                .css(tag.css(['left', 'width']))
                .css('top', '0px')
            ;

            var line = moveHelperOnFreeLine(dummy, list.not(tag), 0);

            dummy.detach();

            return line;
        }
    })();

})(jQuery);<commit_msg>v 0.2.1<commit_after>(function($){

    //====================== Timeline class ================================

    window.Timeline = function(cont, ops) {
        var root = $(cont);

        this.cont      = root;
        this.duration  = ops.duration;
        this['px/sec'] = ops.width / ops.duration;
        this.tags      = [];
        this.tagTpl    = root.find('.tag').detach();
        this.frameTpl  = root.find('.frame').detach();
        this.pointer   = root.find('.pointer');
        this.currentSecond = 1;

        root.css('width', ops.width + 'px');

        this.resetFrames(ops.framesNumber);
        this.goTo(0);

        if( ops.tags ) {
            for(var i = 0; i < ops.tags.length; i++) {
                this.addTag(ops.tags[i]);
            }
        }

        root.data('timeline', this);
    };
    Timeline.prototype.getRootNode = function(){
        return this.cont;
    };
    Timeline.prototype.goTo = function(sec){
        if( this.currentSecond != sec ) {
            this.pointer.css('left', sec * this['px/sec'] + 'px');
            this.currentSecond = sec;
        }
        return this;
    };
    Timeline.prototype.goToNextSecond = function(){
        this.goTo(this.currentSecond + 1);
        return this;
    };
    Timeline.prototype.goToPrevSecond = function(){
        this.goTo(this.currentSecond - 1);
        return this;
    };
    Timeline.prototype.addTag = function(tag){
        if( tag instanceof TimelineTag == false ) {
            tag['px/sec'] = this['px/sec'];
            tag.tpl = this.tagTpl.clone();
            tag = new TimelineTag(tag);
        }

        tag.addTo(this);

        this.tags.push(tag);

        return this;
    };
    Timeline.prototype.getTags = function(){
        return this.tags;
    };
    Timeline.prototype.resetFrames = function(framesNumber){
        this.cont.find('.frame').remove();
        if( ! framesNumber ) return;

        var pxSec    = this['px/sec'],
            frames   = this.cont.find('.frames'),
            secFrame = this.duration / (framesNumber - 1);

        secFrame = secFrame - secFrame % 5;

        for(var i = 0; i <= this.duration; i += secFrame) {
            this.frameTpl.clone()
                .appendTo(frames)
                .css('left', i * pxSec + 'px')
                .find('.time').html(this.formatTime(i))
            ;
        }

        if( this.duration % secFrame > 0 ) {
            this.frameTpl.clone()
                .appendTo(frames)
                .css('left', this.duration * pxSec + 'px')
            ;
        }
    };
    Timeline.prototype.formatTime = function(seconds){
        function pad(num, size) {
            num = "" + num;
            var s = "000000000" + num;
            return num.length < size ? s.substr(s.length - size) : num;
        }

        var $m = Math.floor(seconds / 60),
            $s = seconds % 60;
        return pad($m, 2) + ':' + pad($s, 2);
    };

    //====================== TimelineTag class =============================

    window.TimelineTag = function(ops){
        this.title  = '';
        this.start  = 0;
        this.length = 1;
        this.line   = null;
        this['px/sec'] = ops['px/sec'];

        var root = $(ops.tpl);
        this.getRootNode = function(){
            return root;
        };

        root.data('tag', this);

        this
            .setTitle(ops.title)
            .setStart(ops.start   || this.start)
            .setLength(ops.length || this.length)
        ;
    };
    TimelineTag.prototype.addTo = function(timeline){
        this.getRootNode().appendTo(
            timeline.cont.find('.tags-lines li').first()
        );

        this.setLine(this.getFreeLine());

        if( ! this.getRootNode().data('initDnD') ) {
            this.getRootNode()
                .draggable({
                    containment: '.tags-lines',
                    axis:        "x",
                    zIndex:      1000,
                    start:       onStart,
                    drag:        onDrag,
                    stop:        onStop
                })
                .resizable({
                    containment: '.tags-lines',
                    handles:     "e",
                    start:       onStart,
                    resize:      onDrag,
                    stop:        onStop
                })
            ;
            this.getRootNode().data('initDnD', true);
        }
    };
    TimelineTag.prototype.setTitle = function(title){
        this.getRootNode().find('.title').html(this.title = title);
        return this;
    };
    TimelineTag.prototype.setStart = function(start){
        this.getRootNode().css('left', (this.start = start) * this['px/sec'] + 'px');
        this.setLine(this.getFreeLine());
        return this;
    };
    TimelineTag.prototype.setLength = function(length){
        this.getRootNode().css('width', (this.length = length) * this['px/sec'] + 'px');
        this.setLine(this.getFreeLine());
        return this;
    };
    TimelineTag.prototype.setLine = function(line){
        if( this.line === line ) return this;

        var lines = this.getRootNode().closest('.tags-lines');

        for(var i = lines.find('li').length; i <= line; i++) {
            lines.append('
');
        }

        this.getRootNode().appendTo( lines.find('li').eq(this.line = line) );

        return this;
    };
    TimelineTag.prototype.getFreeLine = function(){
        var lines = this.getRootNode().closest('.tags-lines');

        return getTagFreeLine(this.getRootNode(), lines.find('.tag'));
    };

    //====================== jQuery plugin =================================

    $.fn.timeline = function(ops){
        if( typeof ops === 'string' ) {
            var args = Array.prototype.slice.call(arguments, 1);

            if( ops.substr(0, 3) === 'get' ) {
                var timeline = this.data('timeline');
                return timeline[ops].apply(timeline, args);
            }

            return this.each(function(){
                var timeline = $(this).data('timeline');
                timeline[ops].apply(timeline, args);
            });
        }

        ops = $.extend({
            width: 600,
            duration: 1,
            framesNumber: 0
        }, ops || {});

        return this.each(function(){
            new Timeline(this, ops);
        });
    };

    //====================== Helpers =======================================

    var helper, helperLine, curTag, tagsList, tagsLines, linesCount, fakeLine;

    function onStart(e, ui){
        curTag = ui.helper;

        helper = curTag.clone()
            .appendTo(curTag.closest('.tags-lines').find('li').first())
            .addClass('helper')
        ;

        tagsLines  = curTag.closest('.tags-lines');
        tagsList   = tagsLines.find('.tag').not(helper);
        linesCount = tagsLines.find('li').length - 1;
        helperLine = 0;
        fakeLine   = false;
    }

    function onDrag(){
        var tag = curTag.data('tag');
        tag.start  = parseInt(curTag.css('left'))  / tag['px/sec'];
        tag.length = parseInt(curTag.css('width')) / tag['px/sec'];

        helperLine = getTagFreeLine(curTag, tagsList);

        if( helperLine == curTag.data('tag').line ) {
            helper.hide();
        }
        else {
            helper
                .css(curTag.css(['left', 'width']))
                .css('top', 30 * helperLine + 'px')
                .show()
            ;
        }

        if( helperLine > linesCount && ! fakeLine ) {
            tagsLines.append('
');
            fakeLine = true;
        }
        else if(helperLine <= linesCount && fakeLine) {
            tagsLines.find('li').last().remove();
            fakeLine = false;
        }
    }

    function onStop(){
        curTag.data('tag').setLine(helperLine);

        helper.remove();

        tagsLines.find('li').not(':first').find('.tag').not(curTag).each(function(){
            var $this = $(this);
            $this.data('tag').setLine( getTagFreeLine($this, tagsList) );
        });

        var lastLi = tagsLines.find('li').last();
        if( lastLi.children().length == 0 ) {
            lastLi.remove();
        }
    }

    var getTagFreeLine = (function(){
        var dummy = $('
').css('opacity', 0);

        function moveHelperOnFreeLine(elem, list, line) {
            for(var i = 0; i < list.length; i++) {
                if( overlaps(elem, list[i]) ) {
                    elem.css('top', 30 * ++line + 'px');
                    return moveHelperOnFreeLine(elem, list, line);
                }
            }

            return line;
        }

        var overlaps = (function(){
            function getPositions(elem) {
                var rect = $(elem).get(0).getBoundingClientRect();
                return [ [ rect.left, rect.left + rect.width ], [ rect.top, rect.top + rect.height ] ];
            }

            function comparePositions(p1, p2) {
                var r1 = p1[0] < p2[0] ? p1 : p2,
                    r2 = p1[0] < p2[0] ? p2 : p1;
                return r1[1] > r2[0] || r1[0] === r2[0];
            }

            return function (a, b) {
                var pos1 = getPositions(a),
                    pos2 = getPositions(b);
                return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
            };
        })();

        return function(tag, list){
            if( list.length === 0 ) return 0;

            dummy
                .appendTo(list.eq(0).closest('ul').children().first())
                .css(tag.css(['left', 'width']))
                .css('top', '0px')
            ;

            var line = moveHelperOnFreeLine(dummy, list.not(tag), 0);

            dummy.detach();

            return line;
        }
    })();

})(jQuery);<|endoftext|>


<commit_before>// palette:
// 990033 - red
// 669900 - green
// 0099FF - light blue
// 0033CC - dark blue

var CONTROLS;
var HAVE_POINTER_LOCK = checkForPointerLock();

function checkForPointerLock() {
  return 'pointerLockElement' in document ||
         'mozPointerLockElement' in document ||
         'webkitPointerLockElement' in document;
}

function initPointerLock() {
  var element = document.body;

  if (HAVE_POINTER_LOCK) {
    var pointerlockchange = function(event) {
      if (document.pointerLockElement === element ||
          document.mozPointerLockElement === element ||
          document.webkitPointerLockElement === element) {
        controlsEnabled = true;
        CONTROLS.enabled = true;
      } else {
        controlsEnabled = false;
        CONTROLS.enabled = false;
      }
    };

    var pointerlockerror = function(event) {
      element.innerHTML = 'PointerLock Error';
    };

    document.addEventListener('pointerlockchange', pointerlockchange, false);
    document.addEventListener('mozpointerlockchange', pointerlockchange, false);
    document.addEventListener('webkitpointerlockchange', pointerlockchange, false);

    document.addEventListener('pointerlockerror', pointerlockerror, false);
    document.addEventListener('mozpointerlockerror', pointerlockerror, false);
    document.addEventListener('webkitpointerlockerror', pointerlockerror, false);

    var requestPointerLock = function(event) {
      element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
      element.requestPointerLock();
    };
    element.addEventListener('click', requestPointerLock, false);
  } else {
    element.innerHTML = 'Bad browser; No pointer lock';
  }
}

function choice(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function main() {
  initPointerLock();

  // Set up rendering
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(
    75, window.innerWidth / window.innerHeight, 1, 10000);
  var renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  var stuffDistance = 20;

  // Make a green grass
  var geometry = new THREE.BoxGeometry(10, 1, 10);
  var material = new THREE.MeshLambertMaterial({color: 0x669900});
  var grass = new THREE.Mesh(geometry, material);
  grass.position.set(0, 0, -stuffDistance);
  scene.add(grass);

  // Make a blue ocean
  var geometry = new THREE.BoxGeometry(1000, 1, 1000);
  var material = new THREE.MeshLambertMaterial({color: 0x0033CC});
  var ocean = new THREE.Mesh(geometry, material);
  ocean.position.set(0, -1, -stuffDistance);
  scene.add(ocean);

  // A random brick floating in the air
  var geometry = new THREE.BoxGeometry(1, 1, 1);
  var material = new THREE.MeshLambertMaterial({color: 0x990033});
  var brick = new THREE.Mesh(geometry, material);
  brick.position.set(0, 1, -stuffDistance);
  scene.add(brick);

  // Make a canvas that could have text
  var FONT_SIZE_PX = 40;
  var NUM_LINES = 20;
  var CANVAS_SIZE_PX = NUM_LINES * FONT_SIZE_PX + FONT_SIZE_PX * 0.2;
  var canvas = document.createElement("canvas");
  canvas.width = canvas.height = CANVAS_SIZE_PX;
  var context = canvas.getContext("2d");
  context.font = FONT_SIZE_PX + 'px Inconsolata,monospace';
  context.globalCompositeOperation = 'darker';
  var textMetrics = context.measureText('0');
  var charWidth = textMetrics.width;
  var numCols = Math.floor(CANVAS_SIZE_PX / charWidth);

  // Float it in the air
  var textTexture = new THREE.Texture(canvas);
  textTexture.minFilter = THREE.NearestFilter;
  var textAreaMat = new THREE.MeshBasicMaterial(
    {map: textTexture, side: THREE.DoubleSide});
  textAreaMat.transparent = true;
  var editor = new THREE.Mesh(
    new THREE.PlaneGeometry(10, 10),
    new THREE.MeshBasicMaterial(textAreaMat));
  editor.position.set(0, 10, -stuffDistance);
  editor.rotation.y = 0.1;
  editor.visible = false;
  editor.value = "hello world\nmultiline works\ngo bengals";
  editor.cursor = 0;
  editor.lastValue = "";
  scene.add(editor);

  // Gets its text from the text area
  editor.update = function() {
    if (editor.value == editor.lastValue) {
      return;
    }
    context.clearRect(0, 0, CANVAS_SIZE_PX, CANVAS_SIZE_PX);
    context.fillStyle = 'hsla(0, 0%, 100%, 0.8)';
    context.fillRect(0, 0, CANVAS_SIZE_PX, CANVAS_SIZE_PX);
    editor.lastValue = editor.value;
    var lines = editor.value.split("\n")
    for (var i = 0; i < lines.length; ++i) {
      var line = lines[i];
      context.fillStyle = 'hsl(0, 0%, 25%)';
      context.fillText(line, 0, FONT_SIZE_PX + FONT_SIZE_PX * i);
    }
    textTexture.needsUpdate = true;
  }

  editor.insert = function(text) {
    editor.value = (editor.value.slice(0, editor.cursor) + text +
                    editor.value.slice(editor.cursor));
  }

  // Just a bit of ambient light for convenience
  var ambient = new THREE.AmbientLight(0x333333);
  scene.add(ambient);

  // The main light source is like an arctic sun
  var lightAngle = 0;
  var lightHeight = 300;
  var lightWidth = 400;
  var spotLight = new THREE.SpotLight(0xffffff);
  spotLight.position.set(0, lightHeight, 0);
  scene.add(spotLight);

  // Position camera
  camera.position.x = 0;
  camera.position.y = 3;
  camera.position.z = 0;

  CONTROLS = new THREE.PointerLockControls(camera);
  scene.add(CONTROLS.getObject());

  // An aiming dot
  var geometry = new THREE.BoxGeometry(0.01, 0.01, 0.01);
  var material = new THREE.MeshBasicMaterial({color: 0xFF0000});
  var aimer = new THREE.Mesh(geometry, material);
  aimer.visible = false;
  camera.add(aimer);
  aimer.position.set(0, 0, -1.1);

  // Find the object the aimer is aiming at
  function aimee() {
    var vector = new THREE.Vector3(0, 0, -1);
    vector = camera.localToWorld(vector);
    vector.sub(camera.position);
    // Now vector is a unit vector with the same direction as the camera
    var raycaster = new THREE.Raycaster( camera.position, vector);

    var objects = raycaster.intersectObjects(scene.children);
    if (objects.length == 0) {
      return null;
    }
    return objects[0];
  }

  Mousetrap.bind("shift", function() {
    if (!editor.visible) {
      aimer.visible = true;
    }
  }, "keydown");

  Mousetrap.bind("shift", function() {
    aimer.visible = false;
  }, "keyup");

  Mousetrap.bind("shift+z", function() {
    if (!editor.visible) {
      console.log(aimee());
    }
  });

  // Editor testing
  Mousetrap.bind("e", function() {
    editor.insert("e");
  });

  Mousetrap.bind("shift+t", function() {
    if (!editor.visible) {
      // Displays the text editor for testing
      editor.visible = true;
    }
  });

  Mousetrap.bind("~", function() {
    // Close the text editor
    editor.visible = false;
  });

  // Start rendering
  function render() {
    requestAnimationFrame(render);

    editor.update();

    lightAngle += 0.01;
    spotLight.position.x = Math.cos(lightAngle) * lightWidth;
    spotLight.position.z = Math.sin(lightAngle) * lightWidth;

    renderer.render(scene, camera);
  }
  render();
}

<commit_msg>lots of keys are typable<commit_after>// palette:
// 990033 - red
// 669900 - green
// 0099FF - light blue
// 0033CC - dark blue

var CONTROLS;
var HAVE_POINTER_LOCK = checkForPointerLock();

function checkForPointerLock() {
  return 'pointerLockElement' in document ||
         'mozPointerLockElement' in document ||
         'webkitPointerLockElement' in document;
}

function initPointerLock() {
  var element = document.body;

  if (HAVE_POINTER_LOCK) {
    var pointerlockchange = function(event) {
      if (document.pointerLockElement === element ||
          document.mozPointerLockElement === element ||
          document.webkitPointerLockElement === element) {
        controlsEnabled = true;
        CONTROLS.enabled = true;
      } else {
        controlsEnabled = false;
        CONTROLS.enabled = false;
      }
    };

    var pointerlockerror = function(event) {
      element.innerHTML = 'PointerLock Error';
    };

    document.addEventListener('pointerlockchange', pointerlockchange, false);
    document.addEventListener('mozpointerlockchange', pointerlockchange, false);
    document.addEventListener('webkitpointerlockchange', pointerlockchange, false);

    document.addEventListener('pointerlockerror', pointerlockerror, false);
    document.addEventListener('mozpointerlockerror', pointerlockerror, false);
    document.addEventListener('webkitpointerlockerror', pointerlockerror, false);

    var requestPointerLock = function(event) {
      element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
      element.requestPointerLock();
    };
    element.addEventListener('click', requestPointerLock, false);
  } else {
    element.innerHTML = 'Bad browser; No pointer lock';
  }
}

function choice(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function main() {
  initPointerLock();

  // Set up rendering
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(
    75, window.innerWidth / window.innerHeight, 1, 10000);
  var renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  var stuffDistance = 20;

  // Make a green grass
  var geometry = new THREE.BoxGeometry(10, 1, 10);
  var material = new THREE.MeshLambertMaterial({color: 0x669900});
  var grass = new THREE.Mesh(geometry, material);
  grass.position.set(0, 0, -stuffDistance);
  scene.add(grass);

  // Make a blue ocean
  var geometry = new THREE.BoxGeometry(1000, 1, 1000);
  var material = new THREE.MeshLambertMaterial({color: 0x0033CC});
  var ocean = new THREE.Mesh(geometry, material);
  ocean.position.set(0, -1, -stuffDistance);
  scene.add(ocean);

  // A random brick floating in the air
  var geometry = new THREE.BoxGeometry(1, 1, 1);
  var material = new THREE.MeshLambertMaterial({color: 0x990033});
  var brick = new THREE.Mesh(geometry, material);
  brick.position.set(0, 1, -stuffDistance);
  scene.add(brick);

  // Make a canvas that could have text
  var FONT_SIZE_PX = 40;
  var NUM_LINES = 20;
  var CANVAS_SIZE_PX = NUM_LINES * FONT_SIZE_PX + FONT_SIZE_PX * 0.2;
  var canvas = document.createElement("canvas");
  canvas.width = canvas.height = CANVAS_SIZE_PX;
  var context = canvas.getContext("2d");
  context.font = FONT_SIZE_PX + 'px Inconsolata,monospace';
  context.globalCompositeOperation = 'darker';
  var textMetrics = context.measureText('0');
  var charWidth = textMetrics.width;
  var numCols = Math.floor(CANVAS_SIZE_PX / charWidth);

  // Float it in the air
  var textTexture = new THREE.Texture(canvas);
  textTexture.minFilter = THREE.NearestFilter;
  var textAreaMat = new THREE.MeshBasicMaterial(
    {map: textTexture, side: THREE.DoubleSide});
  textAreaMat.transparent = true;
  var editor = new THREE.Mesh(
    new THREE.PlaneGeometry(10, 10),
    new THREE.MeshBasicMaterial(textAreaMat));
  editor.position.set(0, 10, -stuffDistance);
  editor.rotation.y = 0.1;
  editor.visible = false;
  editor.value = "hello world\nmultiline works\ngo bengals";
  editor.cursor = 0;
  editor.lastValue = "";
  scene.add(editor);

  // Gets its text from the text area
  editor.update = function() {
    if (editor.value == editor.lastValue) {
      return;
    }
    context.clearRect(0, 0, CANVAS_SIZE_PX, CANVAS_SIZE_PX);
    context.fillStyle = 'hsla(0, 0%, 100%, 0.8)';
    context.fillRect(0, 0, CANVAS_SIZE_PX, CANVAS_SIZE_PX);
    editor.lastValue = editor.value;
    var lines = editor.value.split("\n")
    for (var i = 0; i < lines.length; ++i) {
      var line = lines[i];
      context.fillStyle = 'hsl(0, 0%, 25%)';
      context.fillText(line, 0, FONT_SIZE_PX + FONT_SIZE_PX * i);
    }
    textTexture.needsUpdate = true;
  }

  editor.insert = function(text) {
    editor.value = (editor.value.slice(0, editor.cursor) + text +
                    editor.value.slice(editor.cursor));
    editor.cursor++;
  }

  // Just a bit of ambient light for convenience
  var ambient = new THREE.AmbientLight(0x333333);
  scene.add(ambient);

  // The main light source is like an arctic sun
  var lightAngle = 0;
  var lightHeight = 300;
  var lightWidth = 400;
  var spotLight = new THREE.SpotLight(0xffffff);
  spotLight.position.set(0, lightHeight, 0);
  scene.add(spotLight);

  // Position camera
  camera.position.x = 0;
  camera.position.y = 3;
  camera.position.z = 0;

  CONTROLS = new THREE.PointerLockControls(camera);
  scene.add(CONTROLS.getObject());

  // An aiming dot
  var geometry = new THREE.BoxGeometry(0.01, 0.01, 0.01);
  var material = new THREE.MeshBasicMaterial({color: 0xFF0000});
  var aimer = new THREE.Mesh(geometry, material);
  aimer.visible = false;
  camera.add(aimer);
  aimer.position.set(0, 0, -1.1);

  // Find the object the aimer is aiming at
  function aimee() {
    var vector = new THREE.Vector3(0, 0, -1);
    vector = camera.localToWorld(vector);
    vector.sub(camera.position);
    // Now vector is a unit vector with the same direction as the camera
    var raycaster = new THREE.Raycaster( camera.position, vector);

    var objects = raycaster.intersectObjects(scene.children);
    if (objects.length == 0) {
      return null;
    }
    return objects[0];
  }

  Mousetrap.bind("shift", function() {
    if (!editor.visible) {
      aimer.visible = true;
    }
  }, "keydown");

  Mousetrap.bind("shift", function() {
    aimer.visible = false;
  }, "keyup");

  Mousetrap.bind("shift+z", function() {
    if (!editor.visible) {
      console.log(aimee());
    }
  });

  // Keys that go into the editor
  Mousetrap.bind([
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "space",
    "enter",
  ], function(e) {
    if (editor.visible) {
      var display = e.key;
      if (display == "Enter") {
        display = "\n";
      }
      editor.insert(display);
    }
  });

  Mousetrap.bind("shift+t", function() {
    if (!editor.visible) {
      // Displays the text editor for testing
      editor.visible = true;
    }
  });

  Mousetrap.bind("~", function() {
    // Close the text editor
    editor.visible = false;
  });

  // Start rendering
  function render() {
    requestAnimationFrame(render);

    editor.update();

    lightAngle += 0.01;
    spotLight.position.x = Math.cos(lightAngle) * lightWidth;
    spotLight.position.z = Math.sin(lightAngle) * lightWidth;

    renderer.render(scene, camera);
  }
  render();
}

<|endoftext|>


<commit_before>$(function(){
	$('body').on("change", "#my-profile-file-selector", function(){
		checkProfileSize({
			size: 200,
			width: 1280,
			// height: null
		});
	})
	$('#remove-profile-btn').on('click', function(event) {
        event.preventDefault();
        // make image view empty
        $('#upload-profile-image').attr('src', '');
        // make file name empty
        $('#upload-profile-file-info').html('');
        // make input file value empty
        $('input#my-profile-file-selector[type=file]').val('')
        // remove hide button
        $('#remove-profile-btn').hide();
        // show upload button again
        $('label.profile').show();
    });
});
function checkProfileSize(arg){
    $('#upload-profile-image').attr('src', '');
    $('#upload-profile-file-info').html('');
    $('#upload-profile-error').html('');
    var fileInput = $('form').find("input#my-profile-file-selector[type=file]")[0],
    file = fileInput.files && fileInput.files[0];
    var sizeKB = file.size / 1024;
    var tmppath = URL.createObjectURL(event.target.files[0]);
    var maxSize = arg.size || sizeKB;
    var imgHeight, imgWidth;
    console.log("maxSize "+maxSize);
    if( file ) {
        var img = new Image();
        img.src = window.URL.createObjectURL( file );
        img.onload = function() {
            var width = img.naturalWidth, height = img.naturalHeight;
            window.URL.revokeObjectURL( img.src );
            imgWidth = arg.width || width;
            console.log("imgWidth "+imgWidth);
			imgHeight = arg.height || height;
            if( sizeKB <= maxSize) {
            	if( width == imgWidth && height == imgHeight){
            		var fileName = $('input#my-profile-file-selector[type=file]').val();
	                fileName = fileName.substr(fileName.lastIndexOf("\\")+1);
	                $('#upload-profile-image').attr('src', tmppath);
	                $('#upload-profile-file-info').html(fileName);
	                $('label.profile').hide();
	                $('#remove-profile-btn').show();
            	}
            	else{
                    imgWidth = arg.width || "any";
                    imgHeight = arg.height || "any";
            		$('#upload-profile-error')
            			.html('Uploaded Picture Width should be '+
            			imgWidth+' and Height should be '+imgHeight);
	                var fileName = $('input#my-profile-file-selector[type=file]').val();
	                console.log(fileName);
            	}
            }
            else {
                $('#upload-profile-error').html('Uploaded Profile picture size should be less than '+maxSize+'KB');
                var fileName = $('input#my-profile-file-selector[type=file]').val();
                console.log(fileName);
            }
        };
    }
    else { //No file was input or browser doesn't support client side reading
        console.log('No file selected');
    }
}<commit_msg>copy to clipboard added, html code can now be copied. tooltip added when copy button is clicked.<commit_after>$(function(){
	$('body').on("change", "#my-profile-file-selector", function(){
		checkProfileSize({
			size: 200,
			width: 1280,
			// height: null
		});
	})
	$('#remove-profile-btn').on('click', function(event) {
        event.preventDefault();
        // make image view empty
        $('#upload-profile-image').attr('src', '');
        // make file name empty
        $('#upload-profile-file-info').html('');
        // make input file value empty
        $('input#my-profile-file-selector[type=file]').val('')
        // remove hide button
        $('#remove-profile-btn').hide();
        // show upload button again
        $('label.profile').show();
    });
});
function checkProfileSize(arg){
    $('#upload-profile-image').attr('src', '');
    $('#upload-profile-file-info').html('');
    $('#upload-profile-error').html('');
    var fileInput = $('form').find("input#my-profile-file-selector[type=file]")[0],
    file = fileInput.files && fileInput.files[0];
    var sizeKB = file.size / 1024;
    var tmppath = URL.createObjectURL(event.target.files[0]);
    var maxSize = arg.size || sizeKB;
    var imgHeight, imgWidth;
    console.log("maxSize "+maxSize);
    if( file ) {
        var img = new Image();
        img.src = window.URL.createObjectURL( file );
        img.onload = function() {
            var width = img.naturalWidth, height = img.naturalHeight;
            window.URL.revokeObjectURL( img.src );
            imgWidth = arg.width || width;
            console.log("imgWidth "+imgWidth);
			imgHeight = arg.height || height;
            if( sizeKB <= maxSize) {
            	if( width == imgWidth && height == imgHeight){
            		var fileName = $('input#my-profile-file-selector[type=file]').val();
	                fileName = fileName.substr(fileName.lastIndexOf("\\")+1);
	                $('#upload-profile-image').attr('src', tmppath);
	                $('#upload-profile-file-info').html(fileName);
	                $('label.profile').hide();
	                $('#remove-profile-btn').show();
            	}
            	else{
                    imgWidth = arg.width || "any";
                    imgHeight = arg.height || "any";
            		$('#upload-profile-error')
            			.html('Uploaded Picture Width should be '+
            			imgWidth+' and Height should be '+imgHeight);
	                var fileName = $('input#my-profile-file-selector[type=file]').val();
	                console.log(fileName);
            	}
            }
            else {
                $('#upload-profile-error').html('Uploaded Profile picture size should be less than '+maxSize+'KB');
                var fileName = $('input#my-profile-file-selector[type=file]').val();
                console.log(fileName);
            }
        };
    }
    else { //No file was input or browser doesn't support client side reading
        console.log('No file selected');
    }
}

// Copy to Clipboard
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
function setTooltip(message) {
  $('.html-copy').tooltip('hide')
    .attr('data-original-title', message)
    .tooltip('show');
}
function hideTooltip() {
  setTimeout(function() {
    $('.html-copy').tooltip('hide');
  }, 2000);
}

$(function(){
    $('.html-copy').tooltip({
      trigger: 'click',
      placement: 'top'
    });
    $('.html-copy').on('click',function(){
        copyToClipboard('#html-code');
        setTooltip('Copied!');
        hideTooltip();
    });
});<|endoftext|>