// no need for any DOMLOADED event like jQuery's $(document).ready(...)
// just include your scripts at the very end of any page, which is
// best practise for performance anyway.

// see http://technology.razorfish.com/2010/02/08/detecting-css-transitions-support-using-javascript/
var cssTransitionsSupported = false;
(function() {
    var div = document.createElement('div');
    div.innerHTML = '<div style="-webkit-transition:color 1s linear;-moz-transition:color 1s linear;"></div>';
    cssTransitionsSupported = (div.firstChild.style.webkitTransition !== undefined) || (div.firstChild.style.MozTransition !== undefined);
    delete div;
})();
if (cssTransitionsSupported) 
{
  $('body').addClass('transitions')
}

Canvas = {
  costs: $('#costs-value'),
  co2: $('#co2-value'),
  kwh: $('#kwh-value')
}
Footer     = $("#footer")
PrevButton = $("#choice-wrapper a.prev.arrow")
NextButton = $("#choice-wrapper a.next.arrow")
choices_url = 'choices_data.json'

function ChooserClass(str_container, choices_url) {
  var klass,
      Container,
      Choices,
      choices_data,
      cell_width,
      num_choices,
      current,
      current_costs,
      current_co2,
      current_kwh,
      last_data = false
  
  init = function(str_container, choices_url) {
    Container   = $(str_container)
    
    Container.dblclick(function(e) {
      // get the td, return if clicked outside
      Cell = $(e.target)
      if (Cell.is(':not(td)')) Cell = Cell.parents('td')
      if(! Cell) return
      
      goto(Cell.attr('data-nr'))
      
      return false
    })
    Container.draggable({ 
      axis: 'x',
      drag: function(event, ui) {
        // Stop animations
        Container.stop()
        var num = Math.round(left_pos() / cell_width * -1)
        
        // set canvas to current action below the arrow
        setCurrent(num+1)
      },
      stop: function(event, ui) {
        var num = Math.round(left_pos() / cell_width * -1)
        // when dragging is done, center closest action below the arrow
        goto(num + 1)
      }
    })
    
    $.getJSON(choices_url, function(data) {
      build(data)
    });
  }
  
  build = function(data) {
    var cells_html = ''
    
    choices_data = data
    num_choices = choices_data.length
    for(var i = 0; i < num_choices; i++) 
    {
      cells_html += '<td data-nr="'+(i+1)+'"><strong>'+choices_data[i].action+'</strong></td>'
    }
    $('table tr',Container).html(cells_html)
    
    cell_width  = $('td:first-child', Container).outerWidth()
    Choices     = $('td', Container)
    current     = 1
    last_data   = CurrentData()
    
    // slide in
    gotoCurrent()
    // Container.animate({ left: 0 }, 1000, function(){ gotoCurrent() })
    // 
  }
  
  gotoCurrent = function() {
    // get the current and the target position and calculate a factor to adjust the animation time 
    var distance_factor = Math.abs(( (current - 1) * cell_width * -1 - left_pos() ) / cell_width)
    if (distance_factor == 0) distance_factor = 1
    
    Container.stop().animate(
      {
        left: (current - 1) * cell_width * -1
      },
      {
        duration:  800 * distance_factor,
        step: function() {
          
          last_data = {
            costs: last_data.costs + (CurrentData().costs - last_data.costs) / 3,
            co2:   last_data.co2   + (CurrentData().co2  - last_data.co2)   / 3,
            kwh:   last_data.kwh   + (CurrentData().kwh  - last_data.kwh)   / 3
          }
          
          setCurrentNum(last_data)
        },
        complete: function() {
          last_data = CurrentData()
          setCurrentNum(CurrentData())
        }
      }
    )
    setCurrent(current)
    
    // deselect text
    if (window.getSelection) window.getSelection().removeAllRanges();
    else if (document.selection) document.selection.empty();
  }
  CurrentCell = function() {
    return $(Choices[current - 1])
  }
  CurrentData = function() {
    var data = choices_data[current - 1]
    return {
      costs: parseFloat(data.costs),
      co2:   parseFloat(data.co2),
      kwh:   parseFloat(data.kwh)
    }
  }
  setCurrent = function(num) {
    if (num < 1) num = 1
    if (num > num_choices) num = num_choices
    current = num
    CurrentCell().addClass('current').siblings().removeClass('current')
  }
  setCurrentNum = function(data) {
    current_costs = Math.round(data.costs)
    current_co2   = Math.round(data.co2)
    current_kwh   = Math.round(data.kwh)
    
    
    Canvas.costs.text(addDelimiter(current_costs))
    Canvas.co2.text(addDelimiter(current_co2))
    Canvas.kwh.text(addDelimiter(current_kwh))
  }
  goto = function(num) {
    if (num < 1) num = 1
    if (num > num_choices) num = num_choices
    
    current = num
    gotoCurrent()
  }
  left_pos = function() {
    return Container.css('left').replace(/px$/, '') * 1
  }
  goToPrev = function() {
    if (current <= 1) return
    current--
    gotoCurrent()
  }
  goToNext = function() {
    if (current >= num_choices) return
    
    current++
    gotoCurrent()
  }
  addDelimiter = function(num) {
    num = '' + num // make it a string
    while (num.match(/^\d\d{3}/)){
      num = num.replace(/(\d)(\d{3}(\.|$))/, '$1.$2');
    }
    return num;
  }
  this.prev = function() {
    goToPrev()
  },
  this.next = function() {
    goToNext()
  }
  
  init(str_container, choices_url)
}

Chooser = new ChooserClass("#choice", choices_url)

PrevButton.click(function() {
  Chooser.prev()
  return false
})
NextButton.click(function() {
  Chooser.next()
  return false
})

