var projects;
var tags;

$().ready(function(){
  if($('input:password').length > 0){
    $('input:password').dPassword();
  }
  
  $('#log_expander').click(function(){
    $(this).toggleClass('opened')
    $('#log_expander_container').toggle()
    
    $('#log_expander_container:hidden input').val('')
    
  })
	
  if(!projects){
    projects = [];
  }
  if(!tags){
    tags = [];
  }
  
  $('#log_project').autocomplete(projects);
  $('#log_tags').autocomplete(tags, {multiple:true, multipleSeparator:" "});
  
  $('#log_form').submit(function(){
    var submitButton  = $('input[type=submit]', $(this))
    
    submitButton.attr('disabled', true).attr('value', "Please wait..")
    
    var name_project = $("input[name=log[project_name]]", $(this)).val()
    var name_tags = $("input[name=log[tags]]", $(this)).val().split(' ')
    
    var url = $(this).attr('action')
    var args = $(this).serializeArray();
    
    $.post(url, args, function(data){
      if(data == ""){
        $('#messages .error').html("Oops, please fill in whole form").simpleAlerter(5000)
      }else{
        projects = _.uniq(projects.concat([name_project]))
        tags = _.uniq(tags.concat(name_tags))

        $('#log_project').autocomplete(projects);
        $('#log_tags').autocomplete(tags, {multiple:true, multipleSeparator:" "});
        
        $('#log_time, #log_project, #log_tags, #log_for').val("");
        
        $('#messages .success').html("Time was logged, cool!").simpleAlerter(5000)
        
        var content = $(data);

        content.prependTo('#logs')//.effect('highlight', 3000, {})
      }
      
      submitButton.attr('disabled', false).attr('value', 'Log')
    });

    return false;
  })
  
  if(!Modernizr.input.placeholder){
    $('input[placeholder]').placeholder();
  }
  
  $('.custom_date')
    .datepicker({
      dateFormat: 'M dd, yy',
      showButtonPanel: true,
      maxDate: "+0d",
      onSelect: function(selectedDate) {
        var option = this.id == "from" ? "minDate" : "maxDate";
        
        var instance = $(this).data("datepicker");
        
        var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
        $('.custom_date').not(this).datepicker("option", option, date);
        
        $(this).trigger('change')
        
      }
    })
    .live('change', function(){
      if($(this).val() == ""){
        $(this).removeClass('no_bg')
      }else{
        $(this).addClass('no_bg')
      }
    })
    .each(function(i, item){$(item).trigger('change')})
})

function minutesToTimestring(minutes){
  var hours = Math.floor(minutes / 60);
  var minutes = minutes % 60;
  
  var timestring = "";
  
  if(hours == 1){
    timestring += hours +" hour "
  }else if(hours > 1){
    timestring += hours +" hours "
  }
  
  if( (minutes % 10) == 1){
    timestring += minutes+" minute"
  }else if(minutes > 0){
    timestring += minutes+" minutes"
  }
  
  return timestring;
}

function minutesToHHMM(minutes){
  var hours = Math.floor(minutes / 60);
  var minutes = minutes % 60;
  
  var timestring = "";
  
  if( minutes < 10){
    minutes = '0'+minutes;
  }
  
  return hours+":"+minutes;
}

function highcarts_pie1(dom_id, title, data){
  if(data.length == 0){
    $('#'+dom_id).html('<br><br><br><br>No data for '+title).addClass('noDataContainer')
    return;
  }
    
  $(document).ready(function() {
    var chart = new Highcharts.Chart({
      chart: {
        renderTo: dom_id, 
        defaultSeriesType: 'pie'
      },
      plotOptions: {
        pie: {
          dataLabels: {
            enabled: true,
            formatter: function() {
              if (this.y > 5) return this.point.name;
            },
            color: 'white',
            style: {
              font: '13px Trebuchet MS, Verdana, sans-serif'
            }
          }
        }
      },
      legend: {
        enabled: false
      },
      title: {
        text: title
      },
      subtitle: {
        text: ''
      },
      tooltip: {
        formatter: function(){
          var hours = Math.floor(this.y / 60);
          var minutes = this.y % 60;
          
          var timestring = "";
          
          if(hours == 1){
            timestring += hours +" hour "
          }else if(hours > 1){
            timestring += hours +" hours "
          }
          
          if( (minutes % 10) == 1){
            timestring += minutes+" minute"
          }else if(minutes > 0){
            timestring += minutes+" minutes"
          }

          if(this.point.name == "No data"){
            timestring = "n/a";
          }
          
          return "<b>"+this.point.name+"</b><br>"+timestring;
        }
      },
      series: [{
        data: data
      }]
    });


  });
}

function highcharts_bar1(dom_id, title, data){
  if(data["values"].length == 0){
    $('#'+dom_id).html('<br><br><br><br>No data for '+title).addClass('noDataContainer')
    return;
  }
  
  $(document).ready(function(){
    var chart = new Highcharts.Chart({
       chart: {
          renderTo: dom_id,
          defaultSeriesType: 'column',
          margin: [ 50, 50, 100, 80]
       },
       title: {
          text: title
       },
       xAxis: {
          categories: data["names"],
          labels: {
             rotation: -45,
             align: 'right',
             style: {
                 font: 'normal 13px Verdana, sans-serif'
             }
          }
       },
       yAxis: {
          min: 0,
          labels:{
            formatter: function(){
              return minutesToHHMM(this.value)
            }
          },
          title: {
             text: ''
          }
       },
       legend: {
          enabled: false
       },
       tooltip: {
          formatter: function() {
             return '<b>'+ this.x +'</b><br/>'+ minutesToTimestring(this.y);
          }
       },
      series: [{
          data: data["values"]     
       }]
    });
  })
}

function highcarts_line1(dom_id, title, data, categories){
  var show = false;
  
  $.each(data, function(i, item){
    $.each(item["data"], function(i2, item2){
      if(item2 > 0){
        show = true;
        return false;
      }
    })
    
    if(show){
      return false
    }else{
      return true
    }
  })
  
  if(!show){
    $('#'+dom_id).html('<br><br><br><br>No data for '+title).addClass('noDataContainer')
    return;
  }
  
  var original_categories = _.clone(categories);
  if(categories.length > 10){
    var ratio = Math.ceil(categories.length / 10)
    
    var categories = $.map(categories, function(item, i){
      if( (i) % ratio != 0 ){
        return " ";
      }else{
        return item;
      }
    })
  }
  
  $(document).ready(function() {
    var chart = new Highcharts.Chart({
       chart: {
          renderTo: dom_id,
          defaultSeriesType: 'line',
          margin: [50, 150, 60, 80]
       },
       title: {
          text: title,
          style: {
             margin: '10px 100px 0 0' // center it
          }
       },
       xAxis: {
          categories: categories,
          title: {
             text: ''
          }
       },
       yAxis: {
          title: {
             text: ''
          },
          min:0,
          labels:{
            formatter: function(){
              return minutesToHHMM(this.value)
            }
          },
          plotLines: [{
             value: 0,
             width: 1,
             color: '#808080'
          }]
       },
       tooltip: {
         formatter: function(){
           
           var hours = Math.floor(this.y / 60);
           var minutes = this.y % 60;

           var timestring = "";

           if(hours == 1){
             timestring += hours +" hour "
           }else if(hours > 1){
             timestring += hours +" hours "
           }

           if( (minutes % 10) == 1){
             timestring += minutes+" minute"
           }else if(minutes > 0){
             timestring += minutes+" minutes"
           }
           
           if(timestring == ""){
             timestring = "No data"
           }

           return "<b>"+this.series.name+" @ "+original_categories[this.point.x]+"</b><br>"+timestring;
         }
       },
       legend: {
          layout: 'vertical',
          style: {
             left: 'auto',
             bottom: 'auto',
             right: '10px',
             top: '100px'
          }
       },
       series: data
    });
  });
}