var DEBUG = true;

var playlist = {
      "1": {
      	id: "1",
        title: "Follie Circus",
        url: "http://www.chiavedies.it/audio/2003-Prima_Battuta_dell_Ego/01-Chiave_di_Es_-_Follie_Circus.mp3",
        album: "Prima battuta dell'ego",
        anno: "2003"
      },
      "2": {
      	id: "2",
        title: "Annalena",
        url: "http://www.chiavedies.it/audio/2003-Prima_Battuta_dell_Ego/02-Annalena.mp3",
        album: "Prima battuta dell'ego",
        anno: "2003"
      },
      "3": {
      	id: "3",
        title: "Costa del Sol",
        url: "http://www.chiavedies.it/audio/2008-Satura_Lanx/Chiave_di_Es-04-Costa_del_Sol.mp3",
        album: "Satura Lanx",
        anno: "2008"
      },
      "4": {
      	id: "4",
        title: "Walking the Way of Sunshine",
        url: "http://www.chiavedies.it/audio/2008-Satura_Lanx/Chiave_di_Es-02-Walking_the_way_of_Sunshine.mp3",
        album: "Satura Lanx",
        anno: "2008"
      },
      "5": {
      	id: "5",
        title: "Nove",
        url: "http://www.chiavedies.it/audio/2008-Satura_Lanx/Chiave_di_Es-01-Nove.mp3",
        album: "Satura Lanx",
        anno: "2008"
      },
      "6": {
      	id: "6",
        title: "Ultimo Tango",
        url: "http://www.chiavedies.it/audio/2008-Satura_Lanx/Chiave_di_Es-03-Ultimo_Tango_nel_Ninfeo.mp3",
        album: "Satura Lanx",
        anno: "2008"
      },
      "7": {
      	id: "7",
        title: "Mormone Metallico",
        url: "http://www.chiavedies.it/audio/2008-Satura_Lanx/Chiave_di_Es-05-Mormone_Metallico.mp3",
        album: "Satura Lanx",
        anno: "2008"
      },
      "8": {
      	id: "8",
        title: "Digital Sushi",
        url: "http://www.chiavedies.it/audio/2010-B-Sides/Chiave_di_Es-06-Digital_Sushi.mp3",
        album: "Satura Lanx",
        anno: "2010"
      },
      "9": {
      	id: "9",
        title: "Jasmine",
        url: "http://www.chiavedies.it/audio/2010-B-Sides/Chiave_di_Es-07-Jasmine.mp3",
        album: "Satura Lanx",
        anno: "2010"
      },
      "10": {
      	id: "10",
        title: "A'ntrasatta",
        url: "http://www.chiavedies.it/audio/2010-B-Sides/Chiave_di_Es-08-A'ntrasatta.mp3",
        album: "Satura Lanx",
        anno: "2010"
      }
    };
    
    function getObjectLength(obj){
      var length=-1;
      for(v in obj){
        length++;
      };
      if(length == -1) return false;
      else  return length+1;
    }

    function Player(){
      this._object = null;
      this._isPlaying = false;
      this.init = init;
      this.tryPlay = tryPlay;
      this.pause = pause;
      this.stop = stop;
      this.next = next;
      this.previous = previous;
      this.setVolume = setVolume;
      this._firstPlay = true;
      this.TIMER = null;
      this._lastSongObj = null;
      this._prevSongObj = null;
      this._volume = 0.5;
      
      function init(){
        // sets a random url from the playlist
        var randomnumber=Math.floor(Math.random()*getObjectLength(playlist));
        randomnumber = randomnumber + 1;
        var songObj = playlist[""+randomnumber+""];
        this._lastSongObj = songObj;
        this._prevSongObj = songObj;
        toLog(songObj.title);
        toLog(songObj.url);
				$("#jP").jPlayer( {
					ready: function () {
						$(this).setFile(songObj.url);
					},
					oggSupport: false,
					swfPath: "http://www.chiavedies.it/js"
				});
				$("#jP").onProgressChange( function(lp,ppr,ppa,pt,tt) {});

				$("#jP").onSoundComplete( function(){});


        /*var flashvars = {
          src: songObj.url
        };
        var params = {
          allowScriptAccess: 'always',
          wmode: 'transparent'
        };
        var attributes = {
          id : 'DCRadioPlayer'
        };
        swfobject.embedSWF("player.swf", "jP", "1", "1", "9.0.115", false, flashvars, params, attributes);*/
              
        //this.TIMER = setInterval(function(that){ that.tryPlay(songObj);},500,this);
      }
        
      function tryPlay(songObj){
        if(songObj == ''){
          songObj = this._lastSongObj;
        }
        if(!this._isPlaying){
          // gui
          $('#player-play').attr("id","player-pause");
          
          toLog("1");
          try{
            /*var object = '';
            var ua = navigator.userAgent.toLowerCase();
            if(ua.indexOf("ie") != -1){
              toLog("IE");
              object = window['DCRadioPlayer'];
            }
            else{
              toLog("NON-IE");
              object = document['DCRadioPlayer'];
            }
            object.doPlay();*/
            toLog("Play");
            //this._object = object;
            if(this._firstPlay){
            	$('#jP').setFile(songObj.url);
            	$("#jP").onProgressChange( function(lp,ppr,ppa,pt,tt) {
            		if(lp < 1){
            			var html = $('#song-title').html();
            			if(html.indexOf("loading") == -1){
            				html += "<br>(loading...)";
            			}
            			$('#song-title').html(html);
            		}
            		else if(lp > 1){
            			var html = $('#song-title').html();
            			if(html.indexOf("loading") != -1){
            				html = html.substring(0, html.length-12);
            			}
            			$('#song-title').html(html);
            		}
							});
							$("#jP").onSoundComplete(function(){
								toLog("soundComplete");
								logPlayedTrack( CDEPLAYER._lastSongObj );
								CDEPLAYER.next();
							});
            	this._firstPlay = false;
            }
            $('#jP').play();
            if(this.TIMER){
            	clearInterval(this.TIMER);
            }
            this._isPlaying = true;
            toLog(songObj.title);
            toLog(songObj.url)
            $('#song-title').html(songObj.title);
          }catch(err){
            toLog("Errore: "+err);
          }
        }
        else{
          // gui
          $('#player-pause').attr("id","player-play");
          
          toLog("2");
          this.pause();
        }
      }
      function pause(){
        toLog("Pause");
        try{
          //this._object.doPlay();
          $('#jP').pause();
          this._isPlaying = false;
        } catch(err){
          if(this.TIMER){
            clearInterval(this.TIMER);
          }
          this.init();
          toLog("Errore: "+err);
        }
      }
      function stop(changeTitle){
        toLog("Stop");
        if($('#player-pause') != 0){
          $('#player-pause').attr("id","player-play");
        }
        else if($('#player-play') != 0){
          $('#player-play').attr("id","player-pause");
        }
        try{
          //this._object.doStop();
          $('#jP').pause();
          $('#jP').setFile(this._lastSongObj.url);
          this._isPlaying = false;
          if(changeTitle)
            $('#song-title').html("<i>Stopped</i>");
          if(this.TIMER){
            clearInterval(this.TIMER);
          }
        } catch(err){
          toLog("Errore: "+err);
        }
      }
      
      function next(songObj){
      	toLog("Next");
        if(typeof(songObj) == 'undefined'){        
          // sets a random url from the playlist and plays
          var randomnumber=Math.floor(Math.random()*getObjectLength(playlist));
          randomnumber = randomnumber +1;
          var songObj = playlist[""+randomnumber+""];
          
          if(songObj == this._lastSongObj){
            toLog("uguali");
            this.next();
            return;
          }
        }
        toLog(songObj.title);
        toLog(songObj.url);
        
        this._prevSongObj = this._lastSongObj;
        this._lastSongObj = songObj;
        //this._object.setUrl(songObj.url);
        $('#jP').setFile(songObj.url);
        $('#jP').play();
        $('#song-title').html(songObj.title);
        this._isPlaying = true;
        // restore the old volume
        //this.setVolume(this._volume);
        $('#jP').volume(this._volume*100);
      }
      
      function previous(){
        if(this._prevSongObj != this._lastSongObj){
          //this.stop(false);
          // playback previous song
          /*this._object.setUrl(this._prevSongObj.url);
          this.tryPlay(this._prevSongObj);
          this.setVolume(this._volume);*/
          $('#jP').setFile(this._prevSongObj.url);
  	      $('#jP').play();
	        $('#jP').volume(this._volume*100);
	        $('#song-title').html(this._prevSongObj.title);
          
        }
      }
      
      function setVolume(val){
      	//this._object.setVolume(val);
      	$('#jP').volume(val*100);
      	this._volume = val;
      	toLog("Volume: "+val);
      }
    }
    
    // logging function
    function logPlayedTrack( songObj ){
    	toLog("Logging: "+ songObj.title);
    	$.ajax({
			 type: "POST",
			 url: "http://www.chiavedies.it/logger.php",
			 data: "id="+songObj.id,
			 success: function(request){
			 	toLog("Logger result: "+request)
			 }
			});
    }
    
    // Debugging function
    function toLog(str){
      if(DEBUG){
        if(typeof(console)!='undefined'){
          var d = new Date();
          console.log("["+d.toLocaleTimeString()+" "+d.getMilliseconds()+"] "+str);
        }
      }
    }
    
