<commit_before>var ref = new Firebase("https://halle.firebaseio.com");
var fbData;
var userData;

$(document).on("pagecreate", "#landing-screen", function(e, data){

  $('#login').on('click', function(e){
    e.preventDefault();

    fbAuth().then(function(authData){
      fbData = authData;
      ajaxLogin(authData);
      setProfile(authData);
    });
  });
});

$(document).on("pagecreate", "#page-map", function(e, data){
  var mapOptions = {
    zoom: 13,
    disableDefaultUI: true,
    zoomControl: true
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  markCenter(map);
  loadSpaces();

//______________________________________
var markers = [ ]

  // var defaultBounds = new google.maps.LatLngBounds(
  //     new google.maps.LatLng(-33.8902, 151.1759),
  //     new google.maps.LatLng(-33.8474, 151.2631));
  // map.fitBounds(defaultBounds);

// Create the search box and link it to the UI element.
  var input = (document.getElementById('pac-input'));
  map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(input);

  var searchBox = new google.maps.places.SearchBox(input);

  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
  google.maps.event.addListener(searchBox, 'places_changed', function() {
        var places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }
    for (var i = 0, marker; marker = markers[i]; i++) {
      marker.setMap(null);
    }

    // For each place, get the icon, place name, and location.
    markers = [];
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
      var image = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };

      // Create a marker for each place.
      // var marker = new google.maps.Marker({
      //   map: map,
      //   icon: image,
      //   title: place.name,
      //   position: place.geometry.location
      // });

      map.setCenter(place.geometry.location);
      bounds.extend(place.geometry.location);
    }
  });

    // Bias the SearchBox results towards places that are within the bounds of the
  // current map's viewport.
  // google.maps.event.addListener(map, 'bounds_changed', function() {
  //   var bounds = map.getBounds();
  //   searchBox.setBounds(bounds);
  // });
//______________________________________

  ref.on('child_added', function(childSnapshot, prevChildName){
    liveDrop(childSnapshot, prevChildName);
  });

  $('#create-space').on('click', function(e){
    e.preventDefault();
    $('#post-space').popup("open", {
      overlayTheme: "a",
      positionTo: "window",
    });
    $('#add-space').on('click', function(e){
      addSpace(e);
    });
  });

  $('#claim').on('click', function(e){
    e.preventDefault();
    claimSpace(e);
  });

  $('#center').on('click', function(e){
    e.preventDefault();
    centerMap(map);
  });

  $('#profile').on('click', function(e){
    e.preventDefault();
    $('#user').panel("open", {
      overlayTheme: "a",
      positionTo: "window",
    });
  });
});

//function definitions only ++++++++++++++++++++++++++++++++++++++++++++++++++++++

var fbAuth = function(){
  var promise = new Promise(function(resolve, reject){
    ref.authWithOAuthPopup("facebook", function(error, authData) {
      if (error) {
        alert("login failed!");
        reject(error);
      } else {
        resolve(authData);
      };
    });
  })
  return promise;
};

var setProfile = function(authData){
  var userId = authData.facebook.id;
  var name = authData.facebook.cachedUserProfile.name;
  var photo = authData.facebook.cachedUserProfile.picture.data.url;
  $('#user h4').text(name);
  $('#user h2').text('Carma:');
  $('#user img').attr('src', photo);
};

var ajaxLogin = function(authData){
  userId = authData.facebook.id;
  var ajaxData = {user:{oauth_id:userId}};
  $.ajax({
    url: 'http://calm-island-3256.herokuapp.com/users/'+userId+'/identify',
    // url: 'http://localhost:3000/users/'+userId+'/identify',
    type: 'GET',
    data: ajaxData
  }).done(function(response) {
    userData = response;
    window.location.href = '#page-map';
  }).fail(function() {
    alert("YOU'RE A FAILURE");
  });
};

var getLocation = function() {
  var promise = new Promise(function(resolve, reject){
    navigator.geolocation.getCurrentPosition(function(position){
      if (position) {
        resolve(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
      } else {
        reject();
      };
    });
  });
  return promise;
};

var centerMap = function(map){
  getLocation().then(function(response){
    map.setCenter(response);
  });
};

var markCenter = function(map){
  getLocation().then(function(response){
    map.setCenter(response);
    var marker = new google.maps.Marker({
      position: response,
      map: map,
      icon: currentLocation
    });
  });
};

var addSpace = function(e){
  getLocation().then(function(response){
    var note = $('#note').val();
    var latitude  = response.A;
    var longitude = response.F;
    var data      = {space:{latitude:+latitude, longitude:+longitude, note:note}};
    var headers   = '{"Content-Type":"application/json"}';

    $.ajax({
      url: 'http://calm-island-3256.herokuapp.com/spaces',
      // url: 'http://localhost:3000/spaces',
      type: "POST",
      data: data,
      headers: headers
    }).done(function(response) {
      $('#add-space').remove();
      $('#note').remove();
      $('#popup-par').text('Added √');
      setTimeout(function () {
        $('#post-space').popup('close');
      }, 1500);
        // replace with a toast notification
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(response.latitude,response.longitude),
        map: map,
        title:  response.note,
        icon: markerSelect(response),
        id: response.id,
        creation: response.converted_time,
        animation: google.maps.Animation.DROP,
        zIndex: google.maps.Marker.MAX_ZINDEX + 1
      });
    }).fail(function(response) {
      alert("shits fucked up");
    });
  });
}

var claimSpace = function(e){
  var spaceId = e.target.name
  var headers = '{"Content-Type":"application/json"}';
  $.ajax({
    url: 'http://calm-island-3256.herokuapp.com/spaces/'+spaceId,
    // url: 'http://localhost:3000/spaces/'+spaceId,
    type: 'PUT',
    headers: headers,
    data: '' //test without this
  }).done(function(response) {
    var data = {user:{consume: true}};
    $.ajax({
      url: 'http://calm-island-3256.herokuapp.com/users/'+fbData.facebook.id,
      // url: 'http://localhost:3000/users/'+fbData.facebook.id,
      type: 'PUT',
      data: data
    }).done(function(response){
      $('#space-options p').remove();
      $('#space-options a').remove();
      $('#space-options button').remove();
      $('#space-options h4').text('Claimed √');
      setTimeout(function () {
        $('#space-options').popup('close');
      }, 1500);
      // replace with a toast notification
    }).fail(function(response){
      console.log('claim space user update failed');
    });
    var destination = response.latitude +","+ response.longitude
    calcRoute(destination, map);
  }).fail(function(response) {
    console.log("claim space ajax call failed");
  });
};

var calcRoute = function(finalDestination, map) {
  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplay.setMap(map);

  getLocation().then(function(currentLocation){
    var request = {
      origin: currentLocation,
      destination: finalDestination,
      travelMode: google.maps.TravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
      else{alert("Server Error: Directions Unavailable")}
    });
  });
};

var loadSpaces = function(){
  $.ajax({
    url: 'http://calm-island-3256.herokuapp.com',
    // url: 'http://localhost:3000',
    type: "GET",
  }).done(function(response){
    parkingSpots = response
    for(i = 0; i < parkingSpots.length; i++){
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(parkingSpots[i].latitude,parkingSpots[i].longitude),
        map: map,
        title:  parkingSpots[i].note,
        icon: markerSelect(parkingSpots[i]), //set marker according to age
        id: parkingSpots[i].id,
        creation: parkingSpots[i].converted_time
      });
      google.maps.event.addListener(marker, 'click', spaceDetails);
    };
  });
}

var spaceDetails = function() {
  spaceId = this.id;
  $('#claim').attr('name', spaceId);
  $('#space-options').popup("open", {
    overlayTheme: "a",
    positionTo: "window",
  });
  $('p').text(this.title);
};

var markerSelect = function(spaceObject){
  var creation = spaceObject.converted_time;
  if ((Date.now() - creation) <= (5*60000)){
    return spaceFresh;
  } else {
    return spaceStale;
  };
};

var liveDrop = function(childSnapshot, prevChildName){
  var newChild = childSnapshot.val();
  var newChildKey = Object.keys(newChild)[0];
  var spaceObj = JSON.parse(newChild[newChildKey]);

  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(spaceObj.latitude,spaceObj.longitude),
    map: map,
    animation: google.maps.Animation.DROP,
    title:  spaceObj.note,
    icon: markerSelect(spaceObj), //set marker according to age
    id: spaceObj.id,
    creation: spaceObj.converted_time
  });
  google.maps.event.addListener(marker, 'click', spaceDetails);
  console.log("Hit firebase");
}

// Map format???
  // $(".ui-content", this).css({
   // height: $(window).height(),
   // width: $(window).width()
// });

// Space markers CSS -----------------------------------------
var currentLocation = {
  path: fontawesome.markers.LOCATION_ARROW,
  scale: 0.55,
  strokeWeight: 0.2,
  strokeColor: 'black',
  strokeOpacity: 1,
  fillColor: '#263238',
  fillOpacity: 1
};
var spaceFresh = {
  path: fontawesome.markers.MAP_MARKER,
  scale: 0.55,
  strokeWeight: 0.2,
  strokeColor: 'black',
  strokeOpacity: 1,
  fillColor: '#ED273E',
  fillOpacity: 1
};
var spaceStale = {
  path: fontawesome.markers.MAP_MARKER,
  scale: 0.55,
  strokeWeight: 0.2,
  strokeColor: 'black',
  strokeOpacity: 1,
  fillColor: '#A282F9',
  fillOpacity: 1
};<commit_msg>Clean up search function<commit_after>var ref = new Firebase("https://halle.firebaseio.com");
var fbData;
var userData;

$(document).on("pagecreate", "#landing-screen", function(e, data){

  $('#login').on('click', function(e){
    e.preventDefault();

    fbAuth().then(function(authData){
      fbData = authData;
      ajaxLogin(authData);
      setProfile(authData);
    });
  });
});

$(document).on("pagecreate", "#page-map", function(e, data){
  var mapOptions = {
    zoom: 13,
    disableDefaultUI: true,
    zoomControl: true
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  markCenter(map);
  loadSpaces();

  ref.on('child_added', function(childSnapshot, prevChildName){
    liveDrop(childSnapshot, prevChildName);
  });

  $('#create-space').on('click', function(e){
    e.preventDefault();
    $('#post-space').popup("open", {
      overlayTheme: "a",
      positionTo: "window",
    });
    $('#add-space').on('click', function(e){
      addSpace(e);
    });
  });

  $('#claim').on('click', function(e){
    e.preventDefault();
    claimSpace(e);
  });

  $('#center').on('click', function(e){
    e.preventDefault();
    centerMap(map);
  });

  $('#profile').on('click', function(e){
    e.preventDefault();
    $('#user').panel("open", {
      overlayTheme: "a",
      positionTo: "window",
    });
  });
//______________________________________

// Create the search box and link it to the UI element.
  var input = (document.getElementById('pac-input'));
  var searchBox = new google.maps.places.SearchBox((input));

  map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(input);

  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
  google.maps.event.addListener(searchBox, 'places_changed', function(){
    localSearch(searchBox)
  });

//______________________________________

});

//function definitions only ++++++++++++++++++++++++++++++++++++++++++++++++++++++

var fbAuth = function(){
  var promise = new Promise(function(resolve, reject){
    ref.authWithOAuthPopup("facebook", function(error, authData) {
      if (error) {
        alert("login failed!");
        reject(error);
      } else {
        resolve(authData);
      };
    });
  })
  return promise;
};

var setProfile = function(authData){
  var userId = authData.facebook.id;
  var name = authData.facebook.cachedUserProfile.name;
  var photo = authData.facebook.cachedUserProfile.picture.data.url;
  $('#user h4').text(name);
  $('#user h2').text('Carma:');
  $('#user img').attr('src', photo);
};

var ajaxLogin = function(authData){
  userId = authData.facebook.id;
  var ajaxData = {user:{oauth_id:userId}};
  $.ajax({
    url: 'http://calm-island-3256.herokuapp.com/users/'+userId+'/identify',
    // url: 'http://localhost:3000/users/'+userId+'/identify',
    type: 'GET',
    data: ajaxData
  }).done(function(response) {
    userData = response;
    window.location.href = '#page-map';
  }).fail(function() {
    alert("YOU'RE A FAILURE");
  });
};

var getLocation = function() {
  var promise = new Promise(function(resolve, reject){
    navigator.geolocation.getCurrentPosition(function(position){
      if (position) {
        resolve(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
      } else {
        reject();
      };
    });
  });
  return promise;
};

var centerMap = function(map){
  getLocation().then(function(response){
    map.setCenter(response);
  });
};

var markCenter = function(map){
  getLocation().then(function(response){
    map.setCenter(response);
    var marker = new google.maps.Marker({
      position: response,
      map: map,
      icon: currentLocation
    });
  });
};

var addSpace = function(e){
  getLocation().then(function(response){
    var note = $('#note').val();
    var latitude  = response.A;
    var longitude = response.F;
    var data      = {space:{latitude:+latitude, longitude:+longitude, note:note}};
    var headers   = '{"Content-Type":"application/json"}';

    $.ajax({
      url: 'http://calm-island-3256.herokuapp.com/spaces',
      // url: 'http://localhost:3000/spaces',
      type: "POST",
      data: data,
      headers: headers
    }).done(function(response) {
      $('#add-space').remove();
      $('#note').remove();
      $('#popup-par').text('Added √');
      setTimeout(function () {
        $('#post-space').popup('close');
      }, 1500);
        // replace with a toast notification
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(response.latitude,response.longitude),
        map: map,
        title:  response.note,
        icon: markerSelect(response),
        id: response.id,
        creation: response.converted_time,
        animation: google.maps.Animation.DROP,
        zIndex: google.maps.Marker.MAX_ZINDEX + 1
      });
    }).fail(function(response) {
      alert("shits fucked up");
    });
  });
}

var claimSpace = function(e){
  var spaceId = e.target.name
  var headers = '{"Content-Type":"application/json"}';
  $.ajax({
    url: 'http://calm-island-3256.herokuapp.com/spaces/'+spaceId,
    // url: 'http://localhost:3000/spaces/'+spaceId,
    type: 'PUT',
    headers: headers,
    data: '' //test without this
  }).done(function(response) {
    var data = {user:{consume: true}};
    $.ajax({
      url: 'http://calm-island-3256.herokuapp.com/users/'+fbData.facebook.id,
      // url: 'http://localhost:3000/users/'+fbData.facebook.id,
      type: 'PUT',
      data: data
    }).done(function(response){
      $('#space-options p').remove();
      $('#space-options a').remove();
      $('#space-options button').remove();
      $('#space-options h4').text('Claimed √');
      setTimeout(function () {
        $('#space-options').popup('close');
      }, 1500);
      // replace with a toast notification
    }).fail(function(response){
      console.log('claim space user update failed');
    });
    var destination = response.latitude +","+ response.longitude
    calcRoute(destination, map);
  }).fail(function(response) {
    console.log("claim space ajax call failed");
  });
};

var calcRoute = function(finalDestination, map) {
  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplay.setMap(map);

  getLocation().then(function(currentLocation){
    var request = {
      origin: currentLocation,
      destination: finalDestination,
      travelMode: google.maps.TravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
      else{alert("Server Error: Directions Unavailable")}
    });
  });
};

var loadSpaces = function(){
  $.ajax({
    url: 'http://calm-island-3256.herokuapp.com',
    // url: 'http://localhost:3000',
    type: "GET",
  }).done(function(response){
    parkingSpots = response
    for(i = 0; i < parkingSpots.length; i++){
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(parkingSpots[i].latitude,parkingSpots[i].longitude),
        map: map,
        title:  parkingSpots[i].note,
        icon: markerSelect(parkingSpots[i]), //set marker according to age
        id: parkingSpots[i].id,
        creation: parkingSpots[i].converted_time
      });
      google.maps.event.addListener(marker, 'click', spaceDetails);
    };
  });
}

var spaceDetails = function() {
  spaceId = this.id;
  $('#claim').attr('name', spaceId);
  $('#space-options').popup("open", {
    overlayTheme: "a",
    positionTo: "window",
  });
  $('p').text(this.title);
};

var markerSelect = function(spaceObject){
  var creation = spaceObject.converted_time;
  if ((Date.now() - creation) <= (5*60000)){
    return spaceFresh;
  } else {
    return spaceStale;
  };
};

var liveDrop = function(childSnapshot, prevChildName){
  var newChild = childSnapshot.val();
  var newChildKey = Object.keys(newChild)[0];
  var spaceObj = JSON.parse(newChild[newChildKey]);

  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(spaceObj.latitude,spaceObj.longitude),
    map: map,
    animation: google.maps.Animation.DROP,
    title:  spaceObj.note,
    icon: markerSelect(spaceObj), //set marker according to age
    id: spaceObj.id,
    creation: spaceObj.converted_time
  });
  google.maps.event.addListener(marker, 'click', spaceDetails);
  console.log("Hit firebase");
}

//Search
var localSearch = function(searchObject){
  var places = searchObject.getPlaces();
    if (typeof searchMarker !== 'undefined') {
      searchMarker.setMap(null)
    };

  for (var i = 0, place; place = places[i]; i++) {
    searchMarker = new google.maps.Marker({
      position: place.geometry.location,
      map: map,
      icon: searchLocation
      // animation: google.maps.Animation.DROP
    });
    map.setZoom(16);
    map.panTo(place.geometry.location);
  }
};

// Map format???
  // $(".ui-content", this).css({
   // height: $(window).height(),
   // width: $(window).width()
// });

// Space markers CSS -----------------------------------------
var currentLocation = {
  path: fontawesome.markers.LOCATION_ARROW,
  scale: 0.55,
  strokeWeight: 0.2,
  strokeColor: 'black',
  strokeOpacity: 1,
  fillColor: '#263238',
  fillOpacity: 1
};
var spaceFresh = {
  path: fontawesome.markers.MAP_MARKER,
  scale: 0.55,
  strokeWeight: 0.2,
  strokeColor: 'black',
  strokeOpacity: 1,
  fillColor: '#ED273E',
  fillOpacity: 1
};
var spaceStale = {
  path: fontawesome.markers.MAP_MARKER,
  scale: 0.55,
  strokeWeight: 0.2,
  strokeColor: 'black',
  strokeOpacity: 1,
  fillColor: '#A282F9',
  fillOpacity: 1
};

var searchLocation = {
  path: fontawesome.markers.UNIVERSITY,
  scale: 0.25,
  strokeWeight: 0.2,
  strokeColor: 'black',
  strokeOpacity: 1,
  fillColor: 'black',
  fillOpacity: 1

}<|endoftext|>


<commit_before>

window.onload=function()
{
	window.bgnum=4;//背景图片数量
	var myFirebaseRef = new Firebase("https://five-african.firebaseio.com/opentimes");
	myFirebaseRef.on("value", function(snapshot) {
		$(".good").text("已有"+snapshot.val()+"人点赞");
	});
	window.currentrandom=1;
	var audio = $("#audio")["0"];
	var disk = $('.disk');
	var cursor = $(".cursor");
	var paused=true;
	window.loopone = false;
	window.shuffle = false;
	$.getJSON("members.json",parseMembers);
	$("#progressbar").width(0);

	//进度条音量条
	$(".progress").mousedown(starDrag = function(ev) {
                ev.stopPropagation();
                var origX = ev.clientX;
                var origW = $(this).prev().width();
                var target = $(this).prev();
                var type = $(this).attr("id");
                $(document).mousemove(doDrag = function(ev){
                    ev.preventDefault();
                    var moveX = ev.clientX - origX;
                    //console.log(moveX/target.parent().width()*100);
                    var value = (origW+moveX)/target.parent().width();
                    value=value>1?1:(value<0?0:value);
                    target.width(value*100+"%");
                    //console.log(value*100);
                    switch(type)
                    {
                    	case "volume":audio.changeVolumeTo(value);break;
                    	case "progress":audio.setCurrentTime(value*audio.duration);break;
                    }
                });
                $(document).mouseup(stopDrag = function(){
                    $(document).unbind("mousemove",doDrag);
                    $(document).unbind("mouseup",stopDrag);
                });
            });
	$(".progress").bind("touchstart",starTDrag = function(ev) {
                ev.stopPropagation();
                var origX = ev.originalEvent.targetTouches["0"].clientX;
                console.log(ev.originalEvent.targetTouches["0"].clientX);
                var origW = $(this).prev().width();
                var target = $(this).prev();
                var type = $(this).attr("id");
                $(document).bind("touchmove",doTDrag = function(ev){
                    ev.preventDefault();
                    var moveX = ev.originalEvent.targetTouches["0"].clientX - origX;
                    console.log(moveX/target.parent().width()*100);
                    var value = (origW+moveX)/target.parent().width();
                    value=value>1?1:(value<0?0:value);
                    target.width(value*100+"%");
                    console.log(value*100);
                    switch(type)
                    {
                    	case "volume":audio.changeVolumeTo(value);break;
                    	case "progress":audio.setCurrentTime(value*audio.duration);break;
                    }
                });
                $(document).bind("touchend",stopTDrag = function(){
                    $(document).unbind("touchmove",doTDrag);
                    $(document).unbind("touchend",stopTDrag);
                });
            });

	//循环按钮
	$('#loop').click(function(){
		if(window.loopone){//window.loopone->window.shuffle
			$(this).addClass('window.shuffle').removeClass('window.loopone');
			audio.loop = false;
			window.loopone=false;
			window.shuffle=true;
		}
		else if(window.shuffle)//window.shuffle->loop
		{
			$(this).addClass('loop').removeClass('window.shuffle');
			audio.loop = false;
			window.loopone = false;
			window.shuffle=false;
		}
		else //loop->window.loopone
		{
			$(this).addClass('window.loopone').removeClass('loop');
			audio.loop = true;
			window.loopone = true;
			window.shuffle=false;
		}

	});
	$("#list").click(listshow = function(e){
		e.stopPropagation();
		if(!listshow.shown){
			$(".listcontainer").show().css("animation","listshow 0.7s linear 0s forwards").css("-webkit-animation","listshow 0.7s linear 0s forwards").css("-o-animation","listshow 0.7s linear 0s forwards").css("-moz-animation","listshow 0.7s linear 0s forwards").delay(700);listshow.shown=true;
		}else
		{
			$(".listcontainer").css("animation","listhide 0.7s linear 0s forwards").css("-webkit-animation","listhide 0.7s linear 0s forwards").css("-o-animation","listhide 0.7s linear 0s forwards").css("-moz-animation","listhide 0.7s linear 0s forwards").delay(700).hide(0);listshow.shown=false;
		}
	});
	$(".diskborder").click(function(e){
		e.stopPropagation();
		$(".cursoroutter").fadeToggle();
		$(".outtervolumebar").fadeToggle();
		$(".diskborder").fadeToggle();
		$("#membersshow").fadeToggle();
		$(".funcs>:first-child").fadeToggle();

	});
	$("#membersshow").click(function(e){
		e.stopPropagation();
		$(".cursoroutter").fadeToggle();
		$(".outtervolumebar").fadeToggle();
		$(".diskborder").fadeToggle();
		$("#membersshow").fadeToggle();
		$(".funcs>:first-child").fadeToggle();
	});
	$(".love").click(function(e)
	{
		$(this)[0].flag==undefined&&($(this)[0].flag=false);
		e.stopPropagation();
		if($(this)[0].flag)
		{
			$(this).addClass("love").removeClass("loved");
			$(this)[0].flag=false;
		}
		else
		{
			$(this).addClass("loved").removeClass("love");
			myFirebaseRef.transaction(function(opentimes) {

				$(".good").fadeToggle().text("已有"+(opentimes++)+"人点赞").delay(500).fadeToggle();
				return opentimes;
			});
			$(this)[0].flag=true;
		}
	})

	//读取媒体信息
	$(audio).bind("loadedmetadata",function(){
                var totalTime = formatTime(this.duration);
                $($("div").find("span")["1"]).text(totalTime);
                $("#progressbar").width(0);

				//播放暂停
				$("#play").click(function(e)
				{
					e.stopPropagation();
					if(paused)
					{
						audio.play();
					}
					else
					{
						audio.pause();
					}
				});

            });
	$(audio).trigger("loadedmetadata");

	//播放时间更新
	$(audio).bind("timeupdate",function(){
                var duration = this.duration;
                var curTime = this.currentTime;
                var percentage = curTime/duration * 100;
                $("#progressbar").css("width",percentage + "%");
                var passedTime = formatTime(curTime);
                $($("div").find("span")["0"]).text(passedTime);
            });

	//音频播放
	$(audio).bind("play",function(){
			$("#play").addClass('pause').removeClass('play');
			disk.css("animation-play-state","running");
			disk.css("-webkit-animation-play-state","running");
			disk.css("-o-animation-play-state","running");
			disk.css("-moz-animation-play-state","running");
			cursor.css("transform","rotate(-20deg)");
			cursor.css("-webkit-transform","rotate(-20deg)");
			cursor.css("-o-transform","rotate(-20deg)");
			cursor.css("-moztransform","rotate(-20deg)");
			cursor.css("animation","cursorclockwise 0.5s linear 0s forwards");
			cursor.css("-webkit-animation","cursorclockwise 0.5s linear 0s forwards");
			cursor.css("-o-animation","cursorclockwise 0.5s linear 0s forwards");
			cursor.css("-moz-animation","cursorclockwise 0.5s linear 0s forwards");
			paused=false;
            });

	//音频暂停
	$(audio).bind("pause",function(){
            $("#play").addClass('play').removeClass('pause');
			disk.css("animation-play-state","paused");
			disk.css("-wevkit-animation-play-state","paused");
			disk.css("-o-animation-play-state","paused");
			disk.css("-mozanimation-play-state","paused");
			cursor.css("transform","rotate(0deg)");
			cursor.css("-webkit-transform","rotate(0deg)");
			cursor.css("-o-transform","rotate(0deg)");
			cursor.css("-moz-transform","rotate(0deg)");
			cursor.css("animation","cursorcounter 0.5s linear 0s forwards");
			cursor.css("-webkit-animation","cursorcounter 0.5s linear 0s forwards");
			cursor.css("-o-animation","cursorcounter 0.5s linear 0s forwards");
			cursor.css("-moz-animation","cursorcounter 0.5s linear 0s forwards");
			paused=true;
            });

	//音频播放结束
	$(audio).bind("ended",function(){
		disk.css("animation-play-state","paused");
			disk.css("-wevkit-animation-play-state","paused");
			disk.css("-o-animation-play-state","paused");
			disk.css("-mozanimation-play-state","paused");
		paused=true;
		$("#play").addClass('play').removeClass('pause');
		if (!window.loopone) {
                $(".next").triggerHandler("click");
            }
        });
	//下一曲
	$(".next").click(function(){
		if(window.shuffle){
			window.currentSrcIndex = Math.ceil(Math.random()*window.memberlist.length)-1;
			window.currentSrcIndex < 0 && (window.currentSrcIndex = 0);
			window.currentSrcIndex = window.currentSrcIndex % window.memberlist.length;
		}
		else
        	++window.currentSrcIndex > window.memberlist.length - 1 && (window.currentSrcIndex = 0);

        audio.setCurrentSrc(window.currentSrcIndex);
		audio.play();
		audio.loop = window.loopone;
    });
    //上一曲
    $(".prev").click(function(){
    	if(window.shuffle){
			window.currentSrcIndex = Math.ceil(Math.random()*window.memberlist.length)-1;
			window.currentSrcIndex < 0 && (window.currentSrcIndex = 0);
			window.currentSrcIndex = window.currentSrcIndex % window.memberlist.length;
		}
		else
        	--window.currentSrcIndex < 0 && (window.currentSrcIndex = 0);
        var currentSrc = window.memberlist[window.currentSrcIndex].soundsrc;
        audio.setCurrentSrc(window.currentSrcIndex);
		audio.play();
		audio.loop = window.loopone;
    });

}
HTMLAudioElement.prototype.changeVolumeTo = function(volume){
    this.volume = volume;
}
HTMLAudioElement.prototype.setCurrentTime = function(currentTime){
	// $($("div").find("span")["0"]).text(formatTime(currentTime));
    this.currentTime = currentTime;
}
HTMLAudioElement.prototype.setCurrentSrc = function(currentSrcIndex){

	var val = Math.ceil(Math.random()*window.bgnum);
	val==0&&(val=1);
	currentrandom==val&&(val=(val+1)%window.bgnum);
	currentrandom=val;
	// $("#containerbody").fadeOut("fast",function(){$(this).css("background-image","url(\"img/bg"+val+".jpg\")");$(this).fadeIn()});
	// $(".mask_bg").fadeOut("fast",function(){$(this).css("background-image","url(\"img/bg"+val+".jpg\")");$(this).fadeIn()});
	$("#containerbody").css("background-image","url(\"img/bg"+val+".jpg\")");
	$(".mask_bg").css("background-image","url(\"img/bg"+val+".jpg\")");
	window.currentSrcIndex = currentSrcIndex;
	var currentSrc = window.memberlist[window.currentSrcIndex].soundsrc;
    $("#currenttitle").text(window.memberlist[window.currentSrcIndex].soundtitle);
	$("#currentartist").text(window.memberlist[window.currentSrcIndex].soundartist);
	$(".disk").css("background","img/"+window.memberlist[window.currentSrcIndex].soundtitle);
	$(".diskmask").css("background","img/"+window.memberlist[window.currentSrcIndex].soundtitle);
	$(".listcontainer li").css("background-color","");
	$("[data-id="+window.currentSrcIndex+"]").css("background-color","rgba(255,0,0,0.3)");
	$("#membersshow #"+window.memberlist[currentSrcIndex].membername+" .containerwrap").load('content/'+window.memberlist[currentSrcIndex].memberintro+' .main-border');
	$("#membersshow .active").removeClass("active");
	$("#membersshow #"+window.memberlist[currentSrcIndex].membername).addClass("active");
	$(".download").click(function()
	{
		 window.open(currentSrc,'_blank');
	});
    this.src = currentSrc;
}
function formatTime(time) {
    var minutes = parseInt(time/60);
    var seconds = parseInt(time%60);
    seconds<10 && (seconds = "0" + seconds);
    minutes<10 && (minutes = "0" + minutes);
    return isNaN(time)?"∞":minutes + ":" + seconds;
};

function parseMembers(data)
{
	window.memberlist;
	window.currentSrcIndex=0;
	window.memberlist = new Array();
	$.each(data,function(i,content)
	{
		window.memberlist[i]=content;
		$(".listcontainer ul").append('

'+content["membername"]+'
'+content["soundtitle"]+''+content["soundartist"]+'
'+content["soundtime"]+'

');
		$("#membersshow").append('

');
	});
	$("#membersshow #"+window.memberlist[0].membername+" .containerwrap").load('content/'+window.memberlist[0].memberintro+' .main-border');
	audio.setCurrentSrc(0);
	$(".musiclist").click(function()
	{
		audio.setCurrentSrc($(this).attr("data-id"));
		audio.play();
		audio.loop = window.loopone;
	})
}<commit_msg>又改错东西了烦躁<commit_after>

window.onload=function()
{
	window.bgnum=4;//背景图片数量
	var myFirebaseRef = new Firebase("https://five-african.firebaseio.com/opentimes");
	myFirebaseRef.on("value", function(snapshot) {
		$(".good").text("已有"+snapshot.val()+"人点赞");
	});
	window.currentrandom=1;
	var audio = $("#audio")["0"];
	var disk = $('.disk');
	var cursor = $(".cursor");
	var paused=true;
	window.loopone = false;
	window.shuffle = false;
	$.getJSON("members.json",parseMembers);
	$("#progressbar").width(0);

	//进度条音量条
	$(".progress").mousedown(starDrag = function(ev) {
                ev.stopPropagation();
                var origX = ev.clientX;
                var origW = $(this).prev().width();
                var target = $(this).prev();
                var type = $(this).attr("id");
                $(document).mousemove(doDrag = function(ev){
                    ev.preventDefault();
                    var moveX = ev.clientX - origX;
                    //console.log(moveX/target.parent().width()*100);
                    var value = (origW+moveX)/target.parent().width();
                    value=value>1?1:(value<0?0:value);
                    target.width(value*100+"%");
                    //console.log(value*100);
                    switch(type)
                    {
                    	case "volume":audio.changeVolumeTo(value);break;
                    	case "progress":audio.setCurrentTime(value*audio.duration);break;
                    }
                });
                $(document).mouseup(stopDrag = function(){
                    $(document).unbind("mousemove",doDrag);
                    $(document).unbind("mouseup",stopDrag);
                });
            });
	$(".progress").bind("touchstart",starTDrag = function(ev) {
                ev.stopPropagation();
                var origX = ev.originalEvent.targetTouches["0"].clientX;
                console.log(ev.originalEvent.targetTouches["0"].clientX);
                var origW = $(this).prev().width();
                var target = $(this).prev();
                var type = $(this).attr("id");
                $(document).bind("touchmove",doTDrag = function(ev){
                    ev.preventDefault();
                    var moveX = ev.originalEvent.targetTouches["0"].clientX - origX;
                    console.log(moveX/target.parent().width()*100);
                    var value = (origW+moveX)/target.parent().width();
                    value=value>1?1:(value<0?0:value);
                    target.width(value*100+"%");
                    console.log(value*100);
                    switch(type)
                    {
                    	case "volume":audio.changeVolumeTo(value);break;
                    	case "progress":audio.setCurrentTime(value*audio.duration);break;
                    }
                });
                $(document).bind("touchend",stopTDrag = function(){
                    $(document).unbind("touchmove",doTDrag);
                    $(document).unbind("touchend",stopTDrag);
                });
            });

	//循环按钮
	$('#loop').click(function(){
		if(window.loopone){//window.loopone->window.shuffle
			$(this).addClass('window.shuffle').removeClass('window.loopone');
			audio.loop = false;
			window.loopone=false;
			window.shuffle=true;
		}
		else if(window.shuffle)//window.shuffle->loop
		{
			$(this).addClass('loop').removeClass('window.shuffle');
			audio.loop = false;
			window.loopone = false;
			window.shuffle=false;
		}
		else //loop->window.loopone
		{
			$(this).addClass('window.loopone').removeClass('loop');
			audio.loop = true;
			window.loopone = true;
			window.shuffle=false;
		}

	});
	$("#list").click(listshow = function(e){
		e.stopPropagation();
		if(!listshow.shown){
			$(".listcontainer").show().css("animation","listshow 0.7s linear 0s forwards").css("-webkit-animation","listshow 0.7s linear 0s forwards").css("-o-animation","listshow 0.7s linear 0s forwards").css("-moz-animation","listshow 0.7s linear 0s forwards").delay(700);listshow.shown=true;
		}else
		{
			$(".listcontainer").css("animation","listhide 0.7s linear 0s forwards").css("-webkit-animation","listhide 0.7s linear 0s forwards").css("-o-animation","listhide 0.7s linear 0s forwards").css("-moz-animation","listhide 0.7s linear 0s forwards").delay(700).hide(0);listshow.shown=false;
		}
	});
	$(".diskborder").click(function(e){
		e.stopPropagation();
		$(".cursoroutter").fadeToggle();
		$(".outtervolumebar").fadeToggle();
		$(".diskborder").fadeToggle();
		$("#membersshow").fadeToggle();
		$(".funcs>:first-child").fadeToggle();

	});
	$("#membersshow").click(function(e){
		e.stopPropagation();
		$(".cursoroutter").fadeToggle();
		$(".outtervolumebar").fadeToggle();
		$(".diskborder").fadeToggle();
		$("#membersshow").fadeToggle();
		$(".funcs>:first-child").fadeToggle();
	});
	$(".love").click(function(e)
	{
		$(this)[0].flag==undefined&&($(this)[0].flag=false);
		e.stopPropagation();
		if($(this)[0].flag)
		{
			$(this).addClass("love").removeClass("loved");
			$(this)[0].flag=false;
		}
		else
		{
			$(this).addClass("loved").removeClass("love");
			myFirebaseRef.transaction(function(opentimes) {

				$(".good").fadeToggle().text("已有"+(opentimes++)+"人点赞").delay(500).fadeToggle();
				return opentimes;
			});
			$(this)[0].flag=true;
		}
	})

	//读取媒体信息
	$(audio).bind("loadedmetadata",function(){
                var totalTime = formatTime(this.duration);
                $($("div").find("span")["1"]).text(totalTime);
                $("#progressbar").width(0);

				//播放暂停
				$("#play").click(function(e)
				{
					e.stopPropagation();
					if(paused)
					{
						audio.play();
					}
					else
					{
						audio.pause();
					}
				});

            });
	$(audio).trigger("loadedmetadata");

	//播放时间更新
	$(audio).bind("timeupdate",function(){
                var duration = this.duration;
                var curTime = this.currentTime;
                var percentage = curTime/duration * 100;
                $("#progressbar").css("width",percentage + "%");
                var passedTime = formatTime(curTime);
                $($("div").find("span")["0"]).text(passedTime);
            });

	//音频播放
	$(audio).bind("play",function(){
			$("#play").addClass('pause').removeClass('play');
			disk.css("animation-play-state","running");
			disk.css("-webkit-animation-play-state","running");
			disk.css("-o-animation-play-state","running");
			disk.css("-moz-animation-play-state","running");
			cursor.css("transform","rotate(-20deg)");
			cursor.css("-webkit-transform","rotate(-20deg)");
			cursor.css("-o-transform","rotate(-20deg)");
			cursor.css("-moztransform","rotate(-20deg)");
			cursor.css("animation","cursorclockwise 0.5s linear 0s forwards");
			cursor.css("-webkit-animation","cursorclockwise 0.5s linear 0s forwards");
			cursor.css("-o-animation","cursorclockwise 0.5s linear 0s forwards");
			cursor.css("-moz-animation","cursorclockwise 0.5s linear 0s forwards");
			paused=false;
            });

	//音频暂停
	$(audio).bind("pause",function(){
            $("#play").addClass('play').removeClass('pause');
			disk.css("animation-play-state","paused");
			disk.css("-wevkit-animation-play-state","paused");
			disk.css("-o-animation-play-state","paused");
			disk.css("-mozanimation-play-state","paused");
			cursor.css("transform","rotate(0deg)");
			cursor.css("-webkit-transform","rotate(0deg)");
			cursor.css("-o-transform","rotate(0deg)");
			cursor.css("-moz-transform","rotate(0deg)");
			cursor.css("animation","cursorcounter 0.5s linear 0s forwards");
			cursor.css("-webkit-animation","cursorcounter 0.5s linear 0s forwards");
			cursor.css("-o-animation","cursorcounter 0.5s linear 0s forwards");
			cursor.css("-moz-animation","cursorcounter 0.5s linear 0s forwards");
			paused=true;
            });

	//音频播放结束
	$(audio).bind("ended",function(){
		disk.css("animation-play-state","paused");
			disk.css("-wevkit-animation-play-state","paused");
			disk.css("-o-animation-play-state","paused");
			disk.css("-mozanimation-play-state","paused");
		paused=true;
		$("#play").addClass('play').removeClass('pause');
		if (!window.loopone) {
                $(".next").triggerHandler("click");
            }
        });
	//下一曲
	$(".next").click(function(){
		if(window.shuffle){
			window.currentSrcIndex = Math.ceil(Math.random()*window.memberlist.length)-1;
			window.currentSrcIndex < 0 && (window.currentSrcIndex = 0);
			window.currentSrcIndex = window.currentSrcIndex % window.memberlist.length;
		}
		else
        	++window.currentSrcIndex > window.memberlist.length - 1 && (window.currentSrcIndex = 0);

        audio.setCurrentSrc(window.currentSrcIndex);
		audio.play();
		audio.loop = window.loopone;
    });
    //上一曲
    $(".prev").click(function(){
    	if(window.shuffle){
			window.currentSrcIndex = Math.ceil(Math.random()*window.memberlist.length)-1;
			window.currentSrcIndex < 0 && (window.currentSrcIndex = 0);
			window.currentSrcIndex = window.currentSrcIndex % window.memberlist.length;
		}
		else
        	--window.currentSrcIndex < 0 && (window.currentSrcIndex = 0);
        var currentSrc = window.memberlist[window.currentSrcIndex].soundsrc;
        audio.setCurrentSrc(window.currentSrcIndex);
		audio.play();
		audio.loop = window.loopone;
    });

}
HTMLAudioElement.prototype.changeVolumeTo = function(volume){
    this.volume = volume;
}
HTMLAudioElement.prototype.setCurrentTime = function(currentTime){
	// $($("div").find("span")["0"]).text(formatTime(currentTime));
    this.currentTime = currentTime;
}
HTMLAudioElement.prototype.setCurrentSrc = function(currentSrcIndex){

	var val = Math.ceil(Math.random()*window.bgnum);
	val==0&&(val=1);
	currentrandom==val&&(val=(val+1)%window.bgnum);
	currentrandom=val;
	// $("#containerbody").fadeOut("fast",function(){$(this).css("background-image","url(\"img/bg"+val+".jpg\")");$(this).fadeIn()});
	// $(".mask_bg").fadeOut("fast",function(){$(this).css("background-image","url(\"img/bg"+val+".jpg\")");$(this).fadeIn()});
	$("#containerbody").css("background-image","url(\"img/bg"+val+".jpg\")");
	$(".mask_bg").css("background-image","url(\"img/bg"+val+".jpg\")");
	window.currentSrcIndex = currentSrcIndex;
	var currentSrc = window.memberlist[window.currentSrcIndex].soundsrc;
    $("#currenttitle").text(window.memberlist[window.currentSrcIndex].soundtitle);
	$("#currentartist").text(window.memberlist[window.currentSrcIndex].soundartist);
	$(".disk").css("background","img/"+window.memberlist[window.currentSrcIndex].soundtitle);
	$(".diskmask").css("background","img/"+window.memberlist[window.currentSrcIndex].soundtitle);
	$(".listcontainer li").css("background-color","");
	$("[data-id="+window.currentSrcIndex+"]").css("background-color","rgba(255,0,0,0.3)");
	$("#membersshow #"+window.memberlist[currentSrcIndex].membername+" .containerwrap").load(window.memberlist[currentSrcIndex].memberintro+' .main-border');
	$("#membersshow .active").removeClass("active");
	$("#membersshow #"+window.memberlist[currentSrcIndex].membername).addClass("active");
	$(".download").click(function()
	{
		 window.open(currentSrc,'_blank');
	});
    this.src = currentSrc;
}
function formatTime(time) {
    var minutes = parseInt(time/60);
    var seconds = parseInt(time%60);
    seconds<10 && (seconds = "0" + seconds);
    minutes<10 && (minutes = "0" + minutes);
    return isNaN(time)?"∞":minutes + ":" + seconds;
};

function parseMembers(data)
{
	window.memberlist;
	window.currentSrcIndex=0;
	window.memberlist = new Array();
	$.each(data,function(i,content)
	{
		window.memberlist[i]=content;
		$(".listcontainer ul").append('

'+content["membername"]+'
'+content["soundtitle"]+''+content["soundartist"]+'
'+content["soundtime"]+'

');
		$("#membersshow").append('

');
	});
	$("#membersshow #"+window.memberlist[0].membername+" .containerwrap").load(window.memberlist[0].memberintro+' .main-border');
	audio.setCurrentSrc(0);
	$(".musiclist").click(function()
	{
		audio.setCurrentSrc($(this).attr("data-id"));
		audio.play();
		audio.loop = window.loopone;
	})
}<|endoftext|>


<commit_before>var autocomplete = {
    autocompleteTree: {
        pathKey: {
            empty : ['coverage', 'places', 'journeys', 'coord'],
            all : ['addresses',
            'commercial_modes',
            'companies',
            'departures',
            'disruptions',
            'lines',
            'networks',
            'physical_modes',
            'places',
            'places_nearby',
            'poi_types',
            'pois',
            'route_schedule',
            'routes',
            'stop_areas',
            'stop_points',
            'stop_schedules',
            'vehicles_journeys',
            ],
        },
        features: {
            all: ['addresses',
            'commercial_modes',
            'companies',
            'departures',
            'disruptions',
            'lines',
            'networks',
            'physical_modes',
            'places_nearby',
            'poi_types',
            'pois',
            'route_schedule',
            'routes',
            'stop_areas',
            'stop_points',
            'stop_schedules',
            'vehicles_journeys',
            'places',
            ]
        },
        paramKey: {
            journeys : ['from', 'to', 'datetime', 'datetime_represents', 'traveler_type', 'forbidden_uris[]', 'data_freshness', 'count'],
            places: ['q', 'type[]', 'count'],
            pt_objects: ['q', 'type[]', 'count'],
            all: [''],
        }
    },
    addKeyAutocomplete: function(input, key) {
        var  source;
        if (key === 'pathKey' && ! $('#pathFrame').find('.toDelete').length) {
            source = this.autocompleteTree[key].empty;
        } else if (key === 'paramKey'){
            var feature = $('#featureInput').val();
            source = this.autocompleteTree[key][feature];
            source = source ? source : [];
        }else {
            source = this.autocompleteTree[key].all;
        }

        $(input).autocomplete({
            source: source,
            minLength: 0,
            scroll: true,
            delay: 500,
            select: function (event, ui) {
                $(input).parent().find('button.add').prop('disabled', false);
            }
        }).focus(function() {
                $(this).autocomplete('search', '');
        });
    },
    staticAutocompleteTypes : ['coverage',
        'physical_modes',
        'poi_types'
    ],
    staticAutocomplete : function (input, staticType){
        var api = $('#api input.api').attr('value');
        var token = $('#token input.token').val();
        var cov = getCoverage();
        var request = '';
        if (staticType === 'coverage') {
            request =  api +  '/coverage/';
        } else {
            request =  api +  '/coverage/' + cov + '/' + staticType;
        }
        $.ajax({
            headers: isUndefined(token) ? {} : { Authorization: 'Basic ' + btoa(token) },
            dataType: 'json',
            url: request,
            success: function(data) {
                    var res = [];
                    summary(staticType, data);
                    staticType = (staticType==='coverage') ? 'regions' :  staticType;
                    data[staticType].forEach(function(elt){
                        res.push({ value: elt.id, label: elt.name });
                    });
                    $(input).autocomplete({source: res,
                        minLength: 0,
                        scroll: true,
                        delay: 500
                    }).focus(function() {
                            $(input).autocomplete('search', '');
                    });
                    if ($(input).is(':focus')) {
                        $(input).autocomplete('search', '');
                    }
                }
        });
    },
    dynamicAutocompleteTypes : [
        'addresses',
        'administrative_regions',
        'commercial_modes',
        'coord',
        'lines',
        'networks',
        'places',
        'pois',
        'routes',
        'stop_areas',
        'stop_points',
    ],
    dynamicAutocomplete: function (elt, dynamicType) {
        var formatPtReq = function (v){
            return sprintf('pt_objects/?type[]=%s&q=', v);
        };
        var formatPlacesReq = function (v){
            return sprintf('places/?type[]=%s&q=', v);
        };
        var dynamicTypeRequest = {
            addresses:formatPlacesReq('address'),
            administrative_regions: formatPlacesReq('administrative_region'),
            commercial_modes: formatPtReq('commercial_mode'),
            coord: formatPlacesReq('address'),
            lines: formatPtReq('line'),
            networks: formatPtReq('network'),
            places: 'places/?&q=',
            pois: formatPlacesReq('poi'),
            routes: formatPtReq('route'),
            stop_areas: formatPtReq('stop_area'),
            stop_points: formatPlacesReq('stop_point'),
        };
        var httpReq = dynamicTypeRequest[dynamicType];
        if (! httpReq) {
            return;
        }
        $(elt).autocomplete({
            delay: 200,
            source: function (request, response) {
                var token = $('#token input.token').val();
                var url = $('#api input.api').val();
                var cov = getCoverage();
                // cov can be null in case where coverage is not specifeid
                cov = cov ? ('coverage/' + cov) : '';
                $.ajax({
                    url: sprintf('%s/%s/%s%s', url, cov, httpReq, encodeURIComponent(request.term)),
                    headers: isUndefined(token) ? {} : { Authorization: 'Basic ' + btoa(token) },
                    success: function (data) {
                        var res = [];
                        var search = null;
                        if ('places' in data) {
                            search = data.places;
                        }else if ('pt_objects' in data) {
                            search = data.pt_objects;
                        }
                        if (search) {
                            search.forEach(function(s) {
                                res.push({ value: s.id, label: s.name });
                            });
                        }
                        response(res);
                    },
                    error: function() {
                        response([]);
                    }
                });
            }
        });
    }
}
<commit_msg>remove useless line<commit_after>var autocomplete = {
    autocompleteTree: {
        pathKey: {
            empty : ['coverage', 'places', 'journeys', 'coord'],
            all : ['addresses',
            'commercial_modes',
            'companies',
            'departures',
            'disruptions',
            'lines',
            'networks',
            'physical_modes',
            'places',
            'places_nearby',
            'poi_types',
            'pois',
            'route_schedule',
            'routes',
            'stop_areas',
            'stop_points',
            'stop_schedules',
            'vehicles_journeys',
            ],
        },
        features: {
            all: ['addresses',
            'commercial_modes',
            'companies',
            'departures',
            'disruptions',
            'lines',
            'networks',
            'physical_modes',
            'places_nearby',
            'poi_types',
            'pois',
            'route_schedule',
            'routes',
            'stop_areas',
            'stop_points',
            'stop_schedules',
            'vehicles_journeys',
            'places',
            ]
        },
        paramKey: {
            journeys : ['from', 'to', 'datetime', 'datetime_represents', 'traveler_type', 'forbidden_uris[]', 'data_freshness', 'count'],
            places: ['q', 'type[]', 'count'],
            pt_objects: ['q', 'type[]', 'count'],
        }
    },
    addKeyAutocomplete: function(input, key) {
        var  source;
        if (key === 'pathKey' && ! $('#pathFrame').find('.toDelete').length) {
            source = this.autocompleteTree[key].empty;
        } else if (key === 'paramKey'){
            var feature = $('#featureInput').val();
            source = this.autocompleteTree[key][feature];
            source = source ? source : [];
        }else {
            source = this.autocompleteTree[key].all;
        }

        $(input).autocomplete({
            source: source,
            minLength: 0,
            scroll: true,
            delay: 500,
            select: function (event, ui) {
                $(input).parent().find('button.add').prop('disabled', false);
            }
        }).focus(function() {
                $(this).autocomplete('search', '');
        });
    },
    staticAutocompleteTypes : ['coverage',
        'physical_modes',
        'poi_types'
    ],
    staticAutocomplete : function (input, staticType){
        var api = $('#api input.api').attr('value');
        var token = $('#token input.token').val();
        var cov = getCoverage();
        var request = '';
        if (staticType === 'coverage') {
            request =  api +  '/coverage/';
        } else {
            request =  api +  '/coverage/' + cov + '/' + staticType;
        }
        $.ajax({
            headers: isUndefined(token) ? {} : { Authorization: 'Basic ' + btoa(token) },
            dataType: 'json',
            url: request,
            success: function(data) {
                    var res = [];
                    summary(staticType, data);
                    staticType = (staticType==='coverage') ? 'regions' :  staticType;
                    data[staticType].forEach(function(elt){
                        res.push({ value: elt.id, label: elt.name });
                    });
                    $(input).autocomplete({source: res,
                        minLength: 0,
                        scroll: true,
                        delay: 500
                    }).focus(function() {
                            $(input).autocomplete('search', '');
                    });
                    if ($(input).is(':focus')) {
                        $(input).autocomplete('search', '');
                    }
                }
        });
    },
    dynamicAutocompleteTypes : [
        'addresses',
        'administrative_regions',
        'commercial_modes',
        'coord',
        'lines',
        'networks',
        'places',
        'pois',
        'routes',
        'stop_areas',
        'stop_points',
    ],
    dynamicAutocomplete: function (elt, dynamicType) {
        var formatPtReq = function (v){
            return sprintf('pt_objects/?type[]=%s&q=', v);
        };
        var formatPlacesReq = function (v){
            return sprintf('places/?type[]=%s&q=', v);
        };
        var dynamicTypeRequest = {
            addresses:formatPlacesReq('address'),
            administrative_regions: formatPlacesReq('administrative_region'),
            commercial_modes: formatPtReq('commercial_mode'),
            coord: formatPlacesReq('address'),
            lines: formatPtReq('line'),
            networks: formatPtReq('network'),
            places: 'places/?&q=',
            pois: formatPlacesReq('poi'),
            routes: formatPtReq('route'),
            stop_areas: formatPtReq('stop_area'),
            stop_points: formatPlacesReq('stop_point'),
        };
        var httpReq = dynamicTypeRequest[dynamicType];
        if (! httpReq) {
            return;
        }
        $(elt).autocomplete({
            delay: 200,
            source: function (request, response) {
                var token = $('#token input.token').val();
                var url = $('#api input.api').val();
                var cov = getCoverage();
                // cov can be null in case where coverage is not specifeid
                cov = cov ? ('coverage/' + cov) : '';
                $.ajax({
                    url: sprintf('%s/%s/%s%s', url, cov, httpReq, encodeURIComponent(request.term)),
                    headers: isUndefined(token) ? {} : { Authorization: 'Basic ' + btoa(token) },
                    success: function (data) {
                        var res = [];
                        var search = null;
                        if ('places' in data) {
                            search = data.places;
                        }else if ('pt_objects' in data) {
                            search = data.pt_objects;
                        }
                        if (search) {
                            search.forEach(function(s) {
                                res.push({ value: s.id, label: s.name });
                            });
                        }
                        response(res);
                    },
                    error: function() {
                        response([]);
                    }
                });
            }
        });
    }
}
<|endoftext|>


<commit_before>function Wallet()
{
  this.keys = [];
  this.balances = [0,0,0,0,0,0,0,0,0,0];

  // Methods
  this.textToBytes = function(text) {
    return Crypto.SHA256(text, { asBytes: true });
  };

  this.getKeys = function() {
    return this.keys;
  };

  this.getBalances = function() {
    return this.balances;
  }

  this.createBalanceFunction = function(i) {
      return function(text) {
        wallet.getBalances()[i] = parseInt(text);

        // TODO, disconnect GUI code from backend.
        $('#balance' + i).text(
          Bitcoin.Util.formatValue(wallet.getBalances()[i]));
      };
  }

  this.updateAllBalances = function() {

    url = 'http://blockchain.info/q/addressbalance/';
    var funcs = [];

    for(i = 0; i < wallet.getKeys().length; i++)
    {
      funcs[i] = this.createBalanceFunction(i);
      tx_fetch(url + wallet.getKeys()[i].getBitcoinAddress().toString(), funcs[i]);
    }
  }
}

// Global, hmmm.
var wallet = new Wallet();
var txType = 'txBCI';

$(document).ready(function() {

  $('#site').hide();
  $('#tx').hide();
  $('#logout-menu').hide();

  $('#open-sesame').click(function(){

    var seed = $('#password').val();
    seed = mn_decode(seed);
    Electrum.init(seed, function(r) {
        if(r % 20 == 0)
          $('#seed-progress').css('width', (r + 19) + '%');
      },
      function(privKey) {
        Electrum.gen(10, function(r) {
          wallet.getKeys().push(new Bitcoin.ECKey(r[1]));
          if(wallet.getKeys().length == 10)
            login_success();
        });
      }
    );

    return true;
  })

  $('#txDropGetUnspent').click(txDropGetUnspent);
  $('#txDropAddr').change(txOnChangeSource);
  $('#txValue').change(txOnChangeDest);
  $('#txDest').change(txOnChangeDest);

  $('#password').keyup(checkValidPassword);

  $('#txAddDest').click(txOnAddDest);
  $('#txRemoveDest').click(txOnRemoveDest);
  $('#txSend').click(txVerify);
  $('#sendPayment').click(txSend);
  $('#generate-password').click(generatePassword);
  $('#regenerate-password').click(regeneratePassword);
  $('#regenerate-password').tooltip();

  $('#your-addresses-nav, #home').click(function(){
    hideAll();
    $('#your-addresses').show();
    $('#your-addresses-nav').parent().addClass('active');
    return false;
  });

  $('#make-payment-nav').click(function(){
    hideAll();
    $('#tx').show();
    $('#make-payment-nav').parent().addClass('active');
    return false;
  });

  $('#logout').click(function(){
    $('#password').val('');
    $('#site').hide();
    $('#create-keys').collapse('hide');
    $('#create-wallet').collapse('hide');
    $('#logout-menu').hide();
    wallet = new Wallet();
    checkValidPassword();
    $('#logon').show();
    return false;
  });

  function hideAll()
  {
    $('ul.nav-list li').removeClass('active');
    $('#your-addresses').hide();
    $('#tx').hide();
  }

  function login_success()
  {
    $('#logon').hide();
    $('#site').show();
    $('#logout-menu').show();

    wallet.updateAllBalances();
    $("#txDropAddr").find("option").remove();

    for(i = 0; i < wallet.getKeys().length; i++)
    {
      var addr = wallet.getKeys()[i].getBitcoinAddress().toString();
      $('#address' + i).text(addr);
      $("#txDropAddr").append('<option value=' + i + '>' + addr + '</option>');
      $('#balance' + i).text(Bitcoin.Util.formatValue(wallet.getBalances()[i]));
    }

    txOnChangeSource();

    return false;
  }

  function checkValidPassword(){
    var password = $('#password').val()
    var valid = true;

    if(password.split(' ').length != 12)
      valid = false;

    if(valid)
    {
      $('#open-sesame').addClass('btn-primary');
      $('#open-sesame').removeAttr('disabled');
    }
    else
    {
      $('#open-sesame').removeClass('btn-primary');
      $('#open-sesame').attr('disabled', 'disabled');
    }
  }

  // -- Wallet Creation --
  function regeneratePassword() {
    $('#generated').val('');
    return generatePassword();
  }

  function generatePassword() {

    $('#generated').focus();

    if($('#generated').val() != '')
      return true;

    var pk = new Array(32);
    rng_get_bytes(pk);
    var seed = Crypto.util.bytesToHex(pk.slice(0,16));
    //nb! electrum doesn't handle trailing zeros very well
    // and we want to stay compatible.
    if (seed.charAt(0) == '0') seed = seed.substr(1);
    var codes = mn_encode(seed);
    $('#generated').val(codes);

    return true;
  }

  // -- transactions --

  function txOnChangeSource() {
    var i = $('#txDropAddr option:selected').prop('index');
    $('#txSec').val(wallet.getKeys()[i].getExportedPrivateKey());
    txDropGetUnspent();
  }

  function txSetUnspent(text) {
      if(text == '')
        return;
      var r = JSON.parse(text);
      txUnspent = JSON.stringify(r, null, 4);
      $('#txUnspent').val(txUnspent);
      var address = $('#txAddr').val();
      TX.parseInputs(txUnspent, address);
      var value = TX.getBalance();
      var fval = Bitcoin.Util.formatValue(value);
      //var fee = parseFloat($('#txFee').val());
      $('#txBalance').val(fval);
      //$('#txValue').val(fval - fee);
      //txRebuild();
  }

  function txUpdateUnspent() {
      txSetUnspent($('#txUnspent').val());
  }

  function txParseUnspent(text) {
      if (text == '')
          return;
      txSetUnspent(text);
  }

  function txDropGetUnspent() {
      var addr = wallet.getKeys()[$('#txDropAddr').val()].getBitcoinAddress().toString();

      var url = (txType == 'txBCI') ? 'http://blockchain.info/unspent?address=' + addr :
          'http://blockexplorer.com/q/mytransactions/' + addr;

      //url = prompt('Download transaction history:', url);
      if (url != null && url != "") {
          $('#txUnspent').val('');
          tx_fetch(url, txParseUnspent);
      }
  }

  function txOnChangeDest() {

    var res = txGetOutputs();
    var valid = true;

    for( i in res)
    {
      if(res[i].dest == '' || res[i].fval == 0)
      {
        valid = false;
        break;
      }
    }

    if(valid)
      $('#txSend').removeAttr('disabled');
    else
      $('#txSend').attr('disabled','disabled');
  }

  function txOnAddDest() {
      var list = $(document).find('.txCC');
      var clone = list.last().clone();
      clone.find('.help-inline').empty();
      clone.find('.control-label').text('Cc');
      var dest = clone.find('#txDest');
      var value = clone.find('#txValue');
      clone.insertAfter(list.last());
      $(dest).change(txOnChangeDest);
      $(value).change(txOnChangeDest);
      dest.val('');
      value.val('');
      $('#txRemoveDest').attr('disabled', false);
      return false;
  }

  function txOnRemoveDest() {
      var list = $(document).find('.txCC');
      if (list.size() == 2)
          $('#txRemoveDest').attr('disabled', true);
      list.last().remove();
      return false;
  }

  function txSent(text) {
      alert(text ? text : 'No response!');
  }

  function txVerify() {
    txRebuild();

    $('#verifySource').text(TX.getAddress());
    $('#verifyAmountTitle').text(TX.getSendBalance());
    $('#verifyTotal').text(TX.getSendBalance());

    $('#verifyTable').find("tr:gt(0)").remove();
    for(i = 0; i < TX.getOutputs().length; i++)
    {
      if(TX.getOutputs()[i].address != TX.getAddress())
      {
        $('#verifyTable').append('
'
          + TX.getOutputs()[i].address
          + '	'
          + TX.getOutputs()[i].value
          + ' BTC
');
      }
    }
    $('#verifyChange').remove();
    $('#verifyBody').append('
'
        + TX.getChange()
        + ' BTC will be returned to the sending address as change
');

    $('#verifyModal').modal();
  }

  function txSend() {
      var txAddr = $('#txDropAddr option:selected').text();
      var address = TX.getAddress();

      var r = '';
      if (txAddr != address)
          r += 'Warning! Source address does not match private key.\n\n';

      var tx = $('#txHex').val();

      url = 'http://blockchain.info/pushtx';
      postdata = 'tx=' + tx;
      url = prompt(r + 'Send transaction:', url);
      if (url != null && url != "") {
          tx_fetch(url, txSent, txSent, postdata);
      }
      return false;
  }

  function txRebuild() {
      var sec = $('#txSec').val();
      var addr = $('#txDropAddr option:selected').text();
      var unspent = $('#txUnspent').val();
      var balance = parseFloat($('#txBalance').val());

      var fee = parseFloat('0'+$('#txFee').val());

      try {
          var res = parseBase58Check(sec);
          var version = res[0];
          var payload = res[1];
      } catch (err) {
          $('#txJSON').val('');
          $('#txHex').val('');
          return;
      }

      var compressed = false;
      if (payload.length > 32) {
          payload.pop();
          compressed = true;
      }

      var eckey = new Bitcoin.ECKey(payload);

      eckey.setCompressed(compressed);

      TX.init(eckey);

      var fval = 0;
      var o = txGetOutputs();
      for (i in o) {
          TX.addOutput(o[i].dest, o[i].fval);
          fval += o[i].fval;
      }

      // send change back or it will be sent as fee
      if (balance > fval + fee) {
          var change = balance - fval - fee;
          TX.addOutput(addr, change);
      }

      try {
          var sendTx = TX.construct();
          var txJSON = TX.toBBE(sendTx);
          var buf = sendTx.serialize();
          var txHex = Crypto.util.bytesToHex(buf);
          $('#txJSON').val(txJSON);
          $('#txHex').val(txHex);
      } catch(err) {
          $('#txJSON').val('Error ' + err);
          $('#txHex').val('Error ' + err);
      }
  }

  function txGetOutputs() {
      var res = [];
      $.each($(document).find('.txCC'), function() {
          var dest = $(this).find('#txDest').val();
          var fval = parseFloat('0' + $(this).find('#txValue').val());
          res.push( {"dest":dest, "fval":fval } );
      });
      return res;
  }

  function parseBase58Check(address) {
      var bytes = Bitcoin.Base58.decode(address);
      var end = bytes.length - 4;
      var hash = bytes.slice(0, end);
      var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});
      if (checksum[0] != bytes[end] ||
          checksum[1] != bytes[end+1] ||
          checksum[2] != bytes[end+2] ||
          checksum[3] != bytes[end+3])
              throw new Error("Wrong checksum");
      var version = hash.shift();
      return [version, hash];
  }
});
<commit_msg>Validate address.<commit_after>function Wallet()
{
  this.keys = [];
  this.balances = [0,0,0,0,0,0,0,0,0,0];

  // Methods
  this.textToBytes = function(text) {
    return Crypto.SHA256(text, { asBytes: true });
  };

  this.getKeys = function() {
    return this.keys;
  };

  this.getBalances = function() {
    return this.balances;
  }

  this.createBalanceFunction = function(i) {
      return function(text) {
        wallet.getBalances()[i] = parseInt(text);

        // TODO, disconnect GUI code from backend.
        $('#balance' + i).text(
          Bitcoin.Util.formatValue(wallet.getBalances()[i]));
      };
  }

  this.updateAllBalances = function() {

    url = 'http://blockchain.info/q/addressbalance/';
    var funcs = [];

    for(i = 0; i < wallet.getKeys().length; i++)
    {
      funcs[i] = this.createBalanceFunction(i);
      tx_fetch(url + wallet.getKeys()[i].getBitcoinAddress().toString(), funcs[i]);
    }
  }
}

// Global, hmmm.
var wallet = new Wallet();
var txType = 'txBCI';

$(document).ready(function() {

  $('#site').hide();
  $('#tx').hide();
  $('#logout-menu').hide();

  $('#open-sesame').click(function(){

    var seed = $('#password').val();
    seed = mn_decode(seed);
    Electrum.init(seed, function(r) {
        if(r % 20 == 0)
          $('#seed-progress').css('width', (r + 19) + '%');
      },
      function(privKey) {
        Electrum.gen(10, function(r) {
          wallet.getKeys().push(new Bitcoin.ECKey(r[1]));
          if(wallet.getKeys().length == 10)
            login_success();
        });
      }
    );

    return true;
  })

  $('#txDropGetUnspent').click(txDropGetUnspent);
  $('#txDropAddr').change(txOnChangeSource);
  $('#txValue').change(txOnChangeDest);
  $('#txDest').change(txOnChangeDest);

  $('#password').keyup(checkValidPassword);

  $('#txAddDest').click(txOnAddDest);
  $('#txRemoveDest').click(txOnRemoveDest);
  $('#txSend').click(txVerify);
  $('#sendPayment').click(txSend);
  $('#generate-password').click(generatePassword);
  $('#regenerate-password').click(regeneratePassword);
  $('#regenerate-password').tooltip();

  $('#your-addresses-nav, #home').click(function(){
    hideAll();
    $('#your-addresses').show();
    $('#your-addresses-nav').parent().addClass('active');
    return false;
  });

  $('#make-payment-nav').click(function(){
    hideAll();
    $('#tx').show();
    $('#make-payment-nav').parent().addClass('active');
    return false;
  });

  $('#logout').click(function(){
    $('#password').val('');
    $('#site').hide();
    $('#create-keys').collapse('hide');
    $('#create-wallet').collapse('hide');
    $('#logout-menu').hide();
    wallet = new Wallet();
    checkValidPassword();
    $('#logon').show();
    return false;
  });

  function hideAll()
  {
    $('ul.nav-list li').removeClass('active');
    $('#your-addresses').hide();
    $('#tx').hide();
  }

  function login_success()
  {
    $('#logon').hide();
    $('#site').show();
    $('#logout-menu').show();

    wallet.updateAllBalances();
    $("#txDropAddr").find("option").remove();

    for(i = 0; i < wallet.getKeys().length; i++)
    {
      var addr = wallet.getKeys()[i].getBitcoinAddress().toString();
      $('#address' + i).text(addr);
      $("#txDropAddr").append('<option value=' + i + '>' + addr + '</option>');
      $('#balance' + i).text(Bitcoin.Util.formatValue(wallet.getBalances()[i]));
    }

    txOnChangeSource();

    return false;
  }

  function checkValidPassword(){
    var password = $('#password').val()
    var valid = true;

    if(password.split(' ').length != 12)
      valid = false;

    if(valid)
    {
      $('#open-sesame').addClass('btn-primary');
      $('#open-sesame').removeAttr('disabled');
    }
    else
    {
      $('#open-sesame').removeClass('btn-primary');
      $('#open-sesame').attr('disabled', 'disabled');
    }
  }

  // -- Wallet Creation --
  function regeneratePassword() {
    $('#generated').val('');
    return generatePassword();
  }

  function generatePassword() {

    $('#generated').focus();

    if($('#generated').val() != '')
      return true;

    var pk = new Array(32);
    rng_get_bytes(pk);
    var seed = Crypto.util.bytesToHex(pk.slice(0,16));
    //nb! electrum doesn't handle trailing zeros very well
    // and we want to stay compatible.
    if (seed.charAt(0) == '0') seed = seed.substr(1);
    var codes = mn_encode(seed);
    $('#generated').val(codes);

    return true;
  }

  // -- transactions --

  function txOnChangeSource() {
    var i = $('#txDropAddr option:selected').prop('index');
    $('#txSec').val(wallet.getKeys()[i].getExportedPrivateKey());
    txDropGetUnspent();
  }

  function txSetUnspent(text) {
      if(text == '')
        return;
      var r = JSON.parse(text);
      txUnspent = JSON.stringify(r, null, 4);
      $('#txUnspent').val(txUnspent);
      var address = $('#txAddr').val();
      TX.parseInputs(txUnspent, address);
      var value = TX.getBalance();
      var fval = Bitcoin.Util.formatValue(value);
      //var fee = parseFloat($('#txFee').val());
      $('#txBalance').val(fval);
      //$('#txValue').val(fval - fee);
      //txRebuild();
  }

  function txUpdateUnspent() {
      txSetUnspent($('#txUnspent').val());
  }

  function txParseUnspent(text) {
      if (text == '')
          return;
      txSetUnspent(text);
  }

  function txDropGetUnspent() {
      var addr = wallet.getKeys()[$('#txDropAddr').val()].getBitcoinAddress().toString();

      var url = (txType == 'txBCI') ? 'http://blockchain.info/unspent?address=' + addr :
          'http://blockexplorer.com/q/mytransactions/' + addr;

      //url = prompt('Download transaction history:', url);
      if (url != null && url != "") {
          $('#txUnspent').val('');
          tx_fetch(url, txParseUnspent);
      }
  }

  function txOnChangeDest() {

    var res = txGetOutputs();
    var valid = true;

    for( i in res)
    {
      if(res[i].dest == '' || res[i].fval == 0)
      {
        valid = false;
        break;
      }
      else
      {
        try {
          parseBase58Check(res[i].dest);
        }
        catch (e) {
          valid = false;
          break;
        }
      }
    }

    if(valid)
      $('#txSend').removeAttr('disabled');
    else
      $('#txSend').attr('disabled','disabled');
  }

  function txOnAddDest() {
      var list = $(document).find('.txCC');
      var clone = list.last().clone();
      clone.find('.help-inline').empty();
      clone.find('.control-label').text('Cc');
      var dest = clone.find('#txDest');
      var value = clone.find('#txValue');
      clone.insertAfter(list.last());
      $(dest).change(txOnChangeDest);
      $(value).change(txOnChangeDest);
      dest.val('');
      value.val('');
      $('#txRemoveDest').attr('disabled', false);
      return false;
  }

  function txOnRemoveDest() {
      var list = $(document).find('.txCC');
      if (list.size() == 2)
          $('#txRemoveDest').attr('disabled', true);
      list.last().remove();
      return false;
  }

  function txSent(text) {
      alert(text ? text : 'No response!');

      wallet.updateAllBalances();
  }

  function txVerify() {
    txRebuild();

    $('#verifySource').text(TX.getAddress());
    $('#verifyAmountTitle').text(TX.getSendBalance());
    $('#verifyTotal').text(TX.getSendBalance());

    $('#verifyTable').find("tr:gt(0)").remove();
    for(i = 0; i < TX.getOutputs().length; i++)
    {
      if(TX.getOutputs()[i].address != TX.getAddress())
      {
        $('#verifyTable').append('
'
          + TX.getOutputs()[i].address
          + '	'
          + TX.getOutputs()[i].value
          + ' BTC
');
      }
    }
    $('#verifyChange').remove();
    $('#tx-toggle').prepend('
'
        + TX.getChange()
        + ' BTC will be returned to the sending address as change
');

    $('#verifyModal').modal();
  }

  function txSend() {
      var txAddr = $('#txDropAddr option:selected').text();
      var address = TX.getAddress();

      var r = '';
      if (txAddr != address)
          r += 'Warning! Source address does not match private key.\n\n';

      var tx = $('#txHex').val();

      url = 'http://blockchain.info/pushtx';
      postdata = 'tx=' + tx;
      if (url != null && url != "") {
          tx_fetch(url, txSent, txSent, postdata);
      }
      return true;
  }

  function txRebuild() {
      var sec = $('#txSec').val();
      var addr = $('#txDropAddr option:selected').text();
      var unspent = $('#txUnspent').val();
      var balance = parseFloat($('#txBalance').val());

      var fee = parseFloat('0'+$('#txFee').val());

      try {
          var res = parseBase58Check(sec);
          var version = res[0];
          var payload = res[1];
      } catch (err) {
          $('#txJSON').val('');
          $('#txHex').val('');
          return;
      }

      var compressed = false;
      if (payload.length > 32) {
          payload.pop();
          compressed = true;
      }

      var eckey = new Bitcoin.ECKey(payload);

      eckey.setCompressed(compressed);

      TX.init(eckey);

      var fval = 0;
      var o = txGetOutputs();
      for (i in o) {
          TX.addOutput(o[i].dest, o[i].fval);
          fval += o[i].fval;
      }

      // send change back or it will be sent as fee
      if (balance > fval + fee) {
          var change = balance - fval - fee;
          TX.addOutput(addr, change);
      }

      try {
          var sendTx = TX.construct();
          var txJSON = TX.toBBE(sendTx);
          var buf = sendTx.serialize();
          var txHex = Crypto.util.bytesToHex(buf);
          $('#txJSON').val(txJSON);
          $('#txHex').val(txHex);
      } catch(err) {
          $('#txJSON').val('Error ' + err);
          $('#txHex').val('Error ' + err);
      }
  }

  function txGetOutputs() {
      var res = [];
      $.each($(document).find('.txCC'), function() {
          var dest = $(this).find('#txDest').val();
          var fval = parseFloat('0' + $(this).find('#txValue').val());
          res.push( {"dest":dest, "fval":fval } );
      });
      return res;
  }

  function parseBase58Check(address) {
      var bytes = Bitcoin.Base58.decode(address);
      var end = bytes.length - 4;
      var hash = bytes.slice(0, end);
      var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});
      if (checksum[0] != bytes[end] ||
          checksum[1] != bytes[end+1] ||
          checksum[2] != bytes[end+2] ||
          checksum[3] != bytes[end+3])
              throw new Error("Wrong checksum");
      var version = hash.shift();
      return [version, hash];
  }
});
<|endoftext|>


<commit_before>function smoothed_count(iterations, final_modulus){
    return iterations - (Math.log(Math.log(Math.sqrt(final_modulus))) / Math.log(2))
}

function iteration_count(escape_radius_squared, max_iterations, initial_real, initial_imaginary){
    mod_z = (initial_real * initial_real) + (initial_imaginary * initial_imaginary);

    real = initial_real;
    imaginary = initial_imaginary;

    iterations = 0;

    while (mod_z < escape_radius_squared && iterations != max_iterations){

        new_real = (real * real) - (imaginary * imaginary) + initial_real;
        imaginary = (2 * real * imaginary) + initial_imaginary;
        real = new_real;
        mod_z = (real * real) + (imaginary * imaginary);
        iterations++;
    }

    return smoothed_count(iterations, mod_z)
}
<commit_msg>Minor: reformat js<commit_after>function smoothed_count(
    iterations,
    final_modulus){

    return iterations - (Math.log(Math.log(Math.sqrt(final_modulus))) / Math.log(2))
}

function iteration_count(
    escape_radius_squared,
    max_iterations,
    initial_real,
    initial_imaginary){

    mod_z = (initial_real * initial_real) + (initial_imaginary * initial_imaginary);

    real = initial_real;
    imaginary = initial_imaginary;

    iterations = 0;

    while (mod_z < escape_radius_squared && iterations != max_iterations){

        new_real = (real * real) - (imaginary * imaginary) + initial_real;
        imaginary = (2 * real * imaginary) + initial_imaginary;
        real = new_real;
        mod_z = (real * real) + (imaginary * imaginary);
        iterations++;
    }

    return smoothed_count(iterations, mod_z)
}
<|endoftext|>