<commit_before>
//This is where you can change the number of aliens in the different levels by using 1 and 2 intergers which correlate to the different alien images.

  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,2,2,2,2,2,0,0,0],
          [0,0,0,1,1,1,1,1,0,0,0],
          [0,0,0,1,1,1,1,1,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],

     2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,2,0,0],
          [0,0,2,2,2,2,2,2,2,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],

     3:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,1,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],

     4:  [[0,0,0,0,0,0,0,0,0,0,0],
          [2,2,2,2,2,2,2,2,2,2,2],
          [2,2,2,2,2,2,2,2,2,2,2],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,1,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,0,1,1,1,1,1,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]] };

		  //This is the co-ordinates of the images the game uses from the sprite page.

  var spriteData = {
    'alien1': { sx: 0,  sy: 0,  w: 26, h: 32, cls: Alien, frames: 2},
    'alien2': { sx: 0,  sy: 32, w: 26, h: 32, cls: Alien, frames: 2},
    'player': { sx: 0,  sy: 64, w: 26, h: 33, cls: Player, frames: 2 },
    'missile': { sx: 0,  sy: 97, w: 6,  h: 19, cls: Missile, frames: 2 },
  }

var music = new Audio('media/Imperial_march.mp3')
var deathsong = new Audio('media/Die_song.mp3')

 		//This is the start page for the game itself.

  function startGame() {
    var screen = new GameScreen("Space Wars","(Press space to start)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     music.play();

                                 });
    Game.loadBoard(screen);
    Game.loop();
  }

  //This is the screen that tells you you have been killed and to press space to start again from level 1.

  function endGame() {
    var screen = new GameScreen("Game Over","(Press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     music.play();

                                     deathsong.pause();
                                     deathsong.currentTime = 0.0;

                                 });
    Game.loadBoard(screen);
  }
		//This is the screen that tells you you have won and to press space to start the game from level 1.

  function winGame() {
    var screen = new GameScreen("You Win!","(Press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }

  			//This is where the sounds are located to play when you fire a missile or hit something.

  $(function() {
    GameAudio.load({ 'fire' : 'media/blaster.wav', 'die' : 'media/grenade.mp3' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<commit_msg>Level 4 spawning<commit_after>
//This is where you can change the number of aliens in the different levels by using 1 and 2 intergers which correlate to the different alien images.

  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,2,2,2,2,2,0,0,0],
          [0,0,0,1,1,1,1,1,0,0,0],
          [0,0,0,1,1,1,1,1,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],

     2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,2,0,0],
          [0,0,2,2,2,2,2,2,2,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],

     3:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,1,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],

     4:  [[2,2,2,2,2,2,2,2,2,2,2],
          [2,2,2,2,2,2,2,2,2,2,2],
          [2,2,2,2,2,2,2,2,2,2,2],
          [2,2,2,2,2,2,2,2,2,2,2],
          [2,2,1,1,1,1,1,1,1,2,2],
          [2,2,2,1,1,1,1,1,2,2,2],
          [0,0,0,0,1,1,1,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]] };

		  //This is the co-ordinates of the images the game uses from the sprite page.

  var spriteData = {
    'alien1': { sx: 0,  sy: 0,  w: 26, h: 32, cls: Alien, frames: 2},
    'alien2': { sx: 0,  sy: 32, w: 26, h: 32, cls: Alien, frames: 2},
    'player': { sx: 0,  sy: 64, w: 26, h: 33, cls: Player, frames: 2 },
    'missile': { sx: 0,  sy: 97, w: 6,  h: 19, cls: Missile, frames: 2 },
  }

var music = new Audio('media/Imperial_march.mp3')
var deathsong = new Audio('media/Die_song.mp3')

 		//This is the start page for the game itself.

  function startGame() {
    var screen = new GameScreen("Space Wars","(Press space to start)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     music.play();

                                 });
    Game.loadBoard(screen);
    Game.loop();
  }

  //This is the screen that tells you you have been killed and to press space to start again from level 1.

  function endGame() {
    var screen = new GameScreen("Game Over","(Press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     music.play();

                                     deathsong.pause();
                                     deathsong.currentTime = 0.0;

                                 });
    Game.loadBoard(screen);
  }
		//This is the screen that tells you you have won and to press space to start the game from level 1.

  function winGame() {
    var screen = new GameScreen("You Win!","(Press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     music.currentTime = 0.0;

                                 });
    Game.loadBoard(screen);
  }

  			//This is where the sounds are located to play when you fire a missile or hit something.

  $(function() {
    GameAudio.load({ 'fire' : 'media/blaster.wav', 'die' : 'media/grenade.mp3' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<|endoftext|>


<commit_before>;
(function() {

    var api = "https://jsonplaceholder.typicode.com";
    var userId = 1; // default to JSONPlaceholder API

    var postJquery = function() {
      $("#btn-submit-1").click(function() {
        var title = $("#title-1").val();
        var body = $("#body-1").val();
        $.ajax({
          type: 'POST',
          url: api + '/posts',
          dataType: "json",
          data: {
            title: title,
            body: body,
            userId: userId
          },
          success: function(data) {
            console.log("Content added!", data); //the new item is returned with an ID
            $("#res-1").html("
" + JSON.stringify(data) + "
");
            $("#form-1")[0].reset();
          },
          error: function(data) {
            console.log("Content not added!", data); //the new item is returned with an ID
            $("#res-1").html("
Error " + JSON.stringify(data) + "
");
          }
        });
      });
    }();

    var postJS = function() {
      document.getElementById("btn-submit-2").addEventListener("click", function() {
        var title = document.getElementById("title-2").value;
        var body = document.getElementById("body-2").value;
        var http = new XMLHttpRequest();
        var params = "title=" + title + "&body=" + body + "&userId=" + userId;
        var url = api + "/posts";

        http.open("POST", url, true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 201) {
              console.log("Content added!", http.responseText);
              document.getElementById("res-2").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-2").reset();
            } else {
              console.log("User not added!", http.responseText);
              document.getElementById("res-2").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(params);
      });
    }();

    var putJS = function() {
      document.getElementById("btn-submit-3").addEventListener("click", function() {
        var id = document.getElementById("id-3").value;
        var title = document.getElementById("title-3").value;
        var body = document.getElementById("body-3").value;
        var http = new XMLHttpRequest();
        var params = "title=" + title + "&body=" + body + "&userId=" + userId + "&id=" + id;
        var url = api + "/posts/" + id;

        http.open("PUT", url, true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Content updated!", http.responseText);
              document.getElementById("res-3").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-3").reset();
            } else {
              console.log("Content not updated!", http.responseText);
              document.getElementById("res-3").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(params);
      });
    }();

    var patchJS = function() {
      document.getElementById("btn-submit-4").addEventListener("click", function() {
        var id = document.getElementById("id-4").value;
        var title = document.getElementById("title-4").value;
        var http = new XMLHttpRequest();
        var params = "title=" + title;
        var url = api + "/posts/" + id;

        http.open("PATCH", url, true);

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Content updated!", http.responseText);
              document.getElementById("res-4").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-4").reset();
            } else {
              console.log("Content not updated!", http.responseText);
              document.getElementById("res-4").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(params);
      });
    }();

    var getOneItemJS = function() {
      document.getElementById("btn-submit-5").addEventListener("click", function() {
        var id = document.getElementById("id-5").value;
        var http = new XMLHttpRequest();
        var url = api + "/posts/" + id;

        http.open("GET", url, true);

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Content loaded!", http.responseText);
              document.getElementById("res-5").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-5").reset();
            } else {
              console.log("Content not updated!", http.responseText);
              document.getElementById("res-5").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(null);
      });
    }();

    var getAllItensFilterJS = function() {
      document.getElementById("btn-submit-6").addEventListener("click", function() {
        var http = new XMLHttpRequest();
        var url = api + "/users";

        http.open("GET", url, true);

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Users loaded!", http.responseText);
              var obj = JSON.parse(http.responseText);
              var result = obj.map(function(a) {
                var filterParam = document.getElementById("filter-6").value;
                return a[filterParam];
              });
              document.getElementById("res-6").innerHTML = "
" + result.toString().replace(/,/g, "; ") + "
";
            } else {
              console.log("Users not loaded!", http.responseText);
              document.getElementById("res-6").innerHTML = "
Error " + http.status + "
";
            }
          }
        };

        http.send(null);
      });
    }();

    var oAuthSimpleLogin = function(){
    	var lock = new Auth0Lock('NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA', 'danvitoriano.auth0.com');

		  // buttons
		  var btn_login = document.getElementById('btn-login-7');
		  var btn_logout = document.getElementById('btn-logout-7');

		  btn_login.addEventListener('click', function() {
		    lock.show();
		  });

		  btn_logout.addEventListener('click', function() {
		    logout();
		  });

		  lock.on("authenticated", function(authResult) {
		    localStorage.setItem('oAuthSimpleLogin', authResult.idToken);
		    btn_login.style.display = "none";
		    btn_logout.style.display = "inline-block";
		  });

		  var init = function() {
		    var id_token = localStorage.getItem('oAuthSimpleLogin');
		    if (id_token) {
		      btn_login.style.display = "none";
		      btn_logout.style.display = "inline-block";
		    }
		  };

		  var logout = function() {
		    localStorage.removeItem('oAuthSimpleLogin');
		    window.location.href = "/";
		  };

		  init();
    }();

    var oAuthProfileLogin = function() {
    	var lock = new Auth0Lock('NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA', 'danvitoriano.auth0.com');

		  // buttons
		  var btn_login = document.getElementById('btn-login-8');
		  var btn_logout = document.getElementById('btn-logout-8');

		  btn_login.addEventListener('click', function() {
		    lock.show();
		  });

		  btn_logout.addEventListener('click', function() {
		    logout();
		  });

		  lock.on("authenticated", function(authResult) {
		    lock.getProfile(authResult.idToken, function(error, profile) {
		      if (error) {
		        // Handle error
		        return;
		      }
		      localStorage.setItem('oAuthProfileLogin', authResult.idToken);
		      // Display user information
		      show_profile_info(profile);
		    });
		  });

		  //retrieve the profile:
		  var retrieve_profile = function() {
		    var id_token = localStorage.getItem('oAuthProfileLogin');
		    if (id_token) {
		      lock.getProfile(id_token, function (err, profile) {
		        if (err) {
		          return alert('There was an error getting the profile: ' + err.message);
		        }
		        // Display user information
		        show_profile_info(profile);
		      });
		    }
		  };

		  var show_profile_info = function(profile) {
		    var avatar = document.getElementById('avatar');
		    var nickname = document.getElementById('nickname');
		    nickname.textContent = "Welcome " + profile.nickname;
		    btn_login.style.display = "none";
		    avatar.src = profile.picture;
		    avatar.style.display = "block";
		    nickname.style.display = "block";
		    btn_logout.style.display = "block";
		  };

		  var logout = function() {
		    localStorage.removeItem('oAuthProfileLogin');
		    window.location.href = "/";
		  };

		  retrieve_profile();
    }();

})();<commit_msg>add oauth 2 login and get profile examples<commit_after>;
(function() {

    var api = "https://jsonplaceholder.typicode.com";
    var userId = 1; // default to JSONPlaceholder API

    var postJquery = function() {
      $("#btn-submit-1").click(function() {
        var title = $("#title-1").val();
        var body = $("#body-1").val();
        $.ajax({
          type: 'POST',
          url: api + '/posts',
          dataType: "json",
          data: {
            title: title,
            body: body,
            userId: userId
          },
          success: function(data) {
            console.log("Content added!", data); //the new item is returned with an ID
            $("#res-1").html("
" + JSON.stringify(data) + "
");
            $("#form-1")[0].reset();
          },
          error: function(data) {
            console.log("Content not added!", data); //the new item is returned with an ID
            $("#res-1").html("
Error " + JSON.stringify(data) + "
");
          }
        });
      });
    }();

    var postJS = function() {
      document.getElementById("btn-submit-2").addEventListener("click", function() {
        var title = document.getElementById("title-2").value;
        var body = document.getElementById("body-2").value;
        var http = new XMLHttpRequest();
        var params = "title=" + title + "&body=" + body + "&userId=" + userId;
        var url = api + "/posts";

        http.open("POST", url, true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 201) {
              console.log("Content added!", http.responseText);
              document.getElementById("res-2").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-2").reset();
            } else {
              console.log("User not added!", http.responseText);
              document.getElementById("res-2").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(params);
      });
    }();

    var putJS = function() {
      document.getElementById("btn-submit-3").addEventListener("click", function() {
        var id = document.getElementById("id-3").value;
        var title = document.getElementById("title-3").value;
        var body = document.getElementById("body-3").value;
        var http = new XMLHttpRequest();
        var params = "title=" + title + "&body=" + body + "&userId=" + userId + "&id=" + id;
        var url = api + "/posts/" + id;

        http.open("PUT", url, true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Content updated!", http.responseText);
              document.getElementById("res-3").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-3").reset();
            } else {
              console.log("Content not updated!", http.responseText);
              document.getElementById("res-3").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(params);
      });
    }();

    var patchJS = function() {
      document.getElementById("btn-submit-4").addEventListener("click", function() {
        var id = document.getElementById("id-4").value;
        var title = document.getElementById("title-4").value;
        var http = new XMLHttpRequest();
        var params = "title=" + title;
        var url = api + "/posts/" + id;

        http.open("PATCH", url, true);

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Content updated!", http.responseText);
              document.getElementById("res-4").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-4").reset();
            } else {
              console.log("Content not updated!", http.responseText);
              document.getElementById("res-4").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(params);
      });
    }();

    var getOneItemJS = function() {
      document.getElementById("btn-submit-5").addEventListener("click", function() {
        var id = document.getElementById("id-5").value;
        var http = new XMLHttpRequest();
        var url = api + "/posts/" + id;

        http.open("GET", url, true);

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Content loaded!", http.responseText);
              document.getElementById("res-5").innerHTML = "
" + http.responseText + "
";
              document.getElementById("form-5").reset();
            } else {
              console.log("Content not updated!", http.responseText);
              document.getElementById("res-5").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
            }
          }
        }
        http.send(null);
      });
    }();

    var getAllItensFilterJS = function() {
      document.getElementById("btn-submit-6").addEventListener("click", function() {
        var http = new XMLHttpRequest();
        var url = api + "/users";

        http.open("GET", url, true);

        http.onload = function() {
          if (http.readyState === http.DONE) {
            if (http.status === 200) {
              console.log("Users loaded!", http.responseText);
              var obj = JSON.parse(http.responseText);
              var result = obj.map(function(a) {
                var filterParam = document.getElementById("filter-6").value;
                return a[filterParam];
              });
              document.getElementById("res-6").innerHTML = "
" + result.toString().replace(/,/g, "; ") + "
";
            } else {
              console.log("Users not loaded!", http.responseText);
              document.getElementById("res-6").innerHTML = "
Error " + http.status + "
";
            }
          }
        };

        http.send(null);
      });
    }();

    var oAuthSimpleLogin = function(){
    	var lock = new Auth0Lock('NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA', 'danvitoriano.auth0.com');

		  // buttons
		  var btn_login = document.getElementById('btn-login-7');
		  var btn_logout = document.getElementById('btn-logout-7');

		  btn_login.addEventListener('click', function() {
		    lock.show();
		  });

		  btn_logout.addEventListener('click', function() {
		    logout();
		  });

		  lock.on("authenticated", function(authResult) {
		    localStorage.setItem('oAuthSimpleLogin', authResult.idToken);
		    btn_login.style.display = "none";
		    btn_logout.style.display = "inline-block";
		  });

		  var init = function() {
		    var id_token = localStorage.getItem('oAuthSimpleLogin');
		    if (id_token) {
		      btn_login.style.display = "none";
		      btn_logout.style.display = "inline-block";
		    }
		  };

		  var logout = function() {
		    localStorage.removeItem('oAuthSimpleLogin');
		    window.location.href = "/rest-api-examples/";
		  };

		  init();
    }();

    var oAuthProfileLogin = function() {
    	var lock = new Auth0Lock('NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA', 'danvitoriano.auth0.com');

		  // buttons
		  var btn_login = document.getElementById('btn-login-8');
		  var btn_logout = document.getElementById('btn-logout-8');

		  btn_login.addEventListener('click', function() {
		    lock.show();
		  });

		  btn_logout.addEventListener('click', function() {
		    logout();
		  });

		  lock.on("authenticated", function(authResult) {
		    lock.getProfile(authResult.idToken, function(error, profile) {
		      if (error) {
		        // Handle error
		        return;
		      }
		      localStorage.setItem('oAuthProfileLogin', authResult.idToken);
		      // Display user information
		      show_profile_info(profile);
		    });
		  });

		  //retrieve the profile:
		  var retrieve_profile = function() {
		    var id_token = localStorage.getItem('oAuthProfileLogin');
		    if (id_token) {
		      lock.getProfile(id_token, function (err, profile) {
		        if (err) {
		          return alert('There was an error getting the profile: ' + err.message);
		        }
		        // Display user information
		        show_profile_info(profile);
		      });
		    }
		  };

		  var show_profile_info = function(profile) {
		    var avatar = document.getElementById('avatar');
		    var nickname = document.getElementById('nickname');
		    nickname.textContent = "Welcome " + profile.nickname;
		    btn_login.style.display = "none";
		    avatar.src = profile.picture;
		    avatar.style.display = "block";
		    nickname.style.display = "block";
		    btn_logout.style.display = "block";
		  };

		  var logout = function() {
		    localStorage.removeItem('oAuthProfileLogin');
		    window.location.href = "/rest-api-examples/";
		  };

		  retrieve_profile();
    }();

})();<|endoftext|>


<commit_before>// Grouping module
;(function($){
"use strict";
$.jgrid.extend({
	groupingSetup : function () {
		return this.each(function (){
			var $t = this,
			grp = $t.p.groupingView;
			if(grp !== null && ( (typeof grp === 'object') || $.isFunction(grp) ) ) {
				if(!grp.groupField.length) {
					$t.p.grouping = false;
				} else {
					if ( typeof(grp.visibiltyOnNextGrouping) == 'undefined') {
						grp.visibiltyOnNextGrouping = [];
					}
					for(var i=0;i<grp.groupField.length;i++) {
						if(!grp.groupOrder[i]) {
							grp.groupOrder[i] = 'asc';
						}
						if(!grp.groupText[i]) {
							grp.groupText[i] = '{0}';
						}
						if( typeof(grp.groupColumnShow[i]) != 'boolean') {
							grp.groupColumnShow[i] = true;
						}
						if( typeof(grp.groupSummary[i]) != 'boolean') {
							grp.groupSummary[i] = false;
						}
						if(grp.groupColumnShow[i] === true) {
							grp.visibiltyOnNextGrouping[i] = true;
							$($t).jqGrid('showCol',grp.groupField[i]);
						} else {
							grp.visibiltyOnNextGrouping[i] = $("#"+$t.p.id+"_"+grp.groupField[i]).is(":visible");
							$($t).jqGrid('hideCol',grp.groupField[i]);
						}
						grp.sortitems[i] = [];
						grp.sortnames[i] = [];
						grp.summaryval[i] = [];
						if(grp.groupSummary[i]) {
							grp.summary[i] =[];
							var cm = $t.p.colModel;
							for(var j=0, cml = cm.length; j < cml; j++) {
								if(cm[j].summaryType) {
									grp.summary[i].push({nm:cm[j].name,st:cm[j].summaryType, v:''});
								}
							}
						}
					}
				}
			} else {
				$t.p.grouping = false;
			}
		});
	},
	groupingPrepare : function (rData, items, gdata, record) {
		this.each(function(){
			// currently only one level
			// Is this a good idea to do it so!!!!?????
			items[0]  += "";
			var itm = items[0].toString().split(' ').join('');

			var grp = this.p.groupingView, $t= this;
			if(gdata.hasOwnProperty(itm)) {
				gdata[itm].push(rData);
			} else {
				gdata[itm] = [];
				gdata[itm].push(rData);
				grp.sortitems[0].push(itm);
				grp.sortnames[0].push($.trim(items[0].toString()));
				grp.summaryval[0][itm] = $.extend(true,[],grp.summary[0]);
			}
			if(grp.groupSummary[0]) {
				$.each(grp.summaryval[0][itm],function() {
					if ($.isFunction(this.st)) {
						this.v = this.st.call($t, this.v, this.nm, record);
					} else {
						this.v = $($t).jqGrid('groupingCalculations.'+this.st, this.v, this.nm, record);
					}
				});
			}
		});
		return gdata;
	},
	groupingToggle : function(hid){
		this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			strpos = hid.lastIndexOf('_'),
			uid = hid.substring(0,strpos+1),
			num = parseInt(hid.substring(strpos+1),10)+1,
			minus = grp.minusicon,
			plus = grp.plusicon,
			tar = $("#"+hid),
			r = tar.length ? tar[0].nextSibling : null,
			tarspan = $("#"+hid+" span."+"tree-wrap-"+$t.p.direction),
			collapsed = false;
			if( tarspan.hasClass(minus) ) {
				if(grp.showSummaryOnHide && grp.groupSummary[0]) {
					if(r){
						while(r) {
							if($(r).hasClass('jqfoot') ) { break; }
							$(r).hide();
							r = r.nextSibling;
						}
					}
				} else  {
					if(r){
						while(r) {
							if($(r).attr('id') ==uid+String(num) ) { break; }
							$(r).hide();
							r = r.nextSibling;
						}
					}
				}
				tarspan.removeClass(minus).addClass(plus);
				collapsed = true;
			} else {
				if(r){
					while(r) {
						if($(r).attr('id') ==uid+String(num) ) { break; }
						$(r).show();
						r = r.nextSibling;
					}
				}
				tarspan.removeClass(plus).addClass(minus);
			}
			$($t).triggerHandler("jqGridGroupingClickGroup", [hid , collapsed]);
			if( $.isFunction($t.p.onClickGroup)) { $t.p.onClickGroup.call($t, hid , collapsed); }

		});
		return false;
	},
	groupingRender : function (grdata, colspans ) {
		return this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			str = "", icon = "", hid, pmrtl = grp.groupCollapse ? grp.plusicon : grp.minusicon, gv, cp, ii;
			//only one level for now
			if(!grp.groupDataSorted) {
				// ???? TO BE IMPROVED
				grp.sortitems[0].sort();
				grp.sortnames[0].sort();
				if(grp.groupOrder[0].toLowerCase() == 'desc')
				{
					grp.sortitems[0].reverse();
					grp.sortnames[0].reverse();
				}
			}
			pmrtl += " tree-wrap-"+$t.p.direction;
			ii = 0;
			while(ii < colspans) {
				if($t.p.colModel[ii].name == grp.groupField[0]) {
					cp = ii;
					break;
				}
				ii++;
			}
			$.each(grp.sortitems[0],function(i,n){
				hid = $t.p.id+"ghead_"+i;
				icon = "";
				try {
					gv = $t.formatter(hid, grp.sortnames[0][i], cp, grp.sortitems[0] );
				} catch (egv) {
					gv = grp.sortnames[0][i];
				}
				str += "
"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"
";
				for(var kk=0;kk<grdata[n].length;kk++) {
					str += grdata[n][kk].join('');
				}
				if(grp.groupSummary[0]) {
					var hhdr = "";
					if(grp.groupCollapse && !grp.showSummaryOnHide) {
						hhdr = " style=\"display:none;\"";
					}
					str += "
";
					var fdata = grp.summaryval[0][n],
					cm = $t.p.colModel,
					vv, grlen = grdata[n].length;
					for(var k=0; k<colspans;k++) {
						var tmpdata = " 	",
						tplfld = "{0}";
						$.each(fdata,function(){
							if(this.nm == cm[k].name) {
								if(cm[k].summaryTpl)  {
									tplfld = cm[k].summaryTpl;
								}
								if(this.st == 'avg') {
									if(this.v && grlen > 0) {
										this.v = (this.v/grlen);
									}
								}
								try {
									vv = $t.formatter('', this.v, k, this);
								} catch (ef) {
									vv = this.v;
								}
								tmpdata= ""+$.jgrid.format(tplfld,vv)+ "	";
								return false;
							}
						});
						str += tmpdata;
					}
					str += "
";
				}
			});
			$("#"+$t.p.id+" tbody:first").append(str);
			// free up memory
			str = null;
		});
	},
	groupingGroupBy : function (name, options ) {
		return this.each(function(){
			var $t = this;
			if(typeof(name) == "string") {
				name = [name];
			}
			var grp = $t.p.groupingView;
			$t.p.grouping = true;

			//Set default, in case visibilityOnNextGrouping is undefined
			if (typeof grp.visibiltyOnNextGrouping == "undefined") {
				grp.visibiltyOnNextGrouping = [];
			}
			var i;
			// show previous hidden groups if they are hidden and weren't removed yet
			for(i=0;i<grp.groupField.length;i++) {
				if(!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
				$($t).jqGrid('showCol',grp.groupField[i]);
				}
			}
			// set visibility status of current group columns on next grouping
			for(i=0;i<name.length;i++) {
				grp.visibiltyOnNextGrouping[i] = $("#"+$t.p.id+"_"+name[i]).is(":visible");
			}
			$t.p.groupingView = $.extend($t.p.groupingView, options || {});
			grp.groupField = name;
			$($t).trigger("reloadGrid");
		});
	},
	groupingRemove : function (current) {
		return this.each(function(){
			var $t = this;
			if(typeof(current) == 'undefined') {
				current = true;
			}
			$t.p.grouping = false;
			if(current===true) {
				var grp = $t.p.groupingView;
				// show previous hidden groups if they are hidden and weren't removed yet
				for(var i=0;i<grp.groupField.length;i++) {
				if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
						$($t).jqGrid('showCol', grp.groupField);
					}
				}
				$("tr.jqgroup, tr.jqfoot","#"+$t.p.id+" tbody:first").remove();
				$("tr.jqgrow:hidden","#"+$t.p.id+" tbody:first").show();
			} else {
				$($t).trigger("reloadGrid");
			}
		});
	},
	groupingCalculations : {
		"sum" : function(v, field, rc) {
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		},
		"min" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.min(parseFloat(v),parseFloat(rc[field]||0));
		},
		"max" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.max(parseFloat(v),parseFloat(rc[field]||0));
		},
		"count" : function(v, field, rc) {
			if(v==="") {v=0;}
			if(rc.hasOwnProperty(field)) {
				return v+1;
			} else {
				return 0;
			}
		},
		"avg" : function(v, field, rc) {
			// the same as sum, but at end we divide it
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		}
	}
});
})(jQuery);
<commit_msg>Fix grouping to use jqID in jQuery selectors<commit_after>// Grouping module
;(function($){
"use strict";
$.jgrid.extend({
	groupingSetup : function () {
		return this.each(function (){
			var $t = this,
			grp = $t.p.groupingView;
			if(grp !== null && ( (typeof grp === 'object') || $.isFunction(grp) ) ) {
				if(!grp.groupField.length) {
					$t.p.grouping = false;
				} else {
					if ( typeof(grp.visibiltyOnNextGrouping) == 'undefined') {
						grp.visibiltyOnNextGrouping = [];
					}
					for(var i=0;i<grp.groupField.length;i++) {
						if(!grp.groupOrder[i]) {
							grp.groupOrder[i] = 'asc';
						}
						if(!grp.groupText[i]) {
							grp.groupText[i] = '{0}';
						}
						if( typeof(grp.groupColumnShow[i]) != 'boolean') {
							grp.groupColumnShow[i] = true;
						}
						if( typeof(grp.groupSummary[i]) != 'boolean') {
							grp.groupSummary[i] = false;
						}
						if(grp.groupColumnShow[i] === true) {
							grp.visibiltyOnNextGrouping[i] = true;
							$($t).jqGrid('showCol',grp.groupField[i]);
						} else {
							grp.visibiltyOnNextGrouping[i] = $("#"+$.jgrid.jqID($t.p.id+"_"+grp.groupField[i])).is(":visible");
							$($t).jqGrid('hideCol',grp.groupField[i]);
						}
						grp.sortitems[i] = [];
						grp.sortnames[i] = [];
						grp.summaryval[i] = [];
						if(grp.groupSummary[i]) {
							grp.summary[i] =[];
							var cm = $t.p.colModel;
							for(var j=0, cml = cm.length; j < cml; j++) {
								if(cm[j].summaryType) {
									grp.summary[i].push({nm:cm[j].name,st:cm[j].summaryType, v:''});
								}
							}
						}
					}
				}
			} else {
				$t.p.grouping = false;
			}
		});
	},
	groupingPrepare : function (rData, items, gdata, record) {
		this.each(function(){
			// currently only one level
			// Is this a good idea to do it so!!!!?????
			items[0]  += "";
			var itm = items[0].toString().split(' ').join('');

			var grp = this.p.groupingView, $t= this;
			if(gdata.hasOwnProperty(itm)) {
				gdata[itm].push(rData);
			} else {
				gdata[itm] = [];
				gdata[itm].push(rData);
				grp.sortitems[0].push(itm);
				grp.sortnames[0].push($.trim(items[0].toString()));
				grp.summaryval[0][itm] = $.extend(true,[],grp.summary[0]);
			}
			if(grp.groupSummary[0]) {
				$.each(grp.summaryval[0][itm],function() {
					if ($.isFunction(this.st)) {
						this.v = this.st.call($t, this.v, this.nm, record);
					} else {
						this.v = $($t).jqGrid('groupingCalculations.'+this.st, this.v, this.nm, record);
					}
				});
			}
		});
		return gdata;
	},
	groupingToggle : function(hid){
		this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			strpos = hid.lastIndexOf('_'),
			uid = hid.substring(0,strpos+1),
			num = parseInt(hid.substring(strpos+1),10)+1,
			minus = grp.minusicon,
			plus = grp.plusicon,
			tar = $("#"+$.jgrid.jqID(hid)),
			r = tar.length ? tar[0].nextSibling : null,
			tarspan = $("#"+$.jgrid.jqID(hid)+" span."+"tree-wrap-"+$t.p.direction),
			collapsed = false;
			if( tarspan.hasClass(minus) ) {
				if(grp.showSummaryOnHide && grp.groupSummary[0]) {
					if(r){
						while(r) {
							if($(r).hasClass('jqfoot') ) { break; }
							$(r).hide();
							r = r.nextSibling;
						}
					}
				} else  {
					if(r){
						while(r) {
							if($(r).attr('id') ==uid+String(num) ) { break; }
							$(r).hide();
							r = r.nextSibling;
						}
					}
				}
				tarspan.removeClass(minus).addClass(plus);
				collapsed = true;
			} else {
				if(r){
					while(r) {
						if($(r).attr('id') ==uid+String(num) ) { break; }
						$(r).show();
						r = r.nextSibling;
					}
				}
				tarspan.removeClass(plus).addClass(minus);
			}
			$($t).triggerHandler("jqGridGroupingClickGroup", [hid , collapsed]);
			if( $.isFunction($t.p.onClickGroup)) { $t.p.onClickGroup.call($t, hid , collapsed); }

		});
		return false;
	},
	groupingRender : function (grdata, colspans ) {
		return this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			str = "", icon = "", hid, pmrtl = grp.groupCollapse ? grp.plusicon : grp.minusicon, gv, cp, ii;
			//only one level for now
			if(!grp.groupDataSorted) {
				// ???? TO BE IMPROVED
				grp.sortitems[0].sort();
				grp.sortnames[0].sort();
				if(grp.groupOrder[0].toLowerCase() == 'desc')
				{
					grp.sortitems[0].reverse();
					grp.sortnames[0].reverse();
				}
			}
			pmrtl += " tree-wrap-"+$t.p.direction;
			ii = 0;
			while(ii < colspans) {
				if($t.p.colModel[ii].name == grp.groupField[0]) {
					cp = ii;
					break;
				}
				ii++;
			}
			$.each(grp.sortitems[0],function(i,n){
				hid = $t.p.id+"ghead_"+i;
				icon = "";
				try {
					gv = $t.formatter(hid, grp.sortnames[0][i], cp, grp.sortitems[0] );
				} catch (egv) {
					gv = grp.sortnames[0][i];
				}
				str += "
"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"
";
				for(var kk=0;kk<grdata[n].length;kk++) {
					str += grdata[n][kk].join('');
				}
				if(grp.groupSummary[0]) {
					var hhdr = "";
					if(grp.groupCollapse && !grp.showSummaryOnHide) {
						hhdr = " style=\"display:none;\"";
					}
					str += "
";
					var fdata = grp.summaryval[0][n],
					cm = $t.p.colModel,
					vv, grlen = grdata[n].length;
					for(var k=0; k<colspans;k++) {
						var tmpdata = " 	",
						tplfld = "{0}";
						$.each(fdata,function(){
							if(this.nm == cm[k].name) {
								if(cm[k].summaryTpl)  {
									tplfld = cm[k].summaryTpl;
								}
								if(this.st == 'avg') {
									if(this.v && grlen > 0) {
										this.v = (this.v/grlen);
									}
								}
								try {
									vv = $t.formatter('', this.v, k, this);
								} catch (ef) {
									vv = this.v;
								}
								tmpdata= ""+$.jgrid.format(tplfld,vv)+ "	";
								return false;
							}
						});
						str += tmpdata;
					}
					str += "
";
				}
			});
			$("#"+$.jgrid.jqID($t.p.id)+" tbody:first").append(str);
			// free up memory
			str = null;
		});
	},
	groupingGroupBy : function (name, options ) {
		return this.each(function(){
			var $t = this;
			if(typeof(name) == "string") {
				name = [name];
			}
			var grp = $t.p.groupingView;
			$t.p.grouping = true;

			//Set default, in case visibilityOnNextGrouping is undefined
			if (typeof grp.visibiltyOnNextGrouping == "undefined") {
				grp.visibiltyOnNextGrouping = [];
			}
			var i;
			// show previous hidden groups if they are hidden and weren't removed yet
			for(i=0;i<grp.groupField.length;i++) {
				if(!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
				$($t).jqGrid('showCol',grp.groupField[i]);
				}
			}
			// set visibility status of current group columns on next grouping
			for(i=0;i<name.length;i++) {
				grp.visibiltyOnNextGrouping[i] = $("#"+$.jgrid.jqID($t.p.id)+"_"+$.jgrid.jqID(name[i])).is(":visible");
			}
			$t.p.groupingView = $.extend($t.p.groupingView, options || {});
			grp.groupField = name;
			$($t).trigger("reloadGrid");
		});
	},
	groupingRemove : function (current) {
		return this.each(function(){
			var $t = this;
			if(typeof(current) == 'undefined') {
				current = true;
			}
			$t.p.grouping = false;
			if(current===true) {
				var grp = $t.p.groupingView;
				// show previous hidden groups if they are hidden and weren't removed yet
				for(var i=0;i<grp.groupField.length;i++) {
				if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
						$($t).jqGrid('showCol', grp.groupField);
					}
				}
				$("tr.jqgroup, tr.jqfoot","#"+$.jgrid.jqID($t.p.id)+" tbody:first").remove();
				$("tr.jqgrow:hidden","#"+$.jgrid.jqID($t.p.id)+" tbody:first").show();
			} else {
				$($t).trigger("reloadGrid");
			}
		});
	},
	groupingCalculations : {
		"sum" : function(v, field, rc) {
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		},
		"min" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.min(parseFloat(v),parseFloat(rc[field]||0));
		},
		"max" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.max(parseFloat(v),parseFloat(rc[field]||0));
		},
		"count" : function(v, field, rc) {
			if(v==="") {v=0;}
			if(rc.hasOwnProperty(field)) {
				return v+1;
			} else {
				return 0;
			}
		},
		"avg" : function(v, field, rc) {
			// the same as sum, but at end we divide it
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		}
	}
});
})(jQuery);
<|endoftext|>


<commit_before>iD.modes.Move = function(context, entityIDs) {
    var mode = {
        id: 'move',
        button: 'browse'
    };

    var keybinding = d3.keybinding('move'),
        edit = iD.behavior.Edit(context),
        annotation = entityIDs.length === 1 ?
            t('operations.move.annotation.' + context.geometry(entityIDs[0])) :
            t('operations.move.annotation.multiple'),
        cache,
        origin,
        nudgeInterval;

    function clearCache() {
        cache = {
            startLoc: {},
        };
    }

    function cacheLocs(ids) {
        _.each(ids, function(id) {
            var entity = context.entity(id);

            if (entity.type === 'node') {
                cache.startLoc[id] = entity.loc;
            } else if (entity.type === 'way') {
                cacheLocs(entity.nodes);
            } else {
                cacheLocs(_.pluck(entity.members, 'id'));
            }
        });
    }

    function edge(point, size) {
        var pad = [30, 100, 30, 100];
        if (point[0] > size[0] - pad[0]) return [-10, 0];
        else if (point[0] < pad[2]) return [10, 0];
        else if (point[1] > size[1] - pad[1]) return [0, -10];
        else if (point[1] < pad[3]) return [0, 10];
        return null;
    }

    function startNudge(nudge) {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = window.setInterval(function() {
            context.pan(nudge);
            context.replace(
                iD.actions.Move(entityIDs, [-nudge[0], -nudge[1]], context.projection, cache),
                annotation);
            var c = context.projection(origin);
            origin = context.projection.invert([c[0] - nudge[0], c[1] - nudge[1]]);
        }, 50);
    }

    function stopNudge() {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = null;
    }

    function move() {
        var p = context.mouse();

        var delta = origin ?
            [p[0] - context.projection(origin)[0],
                p[1] - context.projection(origin)[1]] :
            [0, 0];

        var nudge = edge(p, context.map().dimensions());
        if (nudge) startNudge(nudge);
        else stopNudge();

        origin = context.map().mouseCoordinates();

        context.replace(
            iD.actions.Move(entityIDs, delta, context.projection, cache),
            annotation);
    }

    function finish() {
        d3.event.stopPropagation();
        context.enter(iD.modes.Select(context, entityIDs)
            .suppressMenu(true));
        stopNudge();
    }

    function cancel() {
        context.pop();
        context.enter(iD.modes.Select(context, entityIDs)
            .suppressMenu(true));
        stopNudge();
    }

    function undone() {
        context.enter(iD.modes.Browse(context));
    }

    mode.enter = function() {
        clearCache();
        cacheLocs(entityIDs);

        context.install(edit);

        context.perform(
            iD.actions.Noop(),
            annotation);

        context.surface()
            .on('mousemove.move', move)
            .on('click.move', finish);

        context.history()
            .on('undone.move', undone);

        keybinding
            .on('⎋', cancel)
            .on('↩', finish);

        d3.select(document)
            .call(keybinding);
    };

    mode.exit = function() {
        stopNudge();

        context.uninstall(edit);

        context.surface()
            .on('mousemove.move', null)
            .on('click.move', null);

        context.history()
            .on('undone.move', null);

        keybinding.off();
    };

    return mode;
};
<commit_msg>Perform moves idempotently<commit_after>iD.modes.Move = function(context, entityIDs) {
    var mode = {
        id: 'move',
        button: 'browse'
    };

    var keybinding = d3.keybinding('move'),
        edit = iD.behavior.Edit(context),
        annotation = entityIDs.length === 1 ?
            t('operations.move.annotation.' + context.geometry(entityIDs[0])) :
            t('operations.move.annotation.multiple'),
        cache,
        origin,
        delta,
        nudgeInterval;

    function clearCache() {
        cache = {
            moving: {},
            startLoc: {}
        };
    }

    function cacheLocs(ids) {
        _.each(ids, function(id) {
            if (cache.moving[id]) return;
            cache.moving[id] = true;

            var entity = context.hasEntity(id);
            if (!entity) return;

            if (entity.type === 'node') {
                cache.startLoc[id] = entity.loc;
            } else if (entity.type === 'way') {
                cacheLocs(entity.nodes);
            } else {
                cacheLocs(_.pluck(entity.members, 'id'));
            }
        });
    }

    function edge(point, size) {
        var pad = [30, 100, 30, 100];
        if (point[0] > size[0] - pad[0]) return [-10, 0];
        else if (point[0] < pad[2]) return [10, 0];
        else if (point[1] > size[1] - pad[1]) return [0, -10];
        else if (point[1] < pad[3]) return [0, 10];
        return null;
    }

    function startNudge(nudge) {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = window.setInterval(function() {
            context.pan(nudge);

            var orig = context.projection(origin);

            orig = [orig[0] - nudge[1], orig[1] - nudge[1]];
            delta = [delta[0] - nudge[0], delta[1] - nudge[1]];
            origin = context.projection.invert(orig);

            context.pop();
            context.perform(
                iD.actions.Move(entityIDs, delta, context.projection, cache),
                annotation);
        }, 50);
    }

    function stopNudge() {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = null;
    }

    function move() {
        var mouse = context.mouse(),
            orig = context.projection(origin);

        delta = [mouse[0] - orig[0], mouse[1] - orig[1]];

        var nudge = edge(mouse, context.map().dimensions());
        if (nudge) startNudge(nudge);
        else stopNudge();

        context.pop();
        context.perform(
            iD.actions.Move(entityIDs, delta, context.projection, cache),
            annotation);
    }

    function finish() {
        d3.event.stopPropagation();
        context.enter(iD.modes.Select(context, entityIDs)
            .suppressMenu(true));
        stopNudge();
    }

    function cancel() {
        context.pop();
        context.enter(iD.modes.Select(context, entityIDs)
            .suppressMenu(true));
        stopNudge();
    }

    function undone() {
        context.enter(iD.modes.Browse(context));
    }

    mode.enter = function() {
        clearCache();
        cacheLocs(entityIDs);
        origin = context.map().mouseCoordinates();
        delta = [0, 0];

        context.install(edit);

        context.perform(
            iD.actions.Noop(),
            annotation);

        context.surface()
            .on('mousemove.move', move)
            .on('click.move', finish);

        context.history()
            .on('undone.move', undone);

        keybinding
            .on('⎋', cancel)
            .on('↩', finish);

        d3.select(document)
            .call(keybinding);
    };

    mode.exit = function() {
        stopNudge();

        context.uninstall(edit);

        context.surface()
            .on('mousemove.move', null)
            .on('click.move', null);

        context.history()
            .on('undone.move', null);

        keybinding.off();
    };

    return mode;
};
<|endoftext|>


<commit_before>$(document).ready(function() {
        // Fill modal with content from link href
        $(".openModal").on("click", function(e) {
            var link = $(this).data("href");
        $('#popup').modal("show");
        $('#popup .modal-body').load(link );
        });
    })

jQuery(function($) {
    //
    $('#output').html('script here<'+'script>$(document).ready(function() { $(".openModal").on("click", function(e) {var link = $(this).data("href"); $('#popup').modal("show"); $('#popup .modal-body').load(link ); }); })</s' + 'cript>')

});
<commit_msg>Update modal.js<commit_after>$(document).ready(function() {
        // Fill modal with content from link href
        $(".openModal").on("click", function(e) {
            var link = $(this).data("href");
        $('#popup').modal("show");
        $('#popup .modal-body').load(link );
        });
    })
<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/combine',
        '../Core/Credit',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/DeveloperError',
        '../Core/Event',
        '../Core/freezeObject',
        '../Core/objectToQuery',
        '../Core/queryToObject',
        '../Core/Rectangle',
        '../Core/WebMercatorTilingScheme',
        '../ThirdParty/Uri',
        './ImageryProvider'
    ], function(
        combine,
        Credit,
        defaultValue,
        defined,
        defineProperties,
        DeveloperError,
        Event,
        freezeObject,
        objectToQuery,
        queryToObject,
        Rectangle,
        WebMercatorTilingScheme,
        Uri,
        ImageryProvider) {
    "use strict";

    /**
     * Provides tiled imagery served by {@link http://www.opengeospatial.org/standards/wmts|WMTS 1.0.0} compliant servers.
     * This provider supports HTTP KVP-encoded GetTile requests, but does not yet support SOAP and RESTful encoding.
     *
     * @alias WebMapTileServiceImageryProvider
     * @constructor
     *
     * @param {Object} options Object with the following properties:
     * @param {String} options.url The WMTS server url.
     * @param {String} [options.format='image/jpeg'] The MIME type for images to retrieve from the server.
     * @param {String} options.layer The layer name for WMTS requests.
     * @param {String} options.style The style name for WMTS requests.
     * @param {String} options.tileMatrixSetID The identifier of the TileMatrixSet to use for WMTS requests.
     * @param {Array} [options.tileMatrixLabels] A list of identifiers in the TileMatrix to use for WMTS requests, one per TileMatrix level.
     * @param {Number} [options.tileWidth=256] The tile width in pixels.
     * @param {Number} [options.tileHeight=256] The tile height in pixels.
     * @param {TilingScheme} [options.tilingScheme] The tiling scheme corresponding to the organization of the tiles in the TileMatrixSet.
     * @param {Object} [options.proxy] A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL.
     * @param {Rectangle} [options.rectangle=Rectangle.MAX_VALUE] The rectangle covered by the layer.
     * @param {Number} [options.minimumLevel=0] The minimum level-of-detail supported by the imagery provider.
     * @param {Number} [options.maximumLevel=18] The maximum level-of-detail supported by the imagery provider.
     * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
     *
     * @see ArcGisMapServerImageryProvider
     * @see BingMapsImageryProvider
     * @see SingleTileImageryProvider
     * @see TileMapServiceImageryProvider
     * @see WebMapServiceImageryProvider
     *
     * @example
     * // USGS shaded relief tile provider
     * var shadedRelief = new Cesium.WebMapTileServiceImageryProvider({
     *     url : 'http://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS',
     *     layer : 'USGSShadedReliefOnly',
     *     style : 'default',
     *     format : 'image/jpeg',
     *     tileMatrixSetID : 'default028mm',
     *     // tileMatrixLabels : ['default028mm:0', 'default028mm:1', 'default028mm:2' ...],
     *     maximumLevel: 19,
     *     credit : new Cesium.Credit('U. S. Geological Survey')
     * });
     * viewer.scene.imageryLayers.addImageryProvider(shadedRelief);
     */
    var WebMapTileServiceImageryProvider = function WebMapTileServiceImageryProvider(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        if (!defined(options.url)) {
            throw new DeveloperError('options.url is required.');
        }
        if (!defined(options.layer)) {
            throw new DeveloperError('options.layer is required.');
        }
        if (!defined(options.style)) {
            throw new DeveloperError('options.style is required.');
        }
        if (!defined(options.tileMatrixSetID)) {
            throw new DeveloperError('options.tileMatrixSetID is required.');
        }

        this._url = options.url;
        this._layer = options.layer;
        this._style = options.style;
        this._tileMatrixSetID = options.tileMatrixSetID;
        this._tileMatrixLabels = options.tileMatrixLabels;
        this._format = defaultValue(options.format, 'image/jpeg');
        this._proxy = options.proxy;
        this._tileDiscardPolicy = options.tileDiscardPolicy;

        this._tilingScheme = defined(options.tilingScheme) ? options.tilingScheme : new WebMercatorTilingScheme();
        this._tileWidth = defaultValue(options.tileWidth, 256);
        this._tileHeight = defaultValue(options.tileHeight, 256);

        this._minimumLevel = defaultValue(options.minimumLevel, 0);
        this._maximumLevel = defaultValue(options.maximumLevel, 18);

        this._rectangle = defaultValue(options.rectangle, this._tilingScheme.rectangle);

        // Check the number of tiles at the minimum level.  If it's more than four,
        // throw an exception, because starting at the higher minimum
        // level will cause too many tiles to be downloaded and rendered.
        var swTile = this._tilingScheme.positionToTileXY(Rectangle.southwest(this._rectangle), this._minimumLevel);
        var neTile = this._tilingScheme.positionToTileXY(Rectangle.northeast(this._rectangle), this._minimumLevel);
        var tileCount = (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
        if (tileCount > 4) {
            throw new DeveloperError('The imagery provider\'s rectangle and minimumLevel indicate that there are ' + tileCount + ' tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.');
        }

        this._errorEvent = new Event();

        this._ready = true;

        var credit = options.credit;
        if (typeof credit === 'string') {
            credit = new Credit(credit);
        }
        this._credit = credit;
    };

    var defaultParameters = freezeObject({
        service : 'WMTS',
        version : '1.0.0',
        request : 'GetTile'
    });

    function buildImageUrl(imageryProvider, col, row, level) {
        var uri = new Uri(imageryProvider._url);
        var queryOptions = queryToObject(defaultValue(uri.query, ''));
        var labels;

        queryOptions = combine(defaultParameters, queryOptions);

        labels = imageryProvider._tileMatrixLabels;
        queryOptions.tilematrix = (!!labels) ? labels[level] : level;
        queryOptions.layer = imageryProvider._layer;
        queryOptions.style = imageryProvider._style;
        queryOptions.tilerow = row;
        queryOptions.tilecol = col;
        queryOptions.tilematrixset = imageryProvider._tileMatrixSetID;
        queryOptions.format = imageryProvider._format;

        uri.query = objectToQuery(queryOptions);

        var url = uri.toString();

        var proxy = imageryProvider._proxy;
        if (defined(proxy)) {
            url = proxy.getURL(url);
        }

        return url;
    }

    defineProperties(WebMapTileServiceImageryProvider.prototype, {
        /**
         * Gets the URL of the service hosting the imagery.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {String}
         * @readonly
         */
        url : {
            get : function() {
                return this._url;
            }
        },

        /**
         * Gets the proxy used by this provider.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Proxy}
         * @readonly
         */
        proxy : {
            get : function() {
                return this._proxy;
            }
        },

        /**
         * Gets the width of each tile, in pixels. This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        tileWidth : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tileWidth must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tileWidth;
            }
        },

        /**
         * Gets the height of each tile, in pixels.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        tileHeight : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tileHeight must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tileHeight;
            }
        },

        /**
         * Gets the maximum level-of-detail that can be requested.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        maximumLevel : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('maximumLevel must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._maximumLevel;
            }
        },

        /**
         * Gets the minimum level-of-detail that can be requested.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        minimumLevel : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('minimumLevel must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._minimumLevel;
            }
        },

        /**
         * Gets the tiling scheme used by this provider.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {TilingScheme}
         * @readonly
         */
        tilingScheme : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tilingScheme must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tilingScheme;
            }
        },

        /**
         * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Rectangle}
         * @readonly
         */
        rectangle : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('rectangle must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._rectangle;
            }
        },

        /**
         * Gets the tile discard policy.  If not undefined, the discard policy is responsible
         * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
         * returns undefined, no tiles are filtered.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {TileDiscardPolicy}
         * @readonly
         */
        tileDiscardPolicy : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tileDiscardPolicy must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tileDiscardPolicy;
            }
        },

        /**
         * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
         * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
         * are passed an instance of {@link TileProviderError}.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Event}
         * @readonly
         */
        errorEvent : {
            get : function() {
                return this._errorEvent;
            }
        },

        /**
         * Gets the mime type of images returned by this imagery provider.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {String}
         * @readonly
         */
        format : {
            get : function() {
                return this._format;
            }
        },

        /**
         * Gets a value indicating whether or not the provider is ready for use.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Boolean}
         * @readonly
         */
        ready : {
            get : function() {
                return this._ready;
            }
        },

        /**
         * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
         * the source of the imagery.  This function should not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Credit}
         * @readonly
         */
        credit : {
            get : function() {
                return this._credit;
            }
        },

        /**
         * Gets a value indicating whether or not the images provided by this imagery provider
         * include an alpha channel.  If this property is false, an alpha channel, if present, will
         * be ignored.  If this property is true, any images without an alpha channel will be treated
         * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
         * and texture upload time are reduced.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Boolean}
         * @readonly
         */
        hasAlphaChannel : {
            get : function() {
                return true;
            }
        }
    });

    /**
     * Gets the credits to be displayed when a given tile is displayed.
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level;
     * @returns {Credit[]} The credits to be displayed when the tile is displayed.
     *
     * @exception {DeveloperError} getTileCredits must not be called before the imagery provider is ready.
     */
    WebMapTileServiceImageryProvider.prototype.getTileCredits = function(x, y, level) {
        return undefined;
    };

    /**
     * Requests the image for a given tile.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level.
     * @returns {Promise} A promise for the image that will resolve when the image is available, or
     *          undefined if there are too many active requests to the server, and the request
     *          should be retried later.  The resolved image may be either an
     *          Image or a Canvas DOM object.
     *
     * @exception {DeveloperError} requestImage must not be called before the imagery provider is ready.
     */
    WebMapTileServiceImageryProvider.prototype.requestImage = function(x, y, level) {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
            throw new DeveloperError('requestImage must not be called before the imagery provider is ready.');
        }
        //>>includeEnd('debug');

        var url = buildImageUrl(this, x, y, level);
        return ImageryProvider.loadImage(this, url);
    };

    /**
     * Picking features is not currently supported by this imagery provider, so this function simply returns
     * undefined.
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level.
     * @param {Number} longitude The longitude at which to pick features.
     * @param {Number} latitude  The latitude at which to pick features.
     * @return {Promise} A promise for the picked features that will resolve when the asynchronous
     *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
     *                   instances.  The array may be empty if no features are found at the given location.
     *                   It may also be undefined if picking is not supported.
     */
    WebMapTileServiceImageryProvider.prototype.pickFeatures = function() {
        return undefined;
    };

    return WebMapTileServiceImageryProvider;
});
<commit_msg>use defined, not !!<commit_after>/*global define*/
define([
        '../Core/combine',
        '../Core/Credit',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/DeveloperError',
        '../Core/Event',
        '../Core/freezeObject',
        '../Core/objectToQuery',
        '../Core/queryToObject',
        '../Core/Rectangle',
        '../Core/WebMercatorTilingScheme',
        '../ThirdParty/Uri',
        './ImageryProvider'
    ], function(
        combine,
        Credit,
        defaultValue,
        defined,
        defineProperties,
        DeveloperError,
        Event,
        freezeObject,
        objectToQuery,
        queryToObject,
        Rectangle,
        WebMercatorTilingScheme,
        Uri,
        ImageryProvider) {
    "use strict";

    /**
     * Provides tiled imagery served by {@link http://www.opengeospatial.org/standards/wmts|WMTS 1.0.0} compliant servers.
     * This provider supports HTTP KVP-encoded GetTile requests, but does not yet support SOAP and RESTful encoding.
     *
     * @alias WebMapTileServiceImageryProvider
     * @constructor
     *
     * @param {Object} options Object with the following properties:
     * @param {String} options.url The WMTS server url.
     * @param {String} [options.format='image/jpeg'] The MIME type for images to retrieve from the server.
     * @param {String} options.layer The layer name for WMTS requests.
     * @param {String} options.style The style name for WMTS requests.
     * @param {String} options.tileMatrixSetID The identifier of the TileMatrixSet to use for WMTS requests.
     * @param {Array} [options.tileMatrixLabels] A list of identifiers in the TileMatrix to use for WMTS requests, one per TileMatrix level.
     * @param {Number} [options.tileWidth=256] The tile width in pixels.
     * @param {Number} [options.tileHeight=256] The tile height in pixels.
     * @param {TilingScheme} [options.tilingScheme] The tiling scheme corresponding to the organization of the tiles in the TileMatrixSet.
     * @param {Object} [options.proxy] A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL.
     * @param {Rectangle} [options.rectangle=Rectangle.MAX_VALUE] The rectangle covered by the layer.
     * @param {Number} [options.minimumLevel=0] The minimum level-of-detail supported by the imagery provider.
     * @param {Number} [options.maximumLevel=18] The maximum level-of-detail supported by the imagery provider.
     * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
     *
     * @see ArcGisMapServerImageryProvider
     * @see BingMapsImageryProvider
     * @see SingleTileImageryProvider
     * @see TileMapServiceImageryProvider
     * @see WebMapServiceImageryProvider
     *
     * @example
     * // USGS shaded relief tile provider
     * var shadedRelief = new Cesium.WebMapTileServiceImageryProvider({
     *     url : 'http://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS',
     *     layer : 'USGSShadedReliefOnly',
     *     style : 'default',
     *     format : 'image/jpeg',
     *     tileMatrixSetID : 'default028mm',
     *     // tileMatrixLabels : ['default028mm:0', 'default028mm:1', 'default028mm:2' ...],
     *     maximumLevel: 19,
     *     credit : new Cesium.Credit('U. S. Geological Survey')
     * });
     * viewer.scene.imageryLayers.addImageryProvider(shadedRelief);
     */
    var WebMapTileServiceImageryProvider = function WebMapTileServiceImageryProvider(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        if (!defined(options.url)) {
            throw new DeveloperError('options.url is required.');
        }
        if (!defined(options.layer)) {
            throw new DeveloperError('options.layer is required.');
        }
        if (!defined(options.style)) {
            throw new DeveloperError('options.style is required.');
        }
        if (!defined(options.tileMatrixSetID)) {
            throw new DeveloperError('options.tileMatrixSetID is required.');
        }

        this._url = options.url;
        this._layer = options.layer;
        this._style = options.style;
        this._tileMatrixSetID = options.tileMatrixSetID;
        this._tileMatrixLabels = options.tileMatrixLabels;
        this._format = defaultValue(options.format, 'image/jpeg');
        this._proxy = options.proxy;
        this._tileDiscardPolicy = options.tileDiscardPolicy;

        this._tilingScheme = defined(options.tilingScheme) ? options.tilingScheme : new WebMercatorTilingScheme();
        this._tileWidth = defaultValue(options.tileWidth, 256);
        this._tileHeight = defaultValue(options.tileHeight, 256);

        this._minimumLevel = defaultValue(options.minimumLevel, 0);
        this._maximumLevel = defaultValue(options.maximumLevel, 18);

        this._rectangle = defaultValue(options.rectangle, this._tilingScheme.rectangle);

        // Check the number of tiles at the minimum level.  If it's more than four,
        // throw an exception, because starting at the higher minimum
        // level will cause too many tiles to be downloaded and rendered.
        var swTile = this._tilingScheme.positionToTileXY(Rectangle.southwest(this._rectangle), this._minimumLevel);
        var neTile = this._tilingScheme.positionToTileXY(Rectangle.northeast(this._rectangle), this._minimumLevel);
        var tileCount = (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
        if (tileCount > 4) {
            throw new DeveloperError('The imagery provider\'s rectangle and minimumLevel indicate that there are ' + tileCount + ' tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.');
        }

        this._errorEvent = new Event();

        this._ready = true;

        var credit = options.credit;
        if (typeof credit === 'string') {
            credit = new Credit(credit);
        }
        this._credit = credit;
    };

    var defaultParameters = freezeObject({
        service : 'WMTS',
        version : '1.0.0',
        request : 'GetTile'
    });

    function buildImageUrl(imageryProvider, col, row, level) {
        var uri = new Uri(imageryProvider._url);
        var queryOptions = queryToObject(defaultValue(uri.query, ''));
        var labels;

        queryOptions = combine(defaultParameters, queryOptions);

        labels = imageryProvider._tileMatrixLabels;
        queryOptions.tilematrix = defined(labels) ? labels[level] : level;
        queryOptions.layer = imageryProvider._layer;
        queryOptions.style = imageryProvider._style;
        queryOptions.tilerow = row;
        queryOptions.tilecol = col;
        queryOptions.tilematrixset = imageryProvider._tileMatrixSetID;
        queryOptions.format = imageryProvider._format;

        uri.query = objectToQuery(queryOptions);

        var url = uri.toString();

        var proxy = imageryProvider._proxy;
        if (defined(proxy)) {
            url = proxy.getURL(url);
        }

        return url;
    }

    defineProperties(WebMapTileServiceImageryProvider.prototype, {
        /**
         * Gets the URL of the service hosting the imagery.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {String}
         * @readonly
         */
        url : {
            get : function() {
                return this._url;
            }
        },

        /**
         * Gets the proxy used by this provider.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Proxy}
         * @readonly
         */
        proxy : {
            get : function() {
                return this._proxy;
            }
        },

        /**
         * Gets the width of each tile, in pixels. This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        tileWidth : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tileWidth must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tileWidth;
            }
        },

        /**
         * Gets the height of each tile, in pixels.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        tileHeight : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tileHeight must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tileHeight;
            }
        },

        /**
         * Gets the maximum level-of-detail that can be requested.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        maximumLevel : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('maximumLevel must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._maximumLevel;
            }
        },

        /**
         * Gets the minimum level-of-detail that can be requested.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Number}
         * @readonly
         */
        minimumLevel : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('minimumLevel must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._minimumLevel;
            }
        },

        /**
         * Gets the tiling scheme used by this provider.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {TilingScheme}
         * @readonly
         */
        tilingScheme : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tilingScheme must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tilingScheme;
            }
        },

        /**
         * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Rectangle}
         * @readonly
         */
        rectangle : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('rectangle must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._rectangle;
            }
        },

        /**
         * Gets the tile discard policy.  If not undefined, the discard policy is responsible
         * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
         * returns undefined, no tiles are filtered.  This function should
         * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {TileDiscardPolicy}
         * @readonly
         */
        tileDiscardPolicy : {
            get : function() {
                //>>includeStart('debug', pragmas.debug);
                if (!this._ready) {
                    throw new DeveloperError('tileDiscardPolicy must not be called before the imagery provider is ready.');
                }
                //>>includeEnd('debug');

                return this._tileDiscardPolicy;
            }
        },

        /**
         * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
         * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
         * are passed an instance of {@link TileProviderError}.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Event}
         * @readonly
         */
        errorEvent : {
            get : function() {
                return this._errorEvent;
            }
        },

        /**
         * Gets the mime type of images returned by this imagery provider.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {String}
         * @readonly
         */
        format : {
            get : function() {
                return this._format;
            }
        },

        /**
         * Gets a value indicating whether or not the provider is ready for use.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Boolean}
         * @readonly
         */
        ready : {
            get : function() {
                return this._ready;
            }
        },

        /**
         * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
         * the source of the imagery.  This function should not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Credit}
         * @readonly
         */
        credit : {
            get : function() {
                return this._credit;
            }
        },

        /**
         * Gets a value indicating whether or not the images provided by this imagery provider
         * include an alpha channel.  If this property is false, an alpha channel, if present, will
         * be ignored.  If this property is true, any images without an alpha channel will be treated
         * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
         * and texture upload time are reduced.
         * @memberof WebMapTileServiceImageryProvider.prototype
         * @type {Boolean}
         * @readonly
         */
        hasAlphaChannel : {
            get : function() {
                return true;
            }
        }
    });

    /**
     * Gets the credits to be displayed when a given tile is displayed.
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level;
     * @returns {Credit[]} The credits to be displayed when the tile is displayed.
     *
     * @exception {DeveloperError} getTileCredits must not be called before the imagery provider is ready.
     */
    WebMapTileServiceImageryProvider.prototype.getTileCredits = function(x, y, level) {
        return undefined;
    };

    /**
     * Requests the image for a given tile.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level.
     * @returns {Promise} A promise for the image that will resolve when the image is available, or
     *          undefined if there are too many active requests to the server, and the request
     *          should be retried later.  The resolved image may be either an
     *          Image or a Canvas DOM object.
     *
     * @exception {DeveloperError} requestImage must not be called before the imagery provider is ready.
     */
    WebMapTileServiceImageryProvider.prototype.requestImage = function(x, y, level) {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
            throw new DeveloperError('requestImage must not be called before the imagery provider is ready.');
        }
        //>>includeEnd('debug');

        var url = buildImageUrl(this, x, y, level);
        return ImageryProvider.loadImage(this, url);
    };

    /**
     * Picking features is not currently supported by this imagery provider, so this function simply returns
     * undefined.
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level.
     * @param {Number} longitude The longitude at which to pick features.
     * @param {Number} latitude  The latitude at which to pick features.
     * @return {Promise} A promise for the picked features that will resolve when the asynchronous
     *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
     *                   instances.  The array may be empty if no features are found at the given location.
     *                   It may also be undefined if picking is not supported.
     */
    WebMapTileServiceImageryProvider.prototype.pickFeatures = function() {
        return undefined;
    };

    return WebMapTileServiceImageryProvider;
});
<|endoftext|>


<commit_before>(function($) {
	$.fn.miller = function(settings) {
		var settings = $.extend({
					'url': function(id) { return id; },
					'tabindex': 0,
					'minWidth': 40,
					'panel': {
						'width': 100,
						'options': {}
					}
				},
				settings
			)
		;

		var hasFocus = false;

		this
			.addClass('miller')
			.attr('tabindex', settings.tabindex)
			.focus(function() { hasFocus = true; })
			.blur(function() { hasFocus = false; })
		;

		var path = $('<div>', { class: 'path' })
			.appendTo(this)
		;

		var columns = $('<div>', { class: 'columns' })
			.appendTo(this)
		;

		var currentLine = null;

		$(document).on('keydown', function(event) {
				if (hasFocus && currentLine && (event.which == 37 || event.which == 38 || event.which == 39 || event.which == 40)) {
					var newCurrentLine = [];

					switch (event.which) {
						case 37:
							newCurrentLine = currentLine.parent().prev().prev().find('li.parentSelected');
							break;

						case 38:
							newCurrentLine = currentLine.prev();
							break;

						case 39:
							newCurrentLine = currentLine.parent().next().next().find('li:first');
							break;

						case 40:
							newCurrentLine = currentLine.next();
							break;
					}

					if (newCurrentLine.length) {
						currentLine = newCurrentLine.click();
						currentLine.parent().scrollTop(currentLine.position().top);
					}

					return false;
				}
			}
		);

		var removeNextColumns = function() {
				var line = $(this);

				var column = line.parent();

				column
					.nextAll()
						.slice(1)
							.remove()
				;

				column
					.find('li')
						.removeClass('selected parentSelected')
				;

				line.addClass(line.hasClass('parent') ? 'parentSelected' : 'selected');

				var columnIndex = column.index();

				columnIndex -= (columnIndex - (columnIndex / 2));

				path
					.append($('<span>', { text: line.text(), css: { cursor: 'pointer' } })
						.on('click', function() {
								columns
									.children()
										.slice((($(this).index() * 2) + 4))
											.remove()
								;
								columns
									.children('ul:last')
										.find('li')
											.removeClass('parentSelected')
								;
								path
									.children()
										.slice($(this).index() + 1)
											.remove()
								;
							}
						)
					)
					.children()
						.slice(columnIndex, -1)
							.remove()
				;

			}
		;

		var buildColumn = function(lines) {
				if (lines == null) {
					$('li.parentLoading').remove();
				} else {
					var width = 0;

					var lastGrip = columns.children('div.grip:last')[0];

					if (lastGrip) {
						lastGrip = $(lastGrip);
						width = lastGrip.position().left + lastGrip.width();
					}

					if (lines.length <= 0) {
						var line = $('li.parentLoading')
							.removeClass('parent')
							.addClass('selected')
						;

						var panel = $('<ul>')
							.css({ 'top': 0, 'left': width })
							.addClass('panel')
						;

						var id = line.data('id');

						$.each(settings['panel']['options'], function(key, callbackGenerator) {
								var option = $('<li>', { text: key })
									.on('click', callbackGenerator(id))
								;

								option.appendTo(panel);
							}
						);

						columns
							.append(panel)
							.scrollLeft(width + panel.width())
						;
					} else {
						$('li.parentLoading').addClass('parentSelected');

						var column = $('<ul>')
							.css({ 'top': 0, 'left': width })
						;

						$.each(lines, function(id, data) {
								var line = $('<li>', { text: data['name'], css: { cursor: 'pointer' } })
									.data('id', data['id'])
									.on('click', removeNextColumns)
									.on('click', getLines)
									.appendTo(column)
								;

								if (data['parent']) {
									line.addClass('parent');
								}
							}
						);

						columns
							.append(column)
							.scrollLeft(width += column.width())
							.append(
								$('<div>', { class: 'grip' })
									.css({ 'top': 0, 'left': width })
									.mousedown(function(event) {
											var x = event.pageX;
											var cursor = columns.css('cursor');

											columns
												.css('cursor', 'col-resize')
												.mousemove(function(event) {
														var delta = event.pageX - x;
														var newWidth = column.width() + delta;

														if (newWidth > settings['minWidth']) {
															column
																.width(newWidth)
																.nextAll()
																	.each(function() {
																			$(this).css('left', $(this).position().left + delta + columns.scrollLeft());
																		}
																	)
															;
														}

														x = event.pageX;
													}
												)
												.mouseup(function() {
														columns
															.off('mousemove')
															.css('cursor', cursor)
														;
													}
												)
											;
										}
									)
							)
						;
					}
				}
			}
		;

		var getLines = function(event) {
				currentLine = $(event.currentTarget)
					.removeClass('parentSelected')
					.addClass('parentLoading')
				;

				$.getJSON(settings['url']($(this).data('id')), buildColumn)
					.always(function() {
							currentLine
								.removeClass('parentLoading')
							;
						}
					)
					.fail(function() {})
				;

			}
		;

		$.getJSON(settings['url'](), buildColumn);

		return this;
	};
})(jQuery);
<commit_msg>Remove bug when there is horizontal scroll.<commit_after>(function($) {
	$.fn.miller = function(settings) {
		var settings = $.extend({
					'url': function(id) { return id; },
					'tabindex': 0,
					'minWidth': 40,
					'panel': {
						'width': 100,
						'options': {}
					}
				},
				settings
			)
		;

		var hasFocus = false;

		this
			.addClass('miller')
			.attr('tabindex', settings.tabindex)
			.focus(function() { hasFocus = true; })
			.blur(function() { hasFocus = false; })
		;

		var path = $('<div>', { class: 'path' })
			.appendTo(this)
		;

		var columns = $('<div>', { class: 'columns' })
			.appendTo(this)
		;

		var currentLine = null;

		$(document).on('keydown', function(event) {
				if (hasFocus && currentLine && (event.which == 37 || event.which == 38 || event.which == 39 || event.which == 40)) {
					var newCurrentLine = [];

					switch (event.which) {
						case 37:
							newCurrentLine = currentLine.parent().prev().prev().find('li.parentSelected');
							break;

						case 38:
							newCurrentLine = currentLine.prev();
							break;

						case 39:
							newCurrentLine = currentLine.parent().next().next().find('li:first');
							break;

						case 40:
							newCurrentLine = currentLine.next();
							break;
					}

					if (newCurrentLine.length) {
						currentLine = newCurrentLine.click();
						currentLine.parent().scrollTop(currentLine.position().top);
					}

					return false;
				}
			}
		);

		var removeNextColumns = function() {
				var line = $(this);

				var column = line.parent();

				column
					.nextAll()
						.slice(1)
							.remove()
				;

				column
					.find('li')
						.removeClass('selected parentSelected')
				;

				line.addClass(line.hasClass('parent') ? 'parentSelected' : 'selected');

				var columnIndex = column.index();

				columnIndex -= (columnIndex - (columnIndex / 2));

				path
					.append($('<span>', { text: line.text(), css: { cursor: 'pointer' } })
						.on('click', function() {
								columns
									.children()
										.slice((($(this).index() * 2) + 4))
											.remove()
								;
								columns
									.children('ul:last')
										.find('li')
											.removeClass('parentSelected')
								;
								path
									.children()
										.slice($(this).index() + 1)
											.remove()
								;
							}
						)
					)
					.children()
						.slice(columnIndex, -1)
							.remove()
				;

			}
		;

		var buildColumn = function(lines) {
				if (lines == null) {
					$('li.parentLoading').remove();
				} else {
					var width = 0;

					var lastGrip = columns.children('div.grip:last')[0];

					if (lastGrip) {
						lastGrip = $(lastGrip);
						width = lastGrip.position().left + lastGrip.width() + columns.scrollLeft();
					}

					if (lines.length <= 0) {
						var line = $('li.parentLoading')
							.removeClass('parent')
							.addClass('selected')
						;

						var panel = $('<ul>')
							.css({ 'top': 0, 'left': width })
							.addClass('panel')
						;

						var id = line.data('id');

						$.each(settings['panel']['options'], function(key, callbackGenerator) {
								var option = $('<li>', { text: key })
									.on('click', callbackGenerator(id))
								;

								option.appendTo(panel);
							}
						);

						columns
							.append(panel)
							.scrollLeft(width + panel.width())
						;
					} else {
						$('li.parentLoading').addClass('parentSelected');

						var column = $('<ul>')
							.css({ 'top': 0, 'left': width })
						;

						$.each(lines, function(id, data) {
								var line = $('<li>', { text: data['name'], css: { cursor: 'pointer' } })
									.data('id', data['id'])
									.on('click', removeNextColumns)
									.on('click', getLines)
									.appendTo(column)
								;

								if (data['parent']) {
									line.addClass('parent');
								}
							}
						);

						columns
							.append(column)
							.scrollLeft(width += column.width())
							.append(
								$('<div>', { class: 'grip' })
									.css({ 'top': 0, 'left': width })
									.mousedown(function(event) {
											var x = event.pageX;
											var cursor = columns.css('cursor');

											columns
												.css('cursor', 'col-resize')
												.mousemove(function(event) {
														var delta = event.pageX - x;
														var newWidth = column.width() + delta;

														if (newWidth > settings['minWidth']) {
															column
																.width(newWidth)
																.nextAll()
																	.each(function() {
																			$(this).css('left', $(this).position().left + delta + columns.scrollLeft());
																		}
																	)
															;
														}

														x = event.pageX;
													}
												)
												.mouseup(function() {
														columns
															.off('mousemove')
															.css('cursor', cursor)
														;
													}
												)
											;
										}
									)
							)
						;
					}
				}
			}
		;

		var getLines = function(event) {
				currentLine = $(event.currentTarget)
					.removeClass('parentSelected')
					.addClass('parentLoading')
				;

				$.getJSON(settings['url']($(this).data('id')), buildColumn)
					.always(function() {
							currentLine
								.removeClass('parentLoading')
							;
						}
					)
					.fail(function() {})
				;

			}
		;

		$.getJSON(settings['url'](), buildColumn);

		return this;
	};
})(jQuery);
<|endoftext|>