/* 
 * SPYGLASS DRAWS CIRCLE TO VIEW HIDDEN LAYER. 
 */

// get the pixel position with every move
var mousePosition = null;
map.on('pointermove', function (event) {
  mousePosition = event.pixel;
  map.render();
});

var chosen;
//console.log("chosen je na zacatku: " + chosen);
function onRadioChange(event) {
  if (chosen) {
    chosen.un('precompose', onPreCompose);
    chosen.un('postcompose', onPostCompose);
    chosen.setVisible(false);
  }
  //console.log("VYPISUJI clipped u chosen: " + clipped[event.target.value]);
  chosen = clipped[event.target.value];
  if (chosen === undefined || chosen === 'undefined') {
    return;
  }
  chosen.on('precompose', onPreCompose);
  chosen.on('postcompose', onPostCompose);
  chosen.setVisible(true);
}

// before rendering the layer, do some clipping
function onPreCompose(event) {
  var ctx = event.context;
  var pixelRatio = event.frameState.pixelRatio;
  ctx.save();
  ctx.beginPath();
  if (mousePosition) {
    // only show a circle around the mouse
    ctx.arc(mousePosition[0] * pixelRatio, mousePosition[1] * pixelRatio,
            radius * pixelRatio, 0, 2 * Math.PI);
    ctx.lineWidth = 10 * pixelRatio;
    ctx.strokeStyle = 'rgba(0,175,211,0.5)';
    ctx.stroke();
  }
  ;
  ctx.clip();
}

// after rendering the layer, restore the canvas context
function onPostCompose(event) {
  var ctx = event.context;
  ctx.restore();
}

var inputs = document.querySelectorAll('input[type="radio"]');
for (var i = 0, ii = inputs.length; i < ii; ++i) {
  inputs[i].addEventListener('change', onRadioChange);
}
onRadioChange({target: document.querySelector('input[type="radio"]:checked')});

var radius = 150;
$(document).keydown(function (evt) {
  if (evt.which === 38) {
    radius = Math.min(radius + 5, 500);
    map.render();
  } else if (evt.which === 40) {
    radius = Math.max(radius - 5, 25);
    map.render();
  }
});