<commit_before>/* Is it hot right now?
   Code for loading in local weather stats (on page load and on location update)
   James Goldie, Steefan Contractor & Mat Lipson 2017 */

/* on page load: choose a location (for now, Sydney Obs Hill), download
    assets and insert */

$(function()
{
  var default_station = "066062";
  var base_path = "output/"
  var location_menu_innerpad = 10;
  var location_request_timeout = 5000;
  var geolocation_timeout = 3000;
  var geolocation_done = false;

  /* request_station: hide the details section, download stats and plots
     for a new station and then display them _when they're ready_
     put up an error message if they don't load quickly enough */
  function request_station(station_id)
  {

    // fn and obj to track downloaded resources. should probably write a
    // self-contained object for this...
    var loaded_resources =
    {
      isit_stats: false,
      isit_ts_plot: false,
      isit_density_plot: false
    }
    function resources_loaded()
    {
      if (
        loaded_resources.isit_stats == false |
        loaded_resources.isit_ts_plot == false |
        loaded_resources.isit_density_plot == false)
      {
        return false;
      }
      else
      {
        return true;
      }
    }

    // hide the details section while we update stuff!
    $("#detail").attr("style", "display: none;");
    $("#digdeeper").attr("style", "color: #eee;");
    $("#digdeeper h3").text("Loading...");
    $("#isit_answer").text(". . .");
    $("#isit_comment").text("");

    // dl stats as json and insert on success.
    // (nb: no error callback available! need to use a timeout below)
    $.getJSON(base_path + station_id + "/stats.json", function(data)
    {
      $("#isit_answer").text(data.isit_answer);
      $("#isit_comment").text(data.isit_comment);
      $("#isit_maximum").text(data.isit_maximum);
      $("#isit_minimum").text(data.isit_minimum);
      $("#isit_current").text(data.isit_current);
      $("#isit_average").text(data.isit_average);
      $("#isit_name").text(data.isit_name);
      $("#isit_span").text(data.isit_span);

      loaded_resources.isit_stats = true;

      // enable page if all resources are loaded
      if (resources_loaded())
      {
        console.log('Isithot: All resources loaded :D');
        $("#detail").attr("style", "display: flex;");
        $("#digdeeper").attr("style", "color: #b22222;");
        $("#digdeeper h3").text("Dig deeper");
      }
    });

    // dl *each* image and insert on success
    plots = ["ts_plot", "density_plot"]
    plots.map(function(content)
    {
      var plot_target = $("#isit_" + content + " img");
      console.log('Isithot: Creating callback to load ' + content);
      var plot_building = $("<img>");
      plot_building.on('load', function()
      {
        console.log('Isithot: Inside onload callback for dummy ' + content);
        // when loading img is ready, set it to the target img
        plot_target.attr("src", $(this).attr("src"));

        // enable page if all resources are loaded
        if (resources_loaded())
        {
          console.log('Isithot: All resources loaded :D');
          $("#detail").attr("style", "display: flex;");
          $("#digdeeper").attr("style", "color: #b22222;");
          $("#digdeeper h3").text("Dig deeper");
        }
      });
      // set loading img src to trigger the download
      plot_building.attr(
        "src", base_path + station_id + "/" + content + ".png");
      console.log('Isithot: Set src attribute for ' + content + '; image ought to be loading now');

      loaded_resources["isit_" + content] = true;
    });

    // apologise if resources aren't all loaded after 10 secs
    setTimeout(function()
    {
      if (!resources_loaded())
      {
        console.log('Isithot: Resources did not load within timeout D:');
        $("#digdeeper h3").text(
          "We're having some trouble downloading the data...");
      }
    }, location_request_timeout);
  }

  /* resize_location_menu: resize the location menu according to the
     current selection */
  function resize_location_menu(new_text)
  {
    // resize the dropdown
    $("#current_location_temp_dummyopt").html(new_text);
    $("#current_location").width(
      $("#current_location_temp").width() + location_menu_innerpad);
  }

  /* geo_failure: requests the nearest station id */
  function geo_success(pos_data)
  {
    if (pos_data.country_code != "AU")
    {
      console.warn("User outside Australia; defaulting to Sydney Obs Hill!");
      $("#current_location").val(default_station).trigger("change");
      geolocation_done = true;
    }
    else {
      switch (pos_data.region_code) {
        case 'ACT':
          $("#current_location").val("070351").trigger("change");
          break;
        case 'NSW':
          $("#current_location").val("066062").trigger("change");
          break;
        case 'VIC':
          $("#current_location").val("087031").trigger("change");
          break;
        case 'TAS':
          $("#current_location").val("094029").trigger("change");
          break;
        case 'QLD':
          $("#current_location").val("040842").trigger("change");
          break;
        case 'SA':
          $("#current_location").val("023090").trigger("change");
          break;
        case 'NT':
          $("#current_location").val("014015").trigger("change");
          break;
        case 'WA':
          $("#current_location").val("009021").trigger("change");
          break;
        default:
          console.warn(
            "User region not recognised; " +
            "defaulting to Sydney Obs Hill!");
          $("#current_location").val(default_station).trigger("change");
      }
      console.log("Geolocation done!");
      geolocation_done = true;
    }
  }

  /* geo_failure: requests the sydney obs hill station id */
  function geo_failure()
  {
    console.warn("Geolocation failed; defaulting to Sydney Obs Hill!");
    $("current_location").val(default_station).trigger("change");
  }

  // = on page load ===========================================================

  // on page load, populate the location menu, then determine default (local)
  // station and request it
  $.getJSON("locations.json", function(data)
  {
    $("#current_location").append(
      '<option value="no_station_selected">----------</option>');
    $.each(data, function(index, station) {
      $("#current_location").append(
        '<option value="' + station.id + '">' + station.label + '</option>');
    });

    // now get user location from ip and use to determine a default station
    // (geo_success and geo_failure will update and request the first time)
    if (navigator.geolocation)
    {
      $.get("https://freegeoip.net/json/", geo_success);
    }
    else
    {
      console.warn("No geolocation available!");
    }

    // default to sydney if geolocation hasn't returned
    setTimeout(function()
    {
      if (!geolocation_done)
      {
        geo_failure();
      }
    }, geolocation_timeout);
  });

  // = callbacks ==============================================================

  /* on new location selected:
       - update the dropdown menu
       - request new location data */
  $("#current_location").change(function() {
    console.log(this.value);
    if (this.value != "no_station_selected")
    {
      resize_location_menu($("option:selected", this).text());
      request_station(this.value);
    }
  });

});<commit_msg>Remove "no station" option (it looks awful)<commit_after>/* Is it hot right now?
   Code for loading in local weather stats (on page load and on location update)
   James Goldie, Steefan Contractor & Mat Lipson 2017 */

/* on page load: choose a location (for now, Sydney Obs Hill), download
    assets and insert */

$(function()
{
  var default_station = "066062";
  var base_path = "output/"
  var location_menu_innerpad = 10;
  var location_request_timeout = 5000;
  var geolocation_timeout = 3000;
  var geolocation_done = false;

  /* request_station: hide the details section, download stats and plots
     for a new station and then display them _when they're ready_
     put up an error message if they don't load quickly enough */
  function request_station(station_id)
  {

    // fn and obj to track downloaded resources. should probably write a
    // self-contained object for this...
    var loaded_resources =
    {
      isit_stats: false,
      isit_ts_plot: false,
      isit_density_plot: false
    }
    function resources_loaded()
    {
      if (
        loaded_resources.isit_stats == false |
        loaded_resources.isit_ts_plot == false |
        loaded_resources.isit_density_plot == false)
      {
        return false;
      }
      else
      {
        return true;
      }
    }

    // hide the details section while we update stuff!
    $("#detail").attr("style", "display: none;");
    $("#digdeeper").attr("style", "color: #eee;");
    $("#digdeeper h3").text("Loading...");
    $("#isit_answer").text(". . .");
    $("#isit_comment").text("");

    // dl stats as json and insert on success.
    // (nb: no error callback available! need to use a timeout below)
    $.getJSON(base_path + station_id + "/stats.json", function(data)
    {
      $("#isit_answer").text(data.isit_answer);
      $("#isit_comment").text(data.isit_comment);
      $("#isit_maximum").text(data.isit_maximum);
      $("#isit_minimum").text(data.isit_minimum);
      $("#isit_current").text(data.isit_current);
      $("#isit_average").text(data.isit_average);
      $("#isit_name").text(data.isit_name);
      $("#isit_span").text(data.isit_span);

      loaded_resources.isit_stats = true;

      // enable page if all resources are loaded
      if (resources_loaded())
      {
        console.log('Isithot: All resources loaded :D');
        $("#detail").attr("style", "display: flex;");
        $("#digdeeper").attr("style", "color: #b22222;");
        $("#digdeeper h3").text("Dig deeper");
      }
    });

    // dl *each* image and insert on success
    plots = ["ts_plot", "density_plot"]
    plots.map(function(content)
    {
      var plot_target = $("#isit_" + content + " img");
      console.log('Isithot: Creating callback to load ' + content);
      var plot_building = $("<img>");
      plot_building.on('load', function()
      {
        console.log('Isithot: Inside onload callback for dummy ' + content);
        // when loading img is ready, set it to the target img
        plot_target.attr("src", $(this).attr("src"));

        // enable page if all resources are loaded
        if (resources_loaded())
        {
          console.log('Isithot: All resources loaded :D');
          $("#detail").attr("style", "display: flex;");
          $("#digdeeper").attr("style", "color: #b22222;");
          $("#digdeeper h3").text("Dig deeper");
        }
      });
      // set loading img src to trigger the download
      plot_building.attr(
        "src", base_path + station_id + "/" + content + ".png");
      console.log('Isithot: Set src attribute for ' + content + '; image ought to be loading now');

      loaded_resources["isit_" + content] = true;
    });

    // apologise if resources aren't all loaded after 10 secs
    setTimeout(function()
    {
      if (!resources_loaded())
      {
        console.log('Isithot: Resources did not load within timeout D:');
        $("#digdeeper h3").text(
          "We're having some trouble downloading the data...");
      }
    }, location_request_timeout);
  }

  /* resize_location_menu: resize the location menu according to the
     current selection */
  function resize_location_menu(new_text)
  {
    // resize the dropdown
    $("#current_location_temp_dummyopt").html(new_text);
    $("#current_location").width(
      $("#current_location_temp").width() + location_menu_innerpad);
  }

  /* geo_failure: requests the nearest station id */
  function geo_success(pos_data)
  {
    if (pos_data.country_code != "AU")
    {
      console.warn("User outside Australia; defaulting to Sydney Obs Hill!");
      $("#current_location").val(default_station).trigger("change");
      geolocation_done = true;
    }
    else {
      switch (pos_data.region_code) {
        case 'ACT':
          $("#current_location").val("070351").trigger("change");
          break;
        case 'NSW':
          $("#current_location").val("066062").trigger("change");
          break;
        case 'VIC':
          $("#current_location").val("087031").trigger("change");
          break;
        case 'TAS':
          $("#current_location").val("094029").trigger("change");
          break;
        case 'QLD':
          $("#current_location").val("040842").trigger("change");
          break;
        case 'SA':
          $("#current_location").val("023090").trigger("change");
          break;
        case 'NT':
          $("#current_location").val("014015").trigger("change");
          break;
        case 'WA':
          $("#current_location").val("009021").trigger("change");
          break;
        default:
          console.warn(
            "User region not recognised; " +
            "defaulting to Sydney Obs Hill!");
          $("#current_location").val(default_station).trigger("change");
      }
      console.log("Geolocation done!");
      geolocation_done = true;
    }
  }

  /* geo_failure: requests the sydney obs hill station id */
  function geo_failure()
  {
    console.warn("Geolocation failed; defaulting to Sydney Obs Hill!");
    $("current_location").val(default_station).trigger("change");
  }

  // = on page load ===========================================================

  // on page load, populate the location menu, then determine default (local)
  // station and request it
  $.getJSON("locations.json", function(data)
  {
    $.each(data, function(index, station) {
      $("#current_location").append(
        '<option value="' + station.id + '">' + station.label + '</option>');
    });

    // now get user location from ip and use to determine a default station
    // (geo_success and geo_failure will update and request the first time)
    if (navigator.geolocation)
    {
      $.get("https://freegeoip.net/json/", geo_success);
    }
    else
    {
      console.warn("No geolocation available!");
    }

    // default to sydney if geolocation hasn't returned
    setTimeout(function()
    {
      if (!geolocation_done)
      {
        geo_failure();
      }
    }, geolocation_timeout);
  });

  // = callbacks ==============================================================

  /* on new location selected:
       - update the dropdown menu
       - request new location data */
  $("#current_location").change(function() {
    console.log(this.value);
    resize_location_menu($("option:selected", this).text());
    request_station(this.value);
  });

});<|endoftext|>


<commit_before>"use strict";angular.module("config",[]).constant("ENV",{name:"production",apiEndpoint:"http://api.yoursite.com/"}),function(){var a=angular.module("Myhealth",["ionic","config","ngRoute","ngResource","Myhealth.services","Myhealth.controllers","Myhealth.directives"]);a.run(["$ionicPlatform",function(a){a.ready(function(){window.cordova&&window.cordova.plugins.Keyboard&&cordova.plugins.Keyboard.hideKeyboardAccessoryBar(!0),window.StatusBar&&StatusBar.styleDefault()})}])}(),function(){var a=angular.module("Myhealth.controllers",[]);a.controller("MapCtrl",["$scope","$ionicLoading","GoogleMapsAPI",function(a,b,c){a.googleMapsAPI=c.query(),console.log(a.googleMapsAPI),a.visiblePano=!0,a.panoValue="Hide",a.togglePano=function(b){console.log("togglePano method called"),console.log("data is: "+b),a.visiblePano=!a.visiblePano,1==b?(a.visiblePano=!0,console.log("Broadcasting to child directive that Panorama view has loaded"),a.$broadcast("loadedPano",!0),a.panoValue="Hide"):a.panoValue=1==a.visiblePano?"Hide":"Show"},a.$on("togglePanoEvent",function(b,c){console.log("togglePanoEvent data sent to parent MapCtrl is: "+c),a.togglePano(c)}),a.mapCreated=function(b){console.log("Myhealth.controllers - mapCreated method called"),a.map=b},a.centerOnMe=function(){console.log("Myhealth.controllers - centerOnMe method called"),console.log("Centering"),a.map&&(b.show({content:"Getting current location...",showBackdrop:!1}),navigator.geolocation.getCurrentPosition(function(c){console.log("Myhealth.controllers - getCurrentPosition method called"),console.log("Got position: ",c),a.map.setCenter(new google.maps.LatLng(c.coords.latitude,c.coords.longitude)),b.hide()},function(a){alert("Unable to get location: "+a.message)}))}}])}(),function(){var a=angular.module("Myhealth.directives",[]);a.directive("map",function(){return{restrict:"E",scope:{onCreate:"&"},link:function(a,b){function c(){console.log("Myhealth.directives - initialize method called");var c=b[0],d=new google.maps.LatLng(-36.43,148.323,!0),e={center:d,zoom:13,noClear:!0,backgroundColor:"#ff5511",mapTypeId:google.maps.MapTypeId.ROADMAP,keyboardShortcuts:!0,disableDoubleClickZoom:!1,draggable:!0,scrollwheel:!0,streetViewControl:!0,disableDefaultUI:!1,mapTypeControl:!0,mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU,position:google.maps.ControlPosition.TOP_LEFT,mapTypeIds:[google.maps.MapTypeId.ROADMAP,google.maps.MapTypeId.SATELLITE,google.maps.MapTypeId.TERRAIN]},navigationControl:!0,navigationControlOptions:{position:google.maps.ControlPosition.TOP_LEFT,style:google.maps.NavigationControlStyle.SMALL},scaleControl:!0,scaleControlOptions:{position:google.maps.ControlPosition.TOP,style:google.maps.ScaleControlStyle.SMALL}},f=new google.maps.Map(c,e);a.onCreate({map:f});var g=(google.maps.event.addListenerOnce(f,"bounds_changed",function(){f.getBounds();console.log("Myhealth.directives - map bounds initialized")}),new google.maps.Marker({position:new google.maps.LatLng(-36.43,148.323),icon:"../images/star_health_high.png",shadow:"../images/star_health_high_shadow.png",title:"Star"})),h=new google.maps.InfoWindow({content:"Warning: Alpine ladybird beetle territory"}),i='

Ladybird

Harmonia Conformis
<video src="../images/ladybird.mp4" controls="controls" autoplay="autoplay">
',j=new google.maps.InfoWindow({content:"Cross country skiing area"}),k=(google.maps.event.addDomListener(h,"closeclick",function(){console.log("Myhealth.directives - close infoWindowLadyBird clicked"),h.close(f,h);var a=g.getPosition();return console.log("InfoWindowLadyBird Closed is at PositionClicked: "+a),!1}),google.maps.event.addDomListener(j,"mouseout",function(){console.log("Myhealth.directives - close infoWindowCrossCountry mouseout"),j.close(f,j);var a=l.getPosition();return console.log("InfoWindowCrossCountry Closed is at PositionMouseOut: "+a),!1}),[new google.maps.LatLng(-36.4317,148.3286),new google.maps.LatLng(-36.43,148.322),new google.maps.LatLng(-36.41,148.2913)]),l=new google.maps.Polygon({path:k,strokeColor:"#ff44dd",strokeWeight:10,strokeOpacity:.5,fillColor:"#ff9999",fillOpacity:.3,map:f});g.setMap(f);google.maps.event.addDomListener(g,"click",function(){return console.log("Myhealth.directives - click marker method called"),a.$emit("togglePanoEvent",!0),a.$on("loadedPano",function(a,b){console.log("loadedPanoEvent msg sent to child directive is: "+b),h.setContent(i),h.open(f,g);var c=g.getPosition();console.log("Marker PositionClicked is: "+c);var d=new google.maps.StreetViewPanorama(document.getElementById("streetview"));d.registerPanoProvider(function(a){return{location:{pano:a,description:"Mount Carruthers"},links:[],copyright:"Imagery © 2014 Luke Schoen",tiles:{tileSize:new google.maps.Size(512,512),worldSize:new google.maps.Size(1500,750),originHeading:0,getTileUrl:function(a,b,c,d){return"../images/happy_campers_"+a+"_"+b+"_"+c+"_"+d+".jpg"}}}}),d.setPano("panorama"),f.setOptions({zoom:10})}),!1}),google.maps.event.addDomListener(l,"mouseover",function(a){console.log("Myhealth.directives - click polygon method called"),j.open(f,l);var b=a.latLng;return console.log("Polygon PositionClicked is: "+b),!1})}google.maps.event.addDomListener(window,"load",c)}}})}(),function(){var a=angular.module("Myhealth.services",["ngResource"]);a.factory("GoogleMapsAPI",["$resource",function(a){return a("config.json",{},{query:{method:"GET",isArray:!0,cache:!0}})}])}();<commit_msg>Performed grunt build<commit_after>"use strict";angular.module("config",[]).constant("ENV",{name:"production",apiEndpoint:"http://api.yoursite.com/"}),function(){var a=angular.module("Myhealth",["ionic","config","ngRoute","ngResource","Myhealth.services","Myhealth.controllers","Myhealth.directives"]);a.run(["$ionicPlatform",function(a){a.ready(function(){window.cordova&&window.cordova.plugins.Keyboard&&cordova.plugins.Keyboard.hideKeyboardAccessoryBar(!0),window.StatusBar&&StatusBar.styleDefault()})}])}(),function(){var a=angular.module("Myhealth.controllers",[]);a.controller("MapCtrl",["$scope","$ionicLoading","GoogleMapsAPI",function(a,b,c){a.googleMapsAPI=c.query(),console.log(a.googleMapsAPI),a.visiblePano=!0,a.panoValue="Hide",a.togglePano=function(b){console.log("togglePano method called"),console.log("data is: "+b),a.visiblePano=!a.visiblePano,1==b?(a.visiblePano=!0,console.log("Broadcasting to child directive that Panorama view has loaded"),a.$broadcast("loadedPano",!0),a.panoValue="Hide"):a.panoValue=1==a.visiblePano?"Hide":"Show"},a.$on("togglePanoEvent",function(b,c){console.log("togglePanoEvent data sent to parent MapCtrl is: "+c),a.togglePano(c)}),a.mapCreated=function(b){console.log("Myhealth.controllers - mapCreated method called"),a.map=b},a.centerOnMe=function(){console.log("Myhealth.controllers - centerOnMe method called"),console.log("Centering"),a.map&&(b.show({content:"Getting current location...",showBackdrop:!1}),navigator.geolocation.getCurrentPosition(function(c){console.log("Myhealth.controllers - getCurrentPosition method called"),console.log("Got position: ",c),a.map.setCenter(new google.maps.LatLng(c.coords.latitude,c.coords.longitude)),b.hide()},function(a){alert("Unable to get location: "+a.message)}))}}])}(),function(){var a=angular.module("Myhealth.directives",[]);a.directive("map",function(){return{restrict:"E",scope:{onCreate:"&"},link:function(a,b){function c(){console.log("Myhealth.directives - initialize method called");var c=b[0],d=new google.maps.LatLng(-36.43,148.323,!0),e={center:d,zoom:13,noClear:!0,backgroundColor:"#ff5511",mapTypeId:google.maps.MapTypeId.ROADMAP,keyboardShortcuts:!0,disableDoubleClickZoom:!1,draggable:!0,scrollwheel:!0,streetViewControl:!0,disableDefaultUI:!1,mapTypeControl:!0,mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU,position:google.maps.ControlPosition.TOP_LEFT,mapTypeIds:[google.maps.MapTypeId.ROADMAP,google.maps.MapTypeId.SATELLITE,google.maps.MapTypeId.TERRAIN]},navigationControl:!0,navigationControlOptions:{position:google.maps.ControlPosition.TOP_LEFT,style:google.maps.NavigationControlStyle.SMALL},scaleControl:!0,scaleControlOptions:{position:google.maps.ControlPosition.TOP,style:google.maps.ScaleControlStyle.SMALL}},f=new google.maps.Map(c,e);a.onCreate({map:f});var g=(google.maps.event.addListenerOnce(f,"bounds_changed",function(){f.getBounds();console.log("Myhealth.directives - map bounds initialized")}),new google.maps.Marker({position:new google.maps.LatLng(-36.43,148.323),icon:"../images/star_health_high.png",shadow:"../images/star_health_high_shadow.png",title:"Star"})),h=new google.maps.InfoWindow({content:"Warning: Alpine ladybird beetle territory"}),i='

Ladybird

Harmonia Conformis
<video src="../images/ladybird.mp4" controls="controls" autoplay="autoplay">
',j=new google.maps.InfoWindow({content:"Cross country skiing area"}),k=(google.maps.event.addDomListener(h,"closeclick",function(){console.log("Myhealth.directives - close infoWindowLadyBird clicked"),h.close(f,h);var a=g.getPosition();return console.log("InfoWindowLadyBird Closed is at PositionClicked: "+a),!1}),google.maps.event.addDomListener(j,"mouseout",function(){console.log("Myhealth.directives - close infoWindowCrossCountry mouseout"),j.close(f,j);var a=l.getPosition();return console.log("InfoWindowCrossCountry Closed is at PositionMouseOut: "+a),!1}),[new google.maps.LatLng(-36.4317,148.3286),new google.maps.LatLng(-36.43,148.312),new google.maps.LatLng(-36.41,148.2913)]),l=new google.maps.Polygon({path:k,strokeColor:"#ff44dd",strokeWeight:10,strokeOpacity:.5,fillColor:"#ff9999",fillOpacity:.3,map:f});g.setMap(f);google.maps.event.addDomListener(g,"click",function(){return console.log("Myhealth.directives - click marker method called"),a.$emit("togglePanoEvent",!0),a.$on("loadedPano",function(a,b){console.log("loadedPanoEvent msg sent to child directive is: "+b),h.setContent(i),h.open(f,g);var c=g.getPosition();console.log("Marker PositionClicked is: "+c);var d=new google.maps.StreetViewPanorama(document.getElementById("streetview"));d.registerPanoProvider(function(a){return{location:{pano:a,description:"Mount Carruthers"},links:[],copyright:"Imagery © 2014 Luke Schoen",tiles:{tileSize:new google.maps.Size(512,512),worldSize:new google.maps.Size(1500,750),originHeading:0,getTileUrl:function(a,b,c,d){return"../images/happy_campers_"+a+"_"+b+"_"+c+"_"+d+".jpg"}}}}),d.setPano("panorama"),f.setOptions({zoom:10})}),!1}),google.maps.event.addDomListener(l,"mouseover",function(a){console.log("Myhealth.directives - click polygon method called");var b=document.createElement("div");b.style.width="200px",b.style.height="200px",document.getElementsByTagName("map")[0].appendChild(b);var c=a.latLng;console.log("Polygon PositionMouseOver is: "+c);{var d={zoom:14,center:c,mapTypeId:f.getMapTypeId(),disableDefaultUI:!0},e=new google.maps.Map(b,d);new google.maps.Marker({position:c,map:e,clickable:!0})}return j||(j=new google.maps.InfoWindow),j.setContent(b),j.open(f,l),!1})}google.maps.event.addDomListener(window,"load",c)}}})}(),function(){var a=angular.module("Myhealth.services",["ngResource"]);a.factory("GoogleMapsAPI",["$resource",function(a){return a("config.json",{},{query:{method:"GET",isArray:!0,cache:!0}})}])}();<|endoftext|>


<commit_before>/*
*   Copyright 2012 Comcast
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/

define('xooie/event_handler', ['jquery', 'xooie/helpers'], function($, helpers) {

  var EventHandler = function(namespace) {
    this.namespace = namespace;
  };

  function format(type, namespace) {
    if (typeof namespace === 'undefined') {
      return type;
    } else {
      return type + '.' + namespace;
    }
  }

  EventHandler.prototype.handlers = {};

  EventHandler.prototype._callbacks = {};

  EventHandler.prototype.add = function(type, method) {
    var self = this,
        formattedType, t;

    if (helpers.isObject(type) && helpers.isUndefined(method)) {
      for(t in type) {
        if (helpers.isFunction(type[t])) {
          this.add(t, type[t]);
        }
      }

      return;
    }

    formattedType = format(type, this.namespace);

    if (helpers.isUndefined(this.handlers[formattedType])) {
      this.handlers[formattedType] = function(e) {
        self.fire(e, this, arguments);
      };
    }

    if (helpers.isUndefined(this._callbacks[type])) {
      this._callbacks[type] = $.Callbacks('unique');
    }

    this._callbacks[type].add(method);
  };

  EventHandler.prototype.clear = function(type) {
    delete(this.handlers[format(type, this.namespace)]);

    if (!helpers.isUndefined(this._callbacks[type])) {
      this._callbacks[type].empty();
    }
  };

  EventHandler.prototype.fire = function(event, context, args) {
    if (event.namespace && event.namespace !== this.namespace) {
      return;
    }

    if (!helpers.isUndefined(this._callbacks[event.type])) {
      this._callbacks[event.type].fireWith(context, args);
    }
  };

  return EventHandler;
});<commit_msg>Fixed event handler so it properly namespaces<commit_after>/*
*   Copyright 2012 Comcast
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/

define('xooie/event_handler', ['jquery', 'xooie/helpers'], function($, helpers) {

  var EventHandler = function(namespace) {
    this.namespace = namespace;

    this.handlers = {};

    this._callbacks = {};
  };

  function format(type, namespace) {
    if (typeof namespace === 'undefined') {
      return type;
    } else {
      return type + '.' + namespace;
    }
  }

  EventHandler.prototype.add = function(type, method) {
    var self = this,
        formattedType, t;

    if (helpers.isObject(type) && helpers.isUndefined(method)) {
      for(t in type) {
        if (helpers.isFunction(type[t])) {
          this.add(t, type[t]);
        }
      }

      return;
    }

    formattedType = format(type, this.namespace);

    if (helpers.isUndefined(this.handlers[formattedType])) {
      this.handlers[formattedType] = function(e) {
        self.fire(e, this, arguments);
      };
    }

    if (helpers.isUndefined(this._callbacks[type])) {
      this._callbacks[type] = $.Callbacks('unique');
    }

    this._callbacks[type].add(method);
  };

  EventHandler.prototype.clear = function(type) {
    delete(this.handlers[format(type, this.namespace)]);

    if (!helpers.isUndefined(this._callbacks[type])) {
      this._callbacks[type].empty();
    }
  };

  EventHandler.prototype.fire = function(event, context, args) {
    if (event.namespace && event.namespace !== this.namespace) {
      return;
    }

    if (!helpers.isUndefined(this._callbacks[event.type])) {
      this._callbacks[event.type].fireWith(context, args);
    }
  };

  return EventHandler;
});<|endoftext|>


<commit_before>
function start_yarn() {
    if (window.use_websockets) {
        var socket = io.connect(window.websockets_url);
        socket.on('connect', function() {
            start_sockets_yarn(socket);
        });
    }
    else {
        $.ajax('api/v1/threads', { success: rest_draw_available_threads, error: draw_launch_error });
    }
}

function start_sockets_yarn(socket) {
    window.yarn_websocket = socket;
    socket.on('initial_thread_list', socket_draw_available_thread_list);
    socket.on('thread_info', socket_draw_new_thread);
    socket.on('messages', socket_update_threads);
    socket.emit('load_threads', { token: websockets_token, user: yarn_current_user });
}

function draw_launch_error() {
    console.log("Error launching yarn");
}

function socket_draw_available_thread_list(data) {
    _draw_available_threads(JSON.parse(data));
}

function rest_draw_available_threads(data) {
    _draw_available_threads(data);
}

function _draw_available_threads(data) {
    var source = $("#available_threads").html();
    var template = Handlebars.compile(source);

    window.all_thread_data = {};
    for (var i = 0; i < data["threads"].length; i++) {
        var thread = data["threads"][i];
        window.all_thread_data[thread.id] = {
            name: thread.name,
            description: thread.description
        };
    }

    $("#available_thread_list").html(template({ threads: data["threads"] }));

    var tabs = $( "#tabs" ).tabs({
        activate: function(ev, ui) {
            select_thread_tab_event(ev, ui);
        }
    });
    refresh_thread_tabs();

    var favs = data["favorites"];
    for (var i = 0; i < favs.length; i++) {
        pre_load_thread(favs[i]);
    }

    for (var i = 0; i < favs.length; i++) {
        load_thread(favs[i]);
    }
    refresh_thread_tabs();
}

function refresh_thread_tabs() {
    $("#tabs").tabs("refresh");
    $("#tabs").find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        handle: ".handle",
        items: "li:not(#home_tab)",
        stop: function() {
            save_thread_preference();
            return true;
        }
    });

}

function handle_window_click(e) {
    var target = e.target;
    var classname = target.className;

    if (classname == "artifact_upload_interface") {
        choose_file_to_upload(target.rel);
    }
    else if (classname == "cancel_upload_artifact") {
        cancel_file_upload(target.rel);
    }
    else if (classname == "upload_artifact") {
        upload_new_artifact(target.rel);
    }
    else if (classname == "private_chat") {
        open_private_chat(target.rel, { "highlight": true });
    }
    else if (classname == "thread-history") {
        show_thread_history(target.rel);
    }
    else if (classname == "close-history") {
        close_thread_history(target.rel);
    }
    else if (classname == "create_new_thread_link") {
        show_thread_creation_panel();
    }
    else if (classname == "cancel_new_thread_create") {
        hide_thread_creation_panel();
    }
    else if (classname == "submit_new_thread") {
        create_new_thread();
    }
    else if (classname == "close_thread_tab") {
        close_thread(target.rel);
    }
    else if (classname == "open_thread") {
        load_thread(target.rel, { highlight: true, save_preference: true });
    }
    else if (classname == "show_more_artifact") {
        show_more_artifact(target);
    }
    else if (classname == "show_less_artifact") {
        show_less_artifact(target);
    }
}

function save_thread_preference() {
    var ids = [];
    var items = $("#tab_list > li");
    for (var i = 0; i < items.length; i++) {
        var item = items[i];

        var item_id = item.id;

        var matches = item_id.match(/thread_tab_([0-9]+)/);
        if (matches) {
            ids.push(matches[1]);
        }
    }

    var json_ids = JSON.stringify(ids);
    if (window.use_websockets) {
        var socket = window.yarn_websocket;
        socket.emit('set_favorite_threads', {
            thread_ids: json_ids
        });
    }
    else {
        var csrf_value = $("input[name='csrfmiddlewaretoken']")[0].value;
        $.ajax('api/v1/set_fav_threads', {
            type: "POST",
            headers: {
                "X-CSRFToken": csrf_value
            },
            data: json_ids,
            dataType: 'text'
        });
    }
}

function show_thread_creation_panel() {
    $("#err_new_thread_name_required").hide();
    $("#err_new_thread_dupe").hide();
    $("#new_thread_name").val("");
    $("#new_thread_topic").val("");
    $("#new_thread_creation_panel").show();
}

function hide_thread_creation_panel() {
    $("#new_thread_creation_panel").hide();
}

function window_focus_event() {
    window.is_blurred = false;
    document.title = yarn_headers["normal"];
    clearTimeout(window.alert_title_timeout);
    window.alert_title_timeout = null;
}

function window_blur_event() {
    window.is_blurred = true;
}

function set_highlight_title() {
    if (window.is_blurred && !window.alert_title_timeout) {
        document.title = yarn_headers["highlight"];
    }
}

function set_alert_title() {
    if (window.alert_title_timeout || !window.is_blurred) {
        return;
    }
    document.title = yarn_headers["alert"][0];
    window.alert_title_position = 0;

    window.alert_title_timeout = setTimeout(toggle_alert_title, 200);
}

function toggle_alert_title() {
    if (!window.is_blurred) {
        return;
    }

    var next_pos = window.alert_title_position + 1;

    if (next_pos >= yarn_headers["alert"].length) {
        next_pos = 0;
    }

    document.title = yarn_headers["alert"][next_pos];
    window.alert_title_position = next_pos;

    window.alert_title_timeout = setTimeout(toggle_alert_title, 400);
}

function stash_person_data(person) {
    if (!window.all_person_data) {
        window.all_person_data = {};
    }

    window.all_person_data[person.login_name] = person;
}

$(window).on("blur", window_blur_event);
$(window).on("focus", window_focus_event);

$(window).on("click", handle_window_click);
start_period_updates();
<commit_msg>socket.io needs a secure: true arg to use https - wss:// isn't enough :(<commit_after>
function start_yarn() {
    if (window.use_websockets) {
        var socket_args = {};
        if (window.websockets_url.match(/^wss:/)) {
            socket_args['secure'] = true;
        }
        var socket = io.connect(window.websockets_url, socket_args);
        socket.on('connect', function() {
            start_sockets_yarn(socket);
        });
    }
    else {
        $.ajax('api/v1/threads', { success: rest_draw_available_threads, error: draw_launch_error });
    }
}

function start_sockets_yarn(socket) {
    window.yarn_websocket = socket;
    socket.on('initial_thread_list', socket_draw_available_thread_list);
    socket.on('thread_info', socket_draw_new_thread);
    socket.on('messages', socket_update_threads);
    socket.emit('load_threads', { token: websockets_token, user: yarn_current_user });
}

function draw_launch_error() {
    console.log("Error launching yarn");
}

function socket_draw_available_thread_list(data) {
    _draw_available_threads(JSON.parse(data));
}

function rest_draw_available_threads(data) {
    _draw_available_threads(data);
}

function _draw_available_threads(data) {
    var source = $("#available_threads").html();
    var template = Handlebars.compile(source);

    window.all_thread_data = {};
    for (var i = 0; i < data["threads"].length; i++) {
        var thread = data["threads"][i];
        window.all_thread_data[thread.id] = {
            name: thread.name,
            description: thread.description
        };
    }

    $("#available_thread_list").html(template({ threads: data["threads"] }));

    var tabs = $( "#tabs" ).tabs({
        activate: function(ev, ui) {
            select_thread_tab_event(ev, ui);
        }
    });
    refresh_thread_tabs();

    var favs = data["favorites"];
    for (var i = 0; i < favs.length; i++) {
        pre_load_thread(favs[i]);
    }

    for (var i = 0; i < favs.length; i++) {
        load_thread(favs[i]);
    }
    refresh_thread_tabs();
}

function refresh_thread_tabs() {
    $("#tabs").tabs("refresh");
    $("#tabs").find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        handle: ".handle",
        items: "li:not(#home_tab)",
        stop: function() {
            save_thread_preference();
            return true;
        }
    });

}

function handle_window_click(e) {
    var target = e.target;
    var classname = target.className;

    if (classname == "artifact_upload_interface") {
        choose_file_to_upload(target.rel);
    }
    else if (classname == "cancel_upload_artifact") {
        cancel_file_upload(target.rel);
    }
    else if (classname == "upload_artifact") {
        upload_new_artifact(target.rel);
    }
    else if (classname == "private_chat") {
        open_private_chat(target.rel, { "highlight": true });
    }
    else if (classname == "thread-history") {
        show_thread_history(target.rel);
    }
    else if (classname == "close-history") {
        close_thread_history(target.rel);
    }
    else if (classname == "create_new_thread_link") {
        show_thread_creation_panel();
    }
    else if (classname == "cancel_new_thread_create") {
        hide_thread_creation_panel();
    }
    else if (classname == "submit_new_thread") {
        create_new_thread();
    }
    else if (classname == "close_thread_tab") {
        close_thread(target.rel);
    }
    else if (classname == "open_thread") {
        load_thread(target.rel, { highlight: true, save_preference: true });
    }
    else if (classname == "show_more_artifact") {
        show_more_artifact(target);
    }
    else if (classname == "show_less_artifact") {
        show_less_artifact(target);
    }
}

function save_thread_preference() {
    var ids = [];
    var items = $("#tab_list > li");
    for (var i = 0; i < items.length; i++) {
        var item = items[i];

        var item_id = item.id;

        var matches = item_id.match(/thread_tab_([0-9]+)/);
        if (matches) {
            ids.push(matches[1]);
        }
    }

    var json_ids = JSON.stringify(ids);
    if (window.use_websockets) {
        var socket = window.yarn_websocket;
        socket.emit('set_favorite_threads', {
            thread_ids: json_ids
        });
    }
    else {
        var csrf_value = $("input[name='csrfmiddlewaretoken']")[0].value;
        $.ajax('api/v1/set_fav_threads', {
            type: "POST",
            headers: {
                "X-CSRFToken": csrf_value
            },
            data: json_ids,
            dataType: 'text'
        });
    }
}

function show_thread_creation_panel() {
    $("#err_new_thread_name_required").hide();
    $("#err_new_thread_dupe").hide();
    $("#new_thread_name").val("");
    $("#new_thread_topic").val("");
    $("#new_thread_creation_panel").show();
}

function hide_thread_creation_panel() {
    $("#new_thread_creation_panel").hide();
}

function window_focus_event() {
    window.is_blurred = false;
    document.title = yarn_headers["normal"];
    clearTimeout(window.alert_title_timeout);
    window.alert_title_timeout = null;
}

function window_blur_event() {
    window.is_blurred = true;
}

function set_highlight_title() {
    if (window.is_blurred && !window.alert_title_timeout) {
        document.title = yarn_headers["highlight"];
    }
}

function set_alert_title() {
    if (window.alert_title_timeout || !window.is_blurred) {
        return;
    }
    document.title = yarn_headers["alert"][0];
    window.alert_title_position = 0;

    window.alert_title_timeout = setTimeout(toggle_alert_title, 200);
}

function toggle_alert_title() {
    if (!window.is_blurred) {
        return;
    }

    var next_pos = window.alert_title_position + 1;

    if (next_pos >= yarn_headers["alert"].length) {
        next_pos = 0;
    }

    document.title = yarn_headers["alert"][next_pos];
    window.alert_title_position = next_pos;

    window.alert_title_timeout = setTimeout(toggle_alert_title, 400);
}

function stash_person_data(person) {
    if (!window.all_person_data) {
        window.all_person_data = {};
    }

    window.all_person_data[person.login_name] = person;
}

$(window).on("blur", window_blur_event);
$(window).on("focus", window_focus_event);

$(window).on("click", handle_window_click);
start_period_updates();
<|endoftext|>


<commit_before>'use strict';

var helper = {
  fileName: '',
  maxRetries: 2,
  id: '',
  chunks: []
};

function guardabosques(url) {
  $(document).ready(function () {
    resourceHandler(url);
  });
}

// Resource fetch from a LB
function resourceHandler(url) {
  $.support.cors = true;
  $.ajax({
    type: 'GET',
    url: url,
    success: function(data) {
      var resource = data;
      console.log('json: ' + JSON.stringify(resource));
      downloadHandler(resource);
    },
    dataType: 'json',
    async: true
  });
}
// End resource fetch

/** Download handler **/
function downloadHandler(resource) {
  setHelper(resource);
  console.log('helper: ' + JSON.stringify(helper));
  downloadFile(helper);
}
// End download handler

// Downloads a single file into a blob
function downloadFile(helper) {
  var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB;
  var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction;

  if (IDBTransaction) {
    IDBTransaction.READ_WRITE = IDBTransaction.READ_WRITE || 'readwrite';
    IDBTransaction.READ_ONLY = IDBTransaction.READ_ONLY || 'readonly';
  }

  var dbVersion = 1.0;
  var dbName = 'guardabosques_' + Date.now();
  var connect = indexedDB.open(dbName, dbVersion);
  var objectStore = helper.id;
  var database;

  // IndexedDB connection handlers
  connect.onerror = function(event) {
    console.error("Error creating/accessing IndexedDB database: " + event);
  };

  connect.onsuccess = function(event) {
    console.info("Success creating/accessing IndexedDB database: " + event);

    database = connect.result;
    database.onerror = function (event) {
      console.error("Error creating/accessing IndexedDB database: " + event);
    };
    database.onblocked = function (event) {
      console.log('Database blocked: ' + event);
    };

    // Provisional solution for Chrome using objectStore instead. Will be deprecated
    if (database.setVersion) {
      if (database.version != dbVersion) {
        var setVersion = database.setVersion(dbVersion);
        setVersion.onsuccess = function () {
          createObjectStore(database);
          getChunkFile(helper.chunks, helper.maxRetries, 0);
        };
      }
      else {
        getChunkFile(helper.chunks, helper.maxRetries, 0);
      }
    }
    else {
      getChunkFile(helper.chunks, helper.maxRetries, 0);
    }
  };

  // For future use. Currently only in latest Firefox versions
  connect.onupgradeneeded = function (event) {
    createObjectStore(event.target.result);
  };
  // End IndexedDB connection handlers

  // Create/open database
  function createObjectStore (database) {
      database.createObjectStore(objectStore);
  }

  function getChunkFile(chunks, maxRetries, currentChunk) {
    var chunk = chunks[currentChunk];
    var url = chunk.candidates[chunk.retries];
    var numChunks = chunks.length;
    var chunkId = chunk.digest;
    var numCandidates = chunk.candidates.length;

    // Create XHR
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";

    // When start downloading
    xhr.onload = function(event) {
      if(xhr.status === 200) {
        var contentLength = xhr.getResponseHeader('Content-Length');
        var blob = xhr.response;
        if(checkChunkIntegrity(contentLength, blob.size, url)) {
          // Put the received blob into IndexedDB
          console.info('Inserting: ' + chunkId + ' blob: ' + blob);
          insertChunkIntoDB(chunks, blob, chunkId, maxRetries, currentChunk, numChunks);
        } else {
          if(chunk.retries < maxRetries && numCandidates >= maxRetries ) {
            console.warn('Retrying because integrity test failed: ' + chunkId);
            chunk.retries = chunk.retries + 1;
            getChunkFile(chunks, maxRetries, currentChunk);
          } else {
          console.error('chunk cannot be downloaded');
          }
        }
      } else {
        if(chunk.retries < maxRetries) {
          console.warn('Retrying because not 200 status code: ' + chunkId);
          chunk.retries = chunk.retries + 1;
          getChunkFile(chunks, maxRetries, currentChunk);
        } else {
          console.error('chunk reached maxRetries');
        }
      }
    };
    // Send XHR
    xhr.send();
  }

  function insertChunkIntoDB(chunks, blob, chunkId, maxRetries, currentChunk, numChunks) {
    var insert = database.transaction([objectStore], IDBTransaction.READ_WRITE).objectStore(objectStore).put(blob, chunkId);
    insert.onerror = function(event) {
      console.info('Transaction: ' +chunkId+ ' failed, rolling back');
      cleanDatabase(getArrayId(chunks), 0);
    }
    insert.onsuccess = function(event) {
      console.info('Transaction: ' +chunkId+ ' success');
      currentChunk = currentChunk + 1;
      if(currentChunk < numChunks) {
        console.info('Downloading the next chunk');
        getChunkFile(chunks, maxRetries, currentChunk);
      } else {
        console.info('Download finished');
        fetchChunksFromDB(getArrayId(chunks), 0, []);
      }
    }
  }

  function getArrayId(chunks) {
    var arrayId = [];
    chunks.forEach(function(chunk) {
      arrayId.push(chunk.digest);
    });
    return arrayId;
  }

  function fetchChunksFromDB(arrayId, index, arrayBlob) {
    var id = arrayId[index];
    console.info('Fetching: ' + id);
    database.transaction([objectStore], IDBTransaction.READ_WRITE).objectStore(objectStore).get(id).onsuccess = function(event) {
      console.info('blob #' + index + ': ' + event.target.result);
      arrayBlob.push(event.target.result);
      if(arrayBlob.length < arrayId.length) {
        index = index + 1;
        fetchChunksFromDB(arrayId, index, arrayBlob);
      } else {
        console.info(arrayBlob);
        var blobJoined = new Blob(arrayBlob);
        var urlFile = URL.createObjectURL(blobJoined);
        console.info(urlFile);
        var link = document.createElement('a');
        link.innerHTML = 'download now';
        link.type = 'application/octet-stream';
        link.download = helper.fileName,
        link.href = urlFile;
        document.body.appendChild(link);

        cleanDatabase(arrayId, 0);
      }
    }
  }

  function cleanDatabase(arrayId, index) {
    var id = arrayId[index];
    database.transaction([objectStore], IDBTransaction.READ_WRITE).objectStore(objectStore).delete(id).onsuccess = function(event) {
      console.info('delete: ' +id+ ' success');
      index = index + 1;
      if(index < arrayId.length) {
        cleanDatabase(arrayId, index);
      } else {
        console.info('Database cleaned successfully');
      }
    }
  }

  function checkChunkIntegrity(contentLength, blobSize, url) {
    if (Number(blobSize) === Number(contentLength)) {
      console.info('chunk '+url+' retrieved successfully');
      return true;
    } else {
      return false;
    }
  }
}

// Setters
function setHelper(resource) {
  helper.maxRetries = resource.numRetries || 2;
  helper.fileName = resource.name;
  helper.id = resource.id;
  var chunks = resource.segments;
  chunks.forEach(function (chunk) {
    var file = {
      downloaded: false,
      retries: 0,
      digest: chunk.digest,
      candidates: chunk.candidates
    }
    helper.chunks.push(file);
  });
}
// End setters<commit_msg>Check for errors at network level<commit_after>'use strict';

var helper = {
  fileName: '',
  maxRetries: 2,
  id: '',
  chunks: []
};

function guardabosques(url) {
  $(document).ready(function () {
    resourceHandler(url);
  });
}

// Resource fetch from a LB
function resourceHandler(url) {
  $.support.cors = true;
  $.ajax({
    type: 'GET',
    url: url,
    success: function(data) {
      var resource = data;
      console.log('json: ' + JSON.stringify(resource));
      downloadHandler(resource);
    },
    dataType: 'json',
    async: true
  });
}
// End resource fetch

/** Download handler **/
function downloadHandler(resource) {
  setHelper(resource);
  console.log('helper: ' + JSON.stringify(helper));
  downloadFile(helper);
}
// End download handler

// Downloads a single file into a blob
function downloadFile(helper) {
  var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB;
  var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction;

  if (IDBTransaction) {
    IDBTransaction.READ_WRITE = IDBTransaction.READ_WRITE || 'readwrite';
    IDBTransaction.READ_ONLY = IDBTransaction.READ_ONLY || 'readonly';
  }

  var dbVersion = 1.0;
  var dbName = 'guardabosques_' + Date.now();
  var connect = indexedDB.open(dbName, dbVersion);
  var objectStore = helper.id;
  var database;

  // IndexedDB connection handlers
  connect.onerror = function(event) {
    console.error("Error creating/accessing IndexedDB database: " + event);
  };

  connect.onsuccess = function(event) {
    console.info("Success creating/accessing IndexedDB database: " + event);

    database = connect.result;
    database.onerror = function (event) {
      console.error("Error creating/accessing IndexedDB database: " + event);
    };
    database.onblocked = function (event) {
      console.log('Database blocked: ' + event);
    };

    // Provisional solution for Chrome using objectStore instead. Will be deprecated
    if (database.setVersion) {
      if (database.version != dbVersion) {
        var setVersion = database.setVersion(dbVersion);
        setVersion.onsuccess = function () {
          createObjectStore(database);
          getChunkFile(helper.chunks, helper.maxRetries, 0);
        };
      }
      else {
        getChunkFile(helper.chunks, helper.maxRetries, 0);
      }
    }
    else {
      getChunkFile(helper.chunks, helper.maxRetries, 0);
    }
  };

  // For future use. Currently only in latest Firefox versions
  connect.onupgradeneeded = function (event) {
    createObjectStore(event.target.result);
  };
  // End IndexedDB connection handlers

  // Create/open database
  function createObjectStore (database) {
      database.createObjectStore(objectStore);
  }

  function getChunkFile(chunks, maxRetries, currentChunk) {
    var chunk = chunks[currentChunk];
    var url = chunk.candidates[chunk.retries];
    var numChunks = chunks.length;
    var chunkId = chunk.digest;
    var numCandidates = chunk.candidates.length;

    // Create XHR
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";

    // Check for errors at network level
    xhr.onerror = function(event) {
      console.error('Error connecting to the server: ' + url + ' ' + event +
      ' Retrying with another candidate...');
      if(chunk.retries < maxRetries && maxRetries <= numCandidates) {
        console.warn('Retrying because integrity test failed: ' + chunkId);
        chunk.retries = chunk.retries + 1;
        getChunkFile(chunks, maxRetries, currentChunk);
      } else {
        console.error('Error downloadin the file');
      }
    }

    // When start downloading
    xhr.onload = function(event) {
      if(xhr.status === 200) {
        var contentLength = xhr.getResponseHeader('Content-Length');
        var blob = xhr.response;
        if(checkChunkIntegrity(contentLength, blob.size, url)) {
          // Put the received blob into IndexedDB
          console.info('Inserting: ' + chunkId + ' blob: ' + blob);
          insertChunkIntoDB(chunks, blob, chunkId, maxRetries, currentChunk, numChunks);
        } else {
          if(chunk.retries < maxRetries && maxRetries <= numCandidates) {
            console.warn('Retrying because integrity test failed: ' + chunkId);
            chunk.retries = chunk.retries + 1;
            getChunkFile(chunks, maxRetries, currentChunk);
          } else {
          console.error('chunk cannot be downloaded');
          }
        }
      } else {
        if(chunk.retries < maxRetries) {
          console.warn('Retrying because not 200 status code: ' + chunkId);
          chunk.retries = chunk.retries + 1;
          getChunkFile(chunks, maxRetries, currentChunk);
        } else {
          console.error('chunk reached maxRetries');
        }
      }
    };
    // Send XHR
    xhr.send();
  }

  function insertChunkIntoDB(chunks, blob, chunkId, maxRetries, currentChunk, numChunks) {
    var insert = database.transaction([objectStore], IDBTransaction.READ_WRITE).objectStore(objectStore).put(blob, chunkId);
    insert.onerror = function(event) {
      console.info('Transaction: ' +chunkId+ ' failed, rolling back');
      cleanDatabase(getArrayId(chunks), 0);
    }
    insert.onsuccess = function(event) {
      console.info('Transaction: ' +chunkId+ ' success');
      currentChunk = currentChunk + 1;
      if(currentChunk < numChunks) {
        console.info('Downloading the next chunk');
        getChunkFile(chunks, maxRetries, currentChunk);
      } else {
        console.info('Download finished');
        fetchChunksFromDB(getArrayId(chunks), 0, []);
      }
    }
  }

  function getArrayId(chunks) {
    var arrayId = [];
    chunks.forEach(function(chunk) {
      arrayId.push(chunk.digest);
    });
    return arrayId;
  }

  function fetchChunksFromDB(arrayId, index, arrayBlob) {
    var id = arrayId[index];
    console.info('Fetching: ' + id);
    database.transaction([objectStore], IDBTransaction.READ_WRITE).objectStore(objectStore).get(id).onsuccess = function(event) {
      console.info('blob #' + index + ': ' + event.target.result);
      arrayBlob.push(event.target.result);
      if(arrayBlob.length < arrayId.length) {
        index = index + 1;
        fetchChunksFromDB(arrayId, index, arrayBlob);
      } else {
        console.info(arrayBlob);
        var blobJoined = new Blob(arrayBlob);
        var urlFile = URL.createObjectURL(blobJoined);
        console.info(urlFile);
        var link = document.createElement('a');
        link.innerHTML = 'download now';
        link.type = 'application/octet-stream';
        link.download = helper.fileName,
        link.href = urlFile;
        document.body.appendChild(link);

        cleanDatabase(arrayId, 0);
      }
    }
  }

  function cleanDatabase(arrayId, index) {
    var id = arrayId[index];
    database.transaction([objectStore], IDBTransaction.READ_WRITE).objectStore(objectStore).delete(id).onsuccess = function(event) {
      console.info('delete: ' +id+ ' success');
      index = index + 1;
      if(index < arrayId.length) {
        cleanDatabase(arrayId, index);
      } else {
        console.info('Database cleaned successfully');
      }
    }
  }

  function checkChunkIntegrity(contentLength, blobSize, url) {
    if (Number(blobSize) === Number(contentLength)) {
      console.info('chunk '+url+' retrieved successfully');
      return true;
    } else {
      return false;
    }
  }
}

// Setters
function setHelper(resource) {
  helper.maxRetries = resource.numRetries || 2;
  helper.fileName = resource.name;
  helper.id = resource.id;
  var chunks = resource.segments;
  chunks.forEach(function (chunk) {
    var file = {
      downloaded: false,
      retries: 0,
      digest: chunk.digest,
      candidates: chunk.candidates
    }
    helper.chunks.push(file);
  });
}
// End setters
<|endoftext|>


<commit_before>(function (_, util) {
    'use strict';

    var ns = util.namespace('kpp.model'),
        User = ns.User,
        Issue = ns.Issue,
        defaultOptions = {
            url: '/api/projects'
        },
        columnKeys = [
            '_id',
            'id',
            'create_user',
            'created_at',
            'github',
            'issues',
            'members',
            'name'
        ];

    ns.Project = ns.Project || Project;

    function Project(o) {
        o = o || {};
        this.opts = _.defaults(o || {}, defaultOptions);

        this.init(o);
    }

    Project.prototype.init = function (o) {
        _.each(columnKeys, function (key) {
            this[key] = o[key];
        }.bind(this));

        this.noAssignedIssues = ko.observableArray();

        this.members = ko.observableArray();
        (o.members || []).forEach(function (member) { this.addMember(member, true); }, this);

        this.issues = ko.observableArray();
        (o.issues || []).forEach(function (issue) { this.addIssue(issue, true); }, this);

        bindIssuesToMembers(this.members, this.issues, this.noAssignedIssues);

        this.noAssignedIssues.sort(Issue.sortFunc);
        this.noAssignedIssues.subscribe(function () {
            this.noAssignedIssues.peek().sort(Issue.sortFunc);
        }, this);

        this.url = createUrl(this.create_user ? this.create_user.userName : 'me',
            this.id, this.name);
    };

    Project.prototype.remove = function () {
        return $.ajax({
            url: this.opts.url + '/' + this.id,
            type: 'delete',
            dataType: 'json'
        });
    };

    Project.prototype.fetch = function (id) {
        return $.ajax({
            url: this.opts.url + '/' + id,
            type: 'get',
            dataType: 'json'
        }).then(function (res) {
            this.init(res.project);
        }.bind(this));
    };

    Project.prototype.assignIssue = function (issueId, memberId) {
        var issue = _.find(this.issues(), function (x) { return x._id() === issueId }),
            member = _.findWhere(this.members(), {_id: memberId}),
            oldAssigneeMember;

        if (!issue) {
            console.error('issue not found');
            return false;
        }

        // pull assigned
        if (issue.assignee()) {
            oldAssigneeMember = _.findWhere(this.members(), {_id: issue.assignee()});
            if (oldAssigneeMember) {
                oldAssigneeMember.unassign(issue);
                issue.stage('issue');
            }
        } else {
            this.noAssignedIssues.remove(issue);
        }

        // assign
        issue.assignee(memberId);
        issue.stage('todo');
        if (member) {
            if (member.assign(issue)) {
                console.error('cannot assign');
                return false;
            }
        } else {
            this.noAssignedIssues.push(issue);
        }
    };

    Project.prototype.updateStage = function (issueId, toStage) {
        var issue = _.find(this.issues(), function (x) { return x._id() === issueId }),
            oldStage, member;

        if (!issue) {
            console.error('issue not found');
            return false;
        }

        member = _.findWhere(this.members(), {_id: issue.assignee()});
        if (!member) {
            console.error('assigned member not found');
            return false;
        }

        oldStage = issue.stage();
        issue.stage(toStage);

        member[oldStage].remove(issue);
        member[toStage].push(issue);
    };

    // direction true: push, false: unshift
    Project.prototype.addIssue = function (issue, direction) {
        var observableIssue = new Issue(issue);
        // assigneeの名前版
        observableIssue.assigneeUserName = ko.computed(function () {
            var userId = observableIssue.assignee();
            var member = _.find(this.members(), function (x) { return x._id === userId; });
            return member ? member.userName : null;
        }, this);

        this.issues[direction ? 'push' : 'unshift'](observableIssue);
    };

    Project.prototype.removeIssue = function (issue) {
        this.issues.remove(issue);
    };

    // direction true: push, false: unshift
    Project.prototype.addMember = function (member, direction) {
        var observableMember = new User(member.user);
        this.members[direction ? 'push' : 'unshift'](observableMember);
    };

    Project.prototype.removeMember = function (member) {
        this.members.remove(member);
    };

    function bindIssuesToMembers(membersObservableArray, issuesObservableArray, noAssignedIssues) {
        var members = membersObservableArray(),
            issues = issuesObservableArray();

        members.forEach(function (member) {
            var userIssues = issues.filter(function (issue) {
                return issue.assignee() && issue.assignee() === member._id;
            });

            Issue.stageTypes.forEach(function (stageName) {
                userIssues.filter(function (issue) {
                    return issue.stage() === stageName;
                }).forEach(function (issue) {
                    member[stageName].push(issue);
                });

                // sort init
                member[stageName].sort(Issue.sortFunc);
                member[stageName].subscribe(function () {
                    member[stageName].peek().sort(Issue.sortFunc);
                });
            });
        });

        issues.filter(function (issue) {
            return !issue.assignee() && issue.stage() === 'issue';
        }).forEach(function (issue) {
            noAssignedIssues.push(issue);
        });

        // issueの追加、削除と連携
        issuesObservableArray.subscribe(function (changes) {
            changes.forEach(function (change) {
                var issue = change.value,
                    member = _.findWhere(membersObservableArray(), {_id: issue.assignee()});

                if (change.status === 'added') {
                    if (member) {
                        member[issue.stage()].unshift(issue);
                    } else {
                        noAssignedIssues.push(issue);
                    }
                } else if (change.status === 'deleted') {
                    if (member) {
                        member[issue.stage()].remove(issue);
                    } else {
                        noAssignedIssues.remove(issue);
                    }
                }
            });
        }, null, 'arrayChange');
    }

    function createUrl (userName, projectId, projectName) {
        return '/users/' + userName + '/projects/' + projectId + '/' + projectName;
    }

}(_, window.nakazawa.util));<commit_msg>assigne後のstageの修正<commit_after>(function (_, util) {
    'use strict';

    var ns = util.namespace('kpp.model'),
        User = ns.User,
        Issue = ns.Issue,
        defaultOptions = {
            url: '/api/projects'
        },
        columnKeys = [
            '_id',
            'id',
            'create_user',
            'created_at',
            'github',
            'issues',
            'members',
            'name'
        ];

    ns.Project = ns.Project || Project;

    function Project(o) {
        o = o || {};
        this.opts = _.defaults(o || {}, defaultOptions);

        this.init(o);
    }

    Project.prototype.init = function (o) {
        _.each(columnKeys, function (key) {
            this[key] = o[key];
        }.bind(this));

        this.noAssignedIssues = ko.observableArray();

        this.members = ko.observableArray();
        (o.members || []).forEach(function (member) { this.addMember(member, true); }, this);

        this.issues = ko.observableArray();
        (o.issues || []).forEach(function (issue) { this.addIssue(issue, true); }, this);

        bindIssuesToMembers(this.members, this.issues, this.noAssignedIssues);

        this.noAssignedIssues.sort(Issue.sortFunc);
        this.noAssignedIssues.subscribe(function () {
            this.noAssignedIssues.peek().sort(Issue.sortFunc);
        }, this);

        this.url = createUrl(this.create_user ? this.create_user.userName : 'me',
            this.id, this.name);
    };

    Project.prototype.remove = function () {
        return $.ajax({
            url: this.opts.url + '/' + this.id,
            type: 'delete',
            dataType: 'json'
        });
    };

    Project.prototype.fetch = function (id) {
        return $.ajax({
            url: this.opts.url + '/' + id,
            type: 'get',
            dataType: 'json'
        }).then(function (res) {
            this.init(res.project);
        }.bind(this));
    };

    Project.prototype.assignIssue = function (issueId, memberId) {
        var issue = _.find(this.issues(), function (x) { return x._id() === issueId }),
            member = _.findWhere(this.members(), {_id: memberId}),
            oldAssigneeMember;

        if (!issue) {
            console.error('issue not found');
            return false;
        }

        // pull assigned
        if (issue.assignee()) {
            oldAssigneeMember = _.findWhere(this.members(), {_id: issue.assignee()});
            if (oldAssigneeMember) {
                oldAssigneeMember.unassign(issue);
            }
        } else {
            this.noAssignedIssues.remove(issue);
        }

        // assign
        issue.assignee(memberId);
        if (member) {
            if (member.assign(issue)) {
                console.error('cannot assign');
                return false;
            }
            issue.stage('todo');
        } else {
            this.noAssignedIssues.push(issue);
            issue.stage('issue');
        }
    };

    Project.prototype.updateStage = function (issueId, toStage) {
        var issue = _.find(this.issues(), function (x) { return x._id() === issueId }),
            oldStage, member;

        if (!issue) {
            console.error('issue not found');
            return false;
        }

        member = _.findWhere(this.members(), {_id: issue.assignee()});
        if (!member) {
            console.error('assigned member not found');
            return false;
        }

        oldStage = issue.stage();
        issue.stage(toStage);

        member[oldStage].remove(issue);
        member[toStage].push(issue);
    };

    // direction true: push, false: unshift
    Project.prototype.addIssue = function (issue, direction) {
        var observableIssue = new Issue(issue);
        // assigneeの名前版
        observableIssue.assigneeUserName = ko.computed(function () {
            var userId = observableIssue.assignee();
            var member = _.find(this.members(), function (x) { return x._id === userId; });
            return member ? member.userName : null;
        }, this);

        this.issues[direction ? 'push' : 'unshift'](observableIssue);
    };

    Project.prototype.removeIssue = function (issue) {
        this.issues.remove(issue);
    };

    // direction true: push, false: unshift
    Project.prototype.addMember = function (member, direction) {
        var observableMember = new User(member.user);
        this.members[direction ? 'push' : 'unshift'](observableMember);
    };

    Project.prototype.removeMember = function (member) {
        this.members.remove(member);
    };

    function bindIssuesToMembers(membersObservableArray, issuesObservableArray, noAssignedIssues) {
        var members = membersObservableArray(),
            issues = issuesObservableArray();

        members.forEach(function (member) {
            var userIssues = issues.filter(function (issue) {
                return issue.assignee() && issue.assignee() === member._id;
            });

            Issue.stageTypes.forEach(function (stageName) {
                userIssues.filter(function (issue) {
                    return issue.stage() === stageName;
                }).forEach(function (issue) {
                    member[stageName].push(issue);
                });

                // sort init
                member[stageName].sort(Issue.sortFunc);
                member[stageName].subscribe(function () {
                    member[stageName].peek().sort(Issue.sortFunc);
                });
            });
        });

        issues.filter(function (issue) {
            return !issue.assignee() && issue.stage() === 'issue';
        }).forEach(function (issue) {
            noAssignedIssues.push(issue);
        });

        // issueの追加、削除と連携
        issuesObservableArray.subscribe(function (changes) {
            changes.forEach(function (change) {
                var issue = change.value,
                    member = _.findWhere(membersObservableArray(), {_id: issue.assignee()});

                if (change.status === 'added') {
                    if (member) {
                        member[issue.stage()].unshift(issue);
                    } else {
                        noAssignedIssues.push(issue);
                    }
                } else if (change.status === 'deleted') {
                    if (member) {
                        member[issue.stage()].remove(issue);
                    } else {
                        noAssignedIssues.remove(issue);
                    }
                }
            });
        }, null, 'arrayChange');
    }

    function createUrl (userName, projectId, projectName) {
        return '/users/' + userName + '/projects/' + projectId + '/' + projectName;
    }

}(_, window.nakazawa.util));<|endoftext|>


<commit_before>$.noConflict();

jQuery(document).ready(function($) {

    $(function() {

        //IMG ARRAY

        var imgarray = [];

        $("#zoom img").each(function () {
            var img = '#' + $(this).attr('id');
            imgarray.push(img);

        });

        // same order as scales_arr
        imgarray.reverse();

        var curImage = imgarray[0];
        var previousValue;
        var val=0;

        // slider value<=>scale string
        //var scales_arr = ["cell","intercellular","liverLobule","liver","organism","all"];//["organism","liver","liverLobe","liverLobule","intercellular","cell"];
        var scale_id;

        //slider mit 5 stufen, regler ist standardm��ig ganz oben
        //the jQuery slider has a build in event that fires every time the handle is moved on the slider called slide.
        //What we have set up here is that every time the slider handle is moved, we get the value and then run a function called valCheck.
        $("#slider").slider({
            orientation: "vertical",
            min: 0,
            max: (scales_arr.length - 1),
            value: current_scale,
            animate:true,
            slide: function (event, ui) {
                //alert("#slider.slide"+ ui.value) ;
                previousValue = val;
                val = ui.value;
                //$('#scale').val(scales_arr[val]) ; // change scale filter for searching
                //valCheck();
                scale_id = "#" + scales_arr[val];
                $(scale_id).click();
            },
        });

        //valCheck() just checks the variable val and then runs a function called imageSwap, passing in the current image and the image we want to display,
        //then we change the current image to the new image.
        function valCheck() {
            if (val > previousValue) {
                //alert("val =" + val + "|| previousValue=" + previousValue);
                imageSwap3(curImage, imgarray[val]);
                curImage = imgarray[val];

            }

            else {
                // alert("val =" + val + " &&  previousValue=" + previousValue);
                imageSwap(curImage, imgarray[val]);
                curImage = imgarray[val];

            }

        }

        //ANIMATION if images are changing!!
        //we�re just passing in the current image and the new image, fading out the current one and then fading in the new image
        function imageSwap(curImage, newImage) {
            /* $(curImage).fadeOut();
             $(newImage).fadeIn(); */
            $(curImage).css({'opacity':'1'});
            $(newImage).css({'opacity':'0'});
            $(newImage).css({'height':'25%', 'marginLeft':'200px', 'marginTop':'105px'});
            $(curImage).css({'display':'inline'});
            $(newImage).css({'display':'inline'});
            $(curImage).animate({
                height: "250%",
                marginLeft: "-120px",
                marginTop: "-222px",
                opacity:'0'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                    //$(this).hide();
                }
            });
            $(newImage).animate({
                height: "100%",
                marginLeft: "0px",
                marginTop: "0px",
                opacity:'1'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                    //this.show();
                }
            });

        }

        function imageSwap2(curImage, newImage) {
            $(curImage).fadeOut();
            $(newImage).fadeIn();

        }

        function imageSwap3(curImage, newImage) {
            $(curImage).css({'opacity':'1'});
            $(newImage).css({'opacity':'0'});
            $(newImage).css({'height':'250%', 'marginLeft':'-120px', 'marginTop':'-222px'});
            $(curImage).css({'display':'inline'});
            $(newImage).css({'display':'inline'});
            $(curImage).animate({
                height: "25%",
                marginLeft: "200px",
                marginTop: "105px",
                opacity:'0'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                    //$(this).hide();
                }
            });
            $(newImage).animate({
                height: "100%",
                marginLeft: "0px",
                marginTop: "0px",
                opacity:'1'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                    //this.show();
                }
            });

            /* alert(newImage + curImage); */
            // alert(val+',' + previousValue);

        }

        //ANIMATION if images are changing!!
        //we�re just passing in the current image and the new image, fading out the current one and then fading in the new image
        function imageSwapElina(curImage, newImage) {
            /* $(curImage).fadeOut();
             $(newImage).fadeIn(); */
            $(curImage).css({'opacity':'1'});

            $(curImage).animate({
                height: "250%",
                marginLeft: "-50px",
                marginTop: "-150px",

            }, 2000);

            $(curImage).fadeOut();

            $(newImage).fadeIn(2000, function() {
                $(newImage).animate({
                    height: "100%",
                    marginLeft: "100px",
                    marginTop: "0px",
                    queue:false,

                }, 1000);
            });

        }

        //We�re just setting val to be the same as num and then running valCheck when the user clicks one of the links, otherwise, the images would only swap when the user slides the handle back and forth. Now the image swap will work if the user either clicks the links or moves the slider.
        function moveSlider(e, num) {
            e.preventDefault();
            $('#slider').slider(
                'value',
                [num]
            );
            val = num;

            // scale_id = "#" + scales_arr[val];
            // $(scale_id).click();
            valCheck();
        }

        scales_arr.each(function( scale ){
            $('#' + scale).click(function(e) {
                moveSlider(e, scales_arr.indexOf(scale));
            });
        });

        //initial status
        previousValue = $('#slider').slider(
            'value'
        );
        val = current_scale;
        scale_id = "#" + scales_arr[val];
        $(scale_id).click();

    });

    /* Source Code: http://atomicrobotdesign.com/blog/web-development/controlling-html-using-the-jquery-ui-slider-and-links/ */
});

function load_tabs() {
    var tabberOptions = {'onLoad':function() {

    }};
    tabberAutomatic(tabberOptions);
}<commit_msg>clean up some bit in scale.js<commit_after>/* Source Code: http://atomicrobotdesign.com/blog/web-development/controlling-html-using-the-jquery-ui-slider-and-links/ */
$.noConflict();

jQuery(document).ready(function($) {
    $(function() {

        var imgarray = [];

        $("#zoom img").each(function () {
            var img = '#' + $(this).attr('id');
            imgarray.push(img);

        });

        // same order as scales_arr
        imgarray.reverse();

        var curImage = imgarray[0];
        var previousValue;
        var val=0;
        var scale_id;

        //slider mit 5 stufen, regler ist standardm��ig ganz oben
        //the jQuery slider has a build in event that fires every time the handle is moved on the slider called slide.
        //What we have set up here is that every time the slider handle is moved, we get the value and then run a function called valCheck.
        $("#slider").slider({
            orientation: "vertical",
            min: 0,
            max: (scales_arr.length - 1),
            value: current_scale,
            animate:true,
            slide: function (event, ui) {
                previousValue = val;
                val = ui.value;
                scale_id = "#" + scales_arr[val];
                $(scale_id).click();
            },
        });

        //valCheck() just checks the variable val and then runs a function called imageSwap, passing in the current image and the image we want to display,
        //then we change the current image to the new image.
        function valCheck() {
            if (val > previousValue) {
                imageSwapZoomOut(curImage, imgarray[val]);
                curImage = imgarray[val];

            }
            else {
                imageSwapZoomIn(curImage, imgarray[val]);
                curImage = imgarray[val];

            }
        }

        //ANIMATION if images are changing!!
        //we�re just passing in the current image and the new image, fading out the current one and then fading in the new image
        function imageSwapZoomIn(curImage, newImage) {
            $(curImage).css({'opacity':'1'});
            $(newImage).css({'opacity':'0'});
            $(newImage).css({'height':'25%', 'marginLeft':'200px', 'marginTop':'105px'});
            $(curImage).css({'display':'inline'});
            $(newImage).css({'display':'inline'});
            $(curImage).animate({
                height: "250%",
                marginLeft: "-120px",
                marginTop: "-222px",
                opacity:'0'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                }
            });
            $(newImage).animate({
                height: "100%",
                marginLeft: "0px",
                marginTop: "0px",
                opacity:'1'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                }
            });

        }

        function imageSwapZoomOut(curImage, newImage) {
            $(curImage).css({'opacity':'1'});
            $(newImage).css({'opacity':'0'});
            $(newImage).css({'height':'250%', 'marginLeft':'-120px', 'marginTop':'-222px'});
            $(curImage).css({'display':'inline'});
            $(newImage).css({'display':'inline'});
            $(curImage).animate({
                height: "25%",
                marginLeft: "200px",
                marginTop: "105px",
                opacity:'0'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                }
            });
            $(newImage).animate({
                height: "100%",
                marginLeft: "0px",
                marginTop: "0px",
                opacity:'1'
            }, {
                duration: 2000,
                queue: false,
                complete: function() {
                }
            });
        }

        //We�re just setting val to be the same as num and then running valCheck when the user clicks one of the links, otherwise, the images would only swap when the user slides the handle back and forth. Now the image swap will work if the user either clicks the links or moves the slider.
        function moveSlider(e, num) {
            e.preventDefault();
            $('#slider').slider(
                'value',
                [num]
            );
            val = num;

            valCheck();
        }

        scales_arr.each(function( scale ){
            $('#' + scale).click(function(e) {
                moveSlider(e, scales_arr.indexOf(scale));
            });
        });

        //initial status
        previousValue = $('#slider').slider(
            'value'
        );
        val = current_scale;
        scale_id = "#" + scales_arr[val];
        $(scale_id).click();

    });
});

function load_tabs() {
    var tabberOptions = {'onLoad':function() {

    }};
    tabberAutomatic(tabberOptions);
}<|endoftext|>


<commit_before>/**
 * Factory to handle photo services.
 * License: MIT
 */

angular.module('app')
.factory('PhotoService', ['$http', '$q', function ($http, $q) {

  var getPhotos = function () {
    var deferred = $q.defer();

    var url = 'https://api.flickr.com/services/feeds/photos_public.gne';
    var params = '?tags=potato&tagmode=all&format=json&jsoncallback=?';

    $.getJSON(url + params, function(data) {
      if (data) deferred.resolve(data);
      else deferred.reject();
    });

    return deferred.promise;
  }

  return {
    'getPhotos': getPhotos
  }
}]);<commit_msg>Updated ajax PhoneService param and dependency injection<commit_after>/**
 * Factory to handle photo services.
 * License: MIT
 */

angular.module('app')
.factory('PhotoService', ['$q', function ($q) {

  var getPhotos = function () {
    var deferred = $q.defer();

    var url = 'https://api.flickr.com/services/feeds/photos_public.gne';
    var params = '?tags=potato&format=json&jsoncallback=?';

    $.getJSON(url + params, function(data) {
      if (data) deferred.resolve(data);
      else deferred.reject();
    });

    return deferred.promise;
  }

  return {
    'getPhotos': getPhotos
  }
}]);<|endoftext|>


<commit_before>// configure our routes
app.config(function($routeProvider, $locationProvider) {
	$routeProvider

	// route for the home page
		.when('/', {
			controller  : 'indexController',
			templateUrl : 'angular/views/index.php'
		})

		// route for the sign in page
		.when('/signin', {
			controller  : 'signinController',
			templateUrl : 'angular/views/signin.php'
		})

		// route for the sign up page
		.when('/signup', {
			controller  : 'signupController',
			templateUrl : 'angular/views/signup.php'
		})
		// route for the the compasss page
		.when('/thecompass', {
			controller  : 'thecompassController',
			templateUrl : 'angular/views/thecompass.php'
		})

		// route for the breweries page
		.when('/breweries', {
			controller  : 'breweriesController',
			templateUrl : 'angular/views/breweries.php'
		})

		// route for the beer page
		.when('/beer', {
			controller  : 'beerController',
			templateUrl : 'angular/views/beer.php'
		})

		// route for the contact page
		.when('/contact', {
			controller  : 'contactController',
			templateUrl : 'angular/views/contact.php'
		})

		// otherwise redirect to home
		.otherwise({
			redirectTo: "/"
		});

	//use the HTML5 History API
	$locationProvider.html5Mode(true);
});
<commit_msg>fiex route-config.js file directories<commit_after>// configure our routes
app.config(function($routeProvider, $locationProvider) {
	$routeProvider

	// route for the home page
		.when('/', {
			controller  : 'homeController',
			templateUrl : 'angular/template/home.php'
		})

		// route for the sign in page
		.when('/signin', {
			controller  : 'signinController',
			templateUrl : 'angular/template/signin.php'
		})

		// route for the sign up page
		.when('/signup', {
			controller  : 'signupController',
			templateUrl : 'angular/template/signup.php'
		})
		// route for the the compasss page
		.when('/thecompass', {
			controller  : 'thecompassController',
			templateUrl : 'angular/template/thecompass.php'
		})

		// route for the breweries page
		.when('/breweries', {
			controller  : 'breweriesController',
			templateUrl : 'angular/template/breweries.php'
		})

		// route for the beer page
		.when('/beer', {
			controller  : 'beerController',
			templateUrl : 'angular/template/beer.php'
		})

		// otherwise redirect to home
		.otherwise({
			redirectTo: "/"
		});

	//use the HTML5 History API
	$locationProvider.html5Mode(true);
});
<|endoftext|>


<commit_before><commit_msg>Added a few more solutions<commit_after><|endoftext|>


<commit_before>define(['base/js/namespace','jquery'], function(Jupyter, $) {
    function does_to_dos_cell_exist() {
        var notebook_cells = Jupyter.notebook.get_cells();
        for (var i = 0; i < notebook_cells.length; i++) {
            var cell = notebook_cells[i];
            if (cell.metadata.id == 'to_dos_cell') {
                return cell;
            }
        }
        return false;
    }

    function place_to_dos_cell() {
        var to_dos_cell = Jupyter.notebook.insert_cell_at_index('markdown', 0);
        var cell_text = '# To Dos\n';
        cell_text += '<button class="to-dos-add-task">Add Task</button>

';
        to_dos_cell.set_text(cell_text);
        to_dos_cell.render();
        to_dos_cell.metadata.id = 'to_dos_cell';
        return to_dos_cell;
    }

    function get_to_dos_cell() {
        var existing_cell = does_to_dos_cell_exist();
        if (existing_cell) {
            var to_dos_cell = existing_cell;
        } else {
            var to_dos_cell = place_to_dos_cell();
        }
        return to_dos_cell;
    }

    function load_to_dos_cell_events() {
        var to_dos_cell = get_to_dos_cell();
        to_dos_cell.element.click(function(event) {
            if ($(event.target).is("button.to-dos-add-task")) {
                var current_content = to_dos_cell.get_text();
                current_content += "<input type='checkbox' class='to-do-item-check'></input>";
                current_content += "<input type='text' class='to-do-item'></input>
";
                to_dos_cell.set_text(current_content);
                to_dos_cell.render();
            }
        });
    }

    function place_to_dos_button() {
        if (!Jupyter.toolbar) {
            $([Jupyter.events]).on("app_initialized.NotebookApp", place_to_dos_button);
        }

        if ($("#create-to-dos-button").length == 0) {
            Jupyter.toolbar.add_buttons_group([
                {
                    'label': 'Add To-do List Cell',
                    'icon': 'fa-list',
                    'callback': load_to_dos_cell_events,
                    'id': 'create-to-dos-button',
                }
            ]);
        }
    }

    function load_ipython_extension() {
        console.log('Loading notebook-to-dos extension');
        place_to_dos_button();
    }

    return {
        load_ipython_extension: load_ipython_extension
    };
});
<commit_msg>Added event handlers for to-do elements<commit_after>define(['base/js/namespace','jquery'], function(Jupyter, $) {
    function does_to_dos_cell_exist() {
        var notebook_cells = Jupyter.notebook.get_cells();
        for (var i = 0; i < notebook_cells.length; i++) {
            var cell = notebook_cells[i];
            if (cell.metadata.id == 'to_dos_cell') {
                return cell;
            }
        }
        return false;
    }

    function place_to_dos_cell() {
        var to_dos_cell = Jupyter.notebook.insert_cell_at_index('markdown', 0);
        var cell_text = '# To Dos\n';
        cell_text += '<button class="to-dos-add-task">Add Task</button>';
        cell_text += '<button class="to-dos-complete-task">Complete Task</button>';
        cell_text += '

';
        to_dos_cell.set_text(cell_text);
        to_dos_cell.render();
        to_dos_cell.metadata.id = 'to_dos_cell';
        return to_dos_cell;
    }

    function get_to_dos_cell() {
        var existing_cell = does_to_dos_cell_exist();
        if (existing_cell) {
            var to_dos_cell = existing_cell;
        } else {
            var to_dos_cell = place_to_dos_cell();
        }
        return to_dos_cell;
    }

    function load_to_dos_cell_events() {
        var to_dos_cell = get_to_dos_cell();
        console.log(to_dos_cell.element);
        console.log(to_dos_cell.element.find("button.to-dos-add-task"));

        to_dos_cell.element.find("button.to-dos-add-task").bind('click', function() {
            var current_content = to_dos_cell.get_text();
            current_content += "<input type='checkbox' class='to-do-item-check'></input>";
            current_content += "<input type='text' class='to-do-item'></input>
";
            to_dos_cell.set_text(current_content);
            to_dos_cell.render();
        });

        to_dos_cell.element.find("input.to-do-item").bind('focusin', function() {
            Jupyter.notebook.keyboard_manager.disable();
        });
        to_dos_cell.element.find("input.to-do-item").bind('focusout', function() {
            Jupyter.notebook.keyboard_manager.enable();
        });
    }

    function place_to_dos_button() {
        if (!Jupyter.toolbar) {
            $([Jupyter.events]).on("app_initialized.NotebookApp", place_to_dos_button);
        }

        if ($("#create-to-dos-button").length == 0) {
            Jupyter.toolbar.add_buttons_group([
                {
                    'label': 'Add To-do List Cell',
                    'icon': 'fa-list',
                    'callback': load_to_dos_cell_events,
                    'id': 'create-to-dos-button',
                }
            ]);
        }

        load_to_dos_cell_events();
    }

    function load_ipython_extension() {
        console.log('Loading notebook-to-dos extension');
        place_to_dos_button();
    }

    return {
        load_ipython_extension: load_ipython_extension
    };
});
<|endoftext|>