// JavaScript Document
var playIndex = null;
var userID    = Math.round(10000000000 * Math.random());
var duration = null;
var file = null;
var player            =  null;
var playlist          =  null;
var currentState      =  null;
var currentItem       =    -1;
var currentPosition   =     0;
var previousPosition  =     0;
var playItem          = false;
var total_watched     =     0;
var skipped           =     0;
var buffering_start   =     0;
var total_buffering   =     0;
var total_tracks      =  null;
var myRequest         = new ajaxObject('/player/statistics_plus_v4.php');			
			
function ajaxObject(url, callbackFunction)  {
        var that      = this;
        this.updating = false;
        this.abort    = function()
        {
          if(that.updating)
          {
            that.updating = false;
            that.AJAX.abort();
            that.AJAX     = null;
          }
        }

        this.update = function(passData, postMethod)
        {
          if(that.updating)
          {
            return false;
          }

          that.AJAX = null;

          if(window.XMLHttpRequest)
          {
            that.AJAX = new XMLHttpRequest();
          }
          else
          {
            that.AJAX = new ActiveXObject("Microsoft.XMLHTTP");
          }

          if(that.AJAX == null)
          {
            return false;
          }
          else
          {
            that.AJAX.onreadystatechange = function()
            {
              if (that.AJAX.readyState == 4)
              {
                that.updating = false;
                that.callback(that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML);
                that.AJAX = null;
              }
            }
            that.updating = new Date();

            if(/post/i.test(postMethod))
            {
              var uri = urlCall + '?' + that.updating.getTime();
              that.AJAX.open("POST", uri, true);
            //that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
              that.AJAX.setRequestHeader("Content-type", "text/plain");
              that.AJAX.setRequestHeader("Content-Length", passData.length);
            //alert('passData: ' + passData);
              that.AJAX.send(passData);
            }
            else
            {
              var uri = urlCall + '?' + passData + '&timestamp=' + (that.updating.getTime());
              that.AJAX.open("GET", uri, true);
              that.AJAX.send(null);
            }
            return true;
          }
        }

        var urlCall = url;

        this.callback = callbackFunction || function ()
        {
        //alert('AJAX Request Done');
        }
}

function playerReady(obj) {
	player = document.getElementById(obj['id']);
	player.addControllerListener('ITEM','itemMonitor');
	player.addControllerListener('PLAYLIST','playlistMonitor');
	player.addModelListener('STATE','stateMonitor');
	player.addModelListener('TIME','timeMonitor');
	player.addViewListener('STOP', 'itemMonitor');
}

function itemMonitor(obj) {
	if(currentItem != obj.index) {
	if(file != undefined) {
		var statistics =
		{
			file: file,
			duration: duration,
			watched: Math.round(currentPosition),
			lingua: lingua,
			userid: userID
		}
		myRequest.update(JSON.stringify(statistics), 'POST');
	  
		}
		  file = playlist[obj.index]['file'];
		  duration = playlist[obj.index]['duration'];
		  // reset counters
		  currentPosition = 1;
	}
	//...global for use in other functions and to remember the previous item
	currentItem = 1
};


function playlistMonitor(obj)  {
        //...global for use in other functions
        playlist = obj.playlist;
        if((playIndex != null) && ((playIndex - 1) < playlist.length))
        {
          player.sendEvent('ITEM', (playIndex - 1));
          playIndex = null;
        }
      }


function stateMonitor(obj)  {
        // play the requested item
        if((obj.newstate == 'IDLE') && (playItem == true))
        {
          player.sendEvent('ITEM', playIndex);
          playItem = false;
        }
	    if(obj.newstate == 'BUFFERING')
        {
          buffering_start = new Date().getTime();
        }
        else if((obj.newstate == 'PLAYING') && (buffering_start != 0))
        {
          total_buffering += Math.round((new Date().getTime() - buffering_start) / 1000);
          buffering_start = 0;
        }
        if(obj.newstate == 'COMPLETED') { }
        //...global for use in other functions and to remember the previous state
        currentState = obj.newstate;
}


function timeMonitor(obj)   {
        //...global for use in other functions and to remember the previous position
        // accumulate position for amount watched
        currentPosition = obj.position;
		duration = obj.duration;
        if(previousPosition < currentPosition - .5)
        {
          skipped += currentPosition - previousPosition;
        } else if(previousPosition > currentPosition && currentPosition == 0) {
			currentPosition = duration;
		}
        previousPosition = currentPosition;
}	
			

