$(function() {
    $('.title').data("loading", false);
    $('.title').click(function() {
        var $this = $(this);
        if ($(this).data("loading")) {
            return;
        }
        $(this).data("loading", true);
        var $parent = $(this).parent();

        if ($parent.find('.srtContainer').length > 0) {
            $parent.find('.srtContainer').slideToggle();
            return;
        }

        var name = $parent.attr("data-name");

        var srtFilename = "srt/" + name + ".srt";
        var audioFilename = "wav/" + name + ".wav";
        $.get(srtFilename, {}, function(srt) {
            $this.data("loading", false);
            var txt = srtToTxt(srt, 'tc');
            var $txtContainer = $('<div />').addClass("srtContainer").data("srt", srt).hide()        
            var $audio = $('<audio />').attr("src", audioFilename).attr("controls", "controls").appendTo($txtContainer);
            var $btnsContainer = $('<div />').addClass("btnsContainer").appendTo($txtContainer);
            var $padmaBtn = $('<button />').addClass("padmaBtn").text("View on pad.ma").appendTo($btnsContainer);
            var $srtBtn = $('<button />').addClass("srtBtn").text("View SRT").data("fmt", "srt").appendTo($btnsContainer);
            var $tcBtn = $('<button />').addClass("srtBtn").text("View Time-coded Text").data("fmt", "tc").appendTo($btnsContainer);
            var $txtBtn = $('<button />').addClass("srtBtn").text("View Plain Text").data("fmt", "txt").appendTo($btnsContainer);
            var $srt = $('<div />').addClass('srt').html(txt.replace(/\n/g, "<br />")).appendTo($txtContainer);
            $txtContainer.appendTo($parent).slideDown();
        });
    });

});

$('.padmaBtn').live("click", function() {
    var padmaId = $(this).parents(".container").attr("data-padma");
    window.open("http://powertapes.pad.ma/" + padmaId);
});

$('.srtBtn').live("click", function() {
    var fmt = $(this).data("fmt");
    var srt = $(this).parents(".srtContainer").data("srt");
    var txt = srtToTxt(srt, fmt);
    txt = txt.replace(/\n/g, "<br />");
    $(this).parents(".srtContainer").find(".srt").html(txt);
});

var srtToTxt = function(txt, fmt) {
  if (fmt == 'srt') return txt;
  var that = this;
  var spans = [];  
  var cleaned = cleanNewlines(txt);
  var srt = strip(cleaned);
  var srt_ = srt.split('\n\n');
  var s;

  for(s in srt_) {
    st = srt_[s].split('\n');
    if(st.length >=2) {
      var n = st[0];
      var i = strip(st[1].split(' --> ')[0]);
      var o = strip(st[1].split(' --> ')[1]);
      var t = st[2];
      if(st.length > 2) {
        for(j=3; j<st.length;j++) {
          t += '\n'+st[j];
          }
        }
        var is = toSeconds(i);
        var os = toSeconds(o);
        
        spans[spans.length] = new Span(is, os, t, spans.length);

     }
  }
  var out = '';
//  var spans = this.spans;
  for (span in spans) {
    if (spans.hasOwnProperty(span)) {
        var sp = spans[span];
//      out += spanToTxt(sp, fmt);
        if (fmt === 'tc') {      
            out += ms2npt(sp.tcInMs) + "\n";
            out += sp.text;
            out += "\n";
    //If the outpoint of current span is equal to inpoint of next span, dont print out timecode, and just add the extra \n to go to next span.
            if (span < spans.length - 1) {
                var p = parseInt(span) + 1;
                if (spans[p].tcInMs != sp.tcOutMs) {
                    out += ms2npt(sp.tcOutMs) + "\n\n";
                } else {
                  out += "\n";
                }
            }
        } else if (fmt == 'txt') {
            out += sp.text;
            out += "\n\n";
        }
    }
  }
  return out;
};

/*
function spansToTxt(span, fmt) {
    var text = span.text;
    var tcOutMs = span.tcOutMs;
    var tcInMs = span.tcInMs;
    switch (fmt) {
        case 'txt':
            return text;

        case 'tc':
            
    }
}
*/

//creates new Span (tcIn and tcOut in npt format)
var Span = function(tcIn, tcOut, text, index) {
  this.index = index;
  this.tcOutMs = npt2ms(tcOut);
  this.text = text;
  this.tcInMs = npt2ms(tcIn);
  }


function cleanNewlines(str) {
  var s = str.replace(/\r\n|\r|\n/g, '\n');
  return s;
  }

function strip(s) {
  return s.replace(/^\s+|\s+$/g,"");
  }

function toSeconds(t) {
  var s = 0.0;
  if(t) {
    var p = t.split(':');
    for(i=0;i<p.length;i++) {
      s = s * 60 + parseFloat(p[i].replace(',', '.'))
      }
    }
  return s;
  }

function ms2npt(ms) {
  var it, ss, mm, hh, npt;
  var it = parseInt(ms / 1000)
  ms = ms - it * 1000;
  if (ms.toString().length > 3) {
    ms = ms.toString().substring(0,3);
    }
  ss = it % 60;
  mm = ((it - ss) / 60) % 60;
  hh = ((it - (mm * 60) - ss) / 3600) % 60;
  npt = hh+':'+strpad(mm.toString(), '0', 2, 'left')
  npt += ':'+strpad(ss.toString(), '0', 2, 'left')
  npt += '.'+strpad(ms.toString(), '0', 3, 'left')
  return npt;
}

function npt2ms(npt) {
  var ms = 0.0
  npt = String(npt);
  var p = npt.split(':')
  for(i=0;i<p.length;i++)
    ms = ms * 60 + parseFloat(p[i])
  return ms * 1000;
}

function strpad(str, pad, len, dir) {
      while (str.length < len) {
      if (dir == 'left')
        str = pad + str;
      else if (dir == 'right')
        str = str + pad;
      }
      return str;
    }

