var Slider = function ($element, options) {
  if (!$element || $element.length == 0) return null;

  var id = $element.attr('id');
  options.value = $element.val();

  $element.before('<div id="' + id + '-control" class="slider"></div>' +
                  '<div id="' + id + '-callout" class="slider-callout"><div>');

  var set_value = function (value) {
    $element.val(value).prev().html(value + ' ' + $element.attr('title'));
  };

  set_value(options.value);

  options.slide = function (e, ui) {
    set_value(ui.value);
  };

  $element.prev().prev().slider(options);
};

var ITM = function ($element) {
  if (!$element || $element.length == 0) return null;

  var calculate = function () {
    var weight = $('#slider-weight').val();
    var height = $('#slider-height').val() / 100;
    var itm = Math.round(weight / Math.pow(height, 2));
    $element.find('.itm-value').html(itm);
  };
  $('#slider-weight-control').bind('slide', calculate);
  $('#slider-height-control').bind('slide', calculate);
  calculate();
}

$(document).ready(function () {
	$('.trigger').click(function() {
		$('.popup').fadeIn("normal", function(){
			$(".slider").remove();
			$(".slider-callout").remove();
			new Slider($('#slider-weight'), { max: 130, min: 1 });
			new Slider($('#slider-height'), { max: 250, min: 1 });
			new ITM ($('#itm'));
		});
	});
	$('.close').click(function() {
		$('.popup').fadeOut("normal");
	});
});
