/*

  SoundManager 2 Demo: Play MP3 links "in-place"
  ----------------------------------------------

  http://schillmania.com/projects/soundmanager2/

  A simple demo making MP3s playable "inline"
  and easily styled/customizable via CSS.

  Requires SoundManager 2 Javascript API.

*/
var snd_inst;

function InlinePlayer() {
  var self = this;
  var pl = this;
  var sm = soundManager; // soundManager instance
  this.excludeClass = 'inline-exclude'; // CSS class for ignoring MP3 links
  this.links = [];
  this.sounds = [];
  this.soundsByURL = [];
  this.indexByURL = [];
  this.lastSound = null;
  this.soundCount = 0;
  var isIE = (navigator.userAgent.match(/msie/i));

  this.config = {
    playNext: false, // stop after one sound, or play through list until end
	autoPlay: false  // start playing the first sound right away
  }

  this.css = {
    // CSS class names appended to link during various states
    sDefault: 'sm2_link', // default state
    sLoading: 'sm2_loading',
    sPlaying: 'sm2_playing',
    sPaused: 'sm2_paused'
  }

  this.addEventHandler = function(o,evtName,evtHandler) {
    typeof(attachEvent)=='undefined'?o.addEventListener(evtName,evtHandler,false):o.attachEvent('on'+evtName,evtHandler);
  }

  this.removeEventHandler = function(o,evtName,evtHandler) {
    typeof(attachEvent)=='undefined'?o.removeEventListener(evtName,evtHandler,false):o.detachEvent('on'+evtName,evtHandler);
  }

  this.classContains = function(o,cStr) {
	return (typeof(o.className)!='undefined'?o.className.match(new RegExp('(\\s|^)'+cStr+'(\\s|$)')):false);
  }

  this.addClass = function(o,cStr) {
    if (!o || !cStr || self.classContains(o,cStr)) return false;
    o.className = (o.className?o.className+' ':'')+cStr;
  }

  this.removeClass = function(o,cStr) {
    if (!o || !cStr || !self.classContains(o,cStr)) return false;
    o.className = o.className.replace(new RegExp('( '+cStr+')|('+cStr+')','g'),'');
  }

  this.getSoundByURL = function(sURL) {
    return (typeof self.soundsByURL[sURL] != 'undefined'?self.soundsByURL[sURL]:null);
  }

  this.isChildOfNode = function(o,sNodeName) {
    if (!o || !o.parentNode) {
      return false;
    }
    sNodeName = sNodeName.toLowerCase();
    do {
      o = o.parentNode;
    } while (o && o.parentNode && o.nodeName.toLowerCase() != sNodeName);
    return (o.nodeName.toLowerCase() == sNodeName?o:null);
  }

  this.events = {

    // handlers for sound events as they're started/stopped/played

    play: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = pl.css.sPlaying;
      pl.addClass(this._data.oLink,this._data.className);
    },

    stop: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = '';
    },

    pause: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = pl.css.sPaused;
      pl.addClass(this._data.oLink,this._data.className);
    },

    resume: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = pl.css.sPlaying;
      pl.addClass(this._data.oLink,this._data.className);      
    },

    finish: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = '';
      if (pl.config.playNext) {
        var nextLink = (pl.indexByURL[this._data.oLink.href]+1);
        if (nextLink<pl.links.length) {
          pl.handleClick({'target':pl.links[nextLink]});
        }
      }
    }

  }

  this.stopEvent = function(e) {
   if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
      e.preventDefault();
    } else if (typeof event != 'undefined' && typeof event.returnValue != 'undefined') {
      event.returnValue = false;
    }
    return false;
  }

  this.getTheDamnLink = (isIE)?function(e) {
    // I really didn't want to have to do this.
    return (e && e.target?e.target:window.event.srcElement);
  }:function(e) {
    return e.target;
  }

  this.handleClick = function(e) {
    // a sound link was clicked
    if (typeof e.button != 'undefined' && e.button>1) {
	  // ignore right-click
	  return true;
    }
    var o = self.getTheDamnLink(e);
    if (o.nodeName.toLowerCase() != 'a') {
      o = self.isChildOfNode(o,'a');
      if (!o) return true;
    }
    var sURL = o.getAttribute('href');
    if (!o.href || !o.href.match(/\.mp3(\\?.*)$/i) || self.classContains(o,self.excludeClass)) {
      if (isIE && o.onclick) {
        return false; // IE will run this handler before .onclick(), everyone else is cool?
      }
      return true; // pass-thru for non-MP3/non-links
    }
    sm._writeDebug('handleClick()');
    var soundURL = (o.href);
    snd_inst = self.getSoundByURL(soundURL);
    if (snd_inst) {
      // already exists
      if (snd_inst == self.lastSound) {
        // and was playing (or paused)
        snd_inst.togglePause();
      } else {
        // different sound
        get_the_lrc(soundURL);
        snd_inst.togglePause(); // start playing current
        sm._writeDebug('sound different than last sound: '+self.lastSound.sID);
        if (self.lastSound) self.stopSound(self.lastSound);
      }
    } else {
       get_the_lrc(soundURL);
      // create sound
      snd_inst = sm.createSound({
       id:'inlineMP3Sound'+(self.soundCount++),
       url:soundURL,
       onplay:self.events.play,
       onstop:self.events.stop,
       onpause:self.events.pause,
       onresume:self.events.resume,
       onfinish:self.events.finish
      });
      // tack on some custom data
      snd_inst._data = {
        oLink: o, // DOM node for reference within SM2 object event handlers
        className: self.css.sPlaying
      };
      self.soundsByURL[soundURL] = snd_inst;
      self.sounds.push(snd_inst);
      if (self.lastSound) self.stopSound(self.lastSound);
      snd_inst.play();
      // stop last sound
    }

    self.lastSound = snd_inst; // reference for next call

    if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
      e.preventDefault();
    } else {
      event.returnValue = false;
    }
    return false;
  }

  this.stopSound = function(oSound) {
    soundManager.stop(oSound.sID);
    soundManager.unload(oSound.sID);
  }

  this.init = function() {
    sm._writeDebug('inlinePlayer.init()');
    var oLinks = document.getElementsByTagName('a');
    // grab all links, look for .mp3
    var foundItems = 0;
    for (var i=0; i<oLinks.length; i++) {
      if (oLinks[i].href.match(/\.mp3/i) && !self.classContains(oLinks[i],self.excludeClass)) {
        self.addClass(oLinks[i],self.css.sDefault); // add default CSS decoration
        self.links[foundItems] = (oLinks[i]);
        self.indexByURL[oLinks[i].href] = foundItems; // hack for indexing
        foundItems++;
      }
    }
    if (foundItems>0) {
      self.addEventHandler(document,'click',self.handleClick);
	  if (self.config.autoPlay) {
	    self.handleClick({target:self.links[0],preventDefault:function(){}});
	  }
    }
    sm._writeDebug('inlinePlayer.init(): Found '+foundItems+' relevant items.');
  }

  this.init();

}

var inlinePlayer = null;

soundManager.debugMode = false; // disable or enable debug output

soundManager.url = './'; // path to directory containing SM2 SWF

soundManager.onready(function() {
  if (soundManager.supported()) {
    inlinePlayer = new InlinePlayer();
  }
});

String.prototype.trim = function() {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
};

/* following is lyrics part */

/* this function is copied straight from:
 * http://dt.in.th/2008-05-18.javascript-karaoke-lyric-scroller.html 
 * */
function parseTime(x) {
	var l = x.split('.');
	var t = 0;
	try {
		var j = l[0].split(':');
		t += parseInt(j[j.length - 1], 10) * 1000;
		if (j.length > 1) {
			t += parseInt(j[j.length - 2], 10) * 60000;
		}
		if (j.length > 2) {
			t += parseInt(j[j.length - 3], 10) * 3600000;
		}
		if (l.length > 1) {
			if (l[1].length == 1) {
				t += parseInt(l[1], 10) * 100;
			} else if (l[1].length == 2) {
				t += parseInt(l[1], 10) * 10;
			} else if (l[1].length == 3) {
				t += parseInt(l[1], 10) * 1;
			}
		}
		return t;
	} catch (e) {
		return 0;
	}
}


var zzz=[];
var lrcs=[]

function get_the_lrc(mp3url){
    var lrcurl = mp3url.substr(0,mp3url.length-4)+".lrc";
    $("#lxjdottv_lrc").find("p").remove();
    zzz=[];
    for(var i=0;i<lrcs.length;i++){
        if(lrcs[i][0]==lrcurl){
            load_the_lrc(lrcs[i][1]);
            return;
        }
    }
    $.get(lrcurl, function(data){
        lrcs.push([lrcurl,data]);
        load_the_lrc(data);
    });
}

load_the_lrc = function(data){
	var m = data.split(/\n/g);
	var d;
        var nl = 1;
	for (var i = 0; i < m.length; i ++) {
            if (d = m[i].trim().match(/^\[([0-9:\.]+)\](.*)$/)) {
                if (a = parseTime(d[1])) {
                    var p;
                    if(d[2]==""){ p=$("<p>&nbsp;</p>");}
                    else        { p=$("<p>"+d[2]+"</p>");}
                    p.attr('ID',"lxjsm_"+i);
                    p.css({"color":"#fff"});
                    $("#lxjdottv_lrc").append(p);
                    zzz.push ([a,i, "lxjsm_"+i]);
                    nl++;
                }
            }
            else{
                var p=$("<p>"+m[i]+"</p>");
                p.attr('ID',"lxjsm_"+i);
                p.css({"color":"#fff"});
                $("#lxjdottv_lrc").append(p);
            }
	}
};

$(document).ready(function(){
        setInterval (cont, 100);
});


var lst = 0;
var cur_i = 0;
function cont() {
    if (zzz.length < 1) return;
    if (!snd_inst) return;
    var real = snd_inst.position - 50;
    if(real <zzz[0][0]){
       cur_i = 0;
       return;
    }
    if (cur_i<zzz.length && real > zzz[cur_i][0]) {
        var c = zzz[cur_i];
        if (lst !== 0) {
            //$("#"+lst).css({"font-size":"12px","font-weight":"","background-color":"#fff"});
            $("#"+lst).css({"font-weight":"","background-color":"#000"});
        }
        if(c[1]>6){
            var cc=c[1]-3;
            $("#lxjdottv_lrc").scrollTo( $("#lxjsm_"+cc), 800 );
        }
        $("#"+c[2]).css({"font-weight":"bold","background-color":"#066"});
        //$("#"+c[2]).animate({fontSize: "18px"},1000);
        lst = c[2];
        cur_i++;
    }
}
