(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};
 
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
   
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
   
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
           
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
           
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);       
            this._super = tmp;
           
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
   
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
   
    // Populate our constructed prototype object
    Class.prototype = prototype;
   
    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
   
    return Class;
  };
})();


var MediaPlayer = Class.extend({
	// Properties
	player:null,
	isMuted:false,
	oldState:-1,
	
	bufferIntervalID:-1,
	isBuffering:false,
	bufferingProgress:0, // in percents
	
	// Method
	init: function(id){
		var self = this;
		switch($.browser.name) {
			case 'chrome':
				setInterval(function(){
					self._checkState();
				},1000);
			break;
		}
	
		if (window.document[id]) {
			this.player = window.document[id];
			return;
		}
	    if (navigator.appName.indexOf("Microsoft Internet")==-1 && document.embeds && document.embeds[id]){
	    	this.player = document.embeds[id];
	    	return;
	    }
	    this.player = document.getElementById(id);
    },
    
	play: function(){
		var state = this.getState();
		if(state == 1 || state == 2) { // if stoped (1), or paused (2)
			this.player.controls.play();
			return true;
		}
		return false;
	},
	
	stop: function(){
		if(this.getState() == 3) { // if playing (3)
			this.player.controls.stop();
			return true;
		}
		return false;
	},
	
	toggleMute: function(){
		this.player.settings.mute = (!this.isMuted) ? true : false;
		this.isMuted = !this.isMuted;
	},
	
	setVolume: function(volume){
		this.player.settings.volume = volume;
	},
	
	getVolume: function(volume){
		return this.player.settings.volume;
	},
	
	fullScreen: function(volume){
		if(this.getState() == 3) this.player.fullScreen = true;
	},
	
	getState: function(){
		return this.player.playState;
	},
	
	getBufferingProgress: function() {
		return this.bufferingProgress;
	},
	
	exists: function(){
		return (!this.player) ? false : true;
	},
	
	hasPlugin: function(){
		return (this.player.playState != undefined) ? true : false;
	},
	
	setSrc:function(src) {
		this.player.src = src; 
		this.player.URL = src; 
	},
	
	_checkState: function() {
		var currState = this.getState();
		if (currState != this.oldState) {
			OnDSPlayStateChangeEvt(currState); // default state change event handler
			if (currState == 6 || this.oldState == 6) { // State 6 is buffering
				OnDSBufferingEvt(currState == 6); // default buffering event handler
			}
		}
		this.bufferingProgress = (currState == 3) ? 100 : 0; // // State 3 is playing
		this.oldState = currState;
	},
	
	// Events
	playStateChange: function(newState) {
		
	},
	
	buffering: function(Start) {
		var self = this;
		if (Start && this.bufferIntervalID < 0) this.bufferIntervalID = setInterval(function() {self.buffering(Start);},500);
		this.isBuffering = Start;
		this.bufferingProgress = this.player.network.bufferingProgress;
		if (this.bufferingProgress == 100) {
			clearInterval(this.bufferIntervalID);
			this.bufferIntervalID = -1;
		}
	}
});



function MediaPlayerStats() {
	this.url = "";
	this.id = -1;
	
	var d=new Date();
	this.runningTimeIntervalID = -1;
	this.runningTimeInterval = 60000; // 1 minute
	this.lastRuningTime = d.getTime()/1000;
	
	this.bufferSent = true;
	this.sendBufferIntervalID = -1;
	this.sendBufferThreshold = 1000; // 1 second
	this.deltaBufferTime = 0;
	this.bufferingStart = -1;
	this.bufferingsThreshold = 5;
	this.onTooManyBufferings = null;
	
	
	this.runningTime = function() {
		var self = this;
		
		$.ajax({
			type: 'POST',
			url: self.url,
			data: {
				'id': self.id,
				'timetoadd': self.runningTimeInterval/1000 // in seconds
			},
			dataType: 'json',
			jsonp:'jsonp_callback'
		});
		var d=new Date();
		this.lastRuningTime = d.getTime()/1000;
	};
	
	this.stopRunning = function(reason){
		var self = this;
		
		clearInterval(this.runningTimeIntervalID);
		this.runningTimeIntervalID = -1;
		
		var d=new Date();
		var now = d.getTime()/1000;
		$.ajax({
			async: false,
			type: 'POST',
			url: self.url,
			data: {
				'id': self.id,
				'stop': 1,
				'timetoadd': now - self.lastRuningTime,
				'reason': reason
			},
			dataType: 'json',
			jsonp:'jsonp_callback'
		});
	};
	
	this.startRunning = function(){
		var self = this;
		var d=new Date();
		
		this.id = -1;
		clearInterval(this.runningTimeIntervalID);
		this.runningTimeIntervalID = -1;
		this.lastRuningTime = d.getTime()/1000;
		
		this.bufferSent = true;
		clearInterval(this.sendBufferIntervalID);
		this.sendBufferIntervalID = -1;
		this.deltaBufferTime = 0;
		this.bufferingStart = -1;
		
		var self = this;
		$.ajax({
			type: 'POST',
			url: self.url,
			data: {
				'id': self.id,
				'start': 1
			},
			dataType: 'text',
			jsonp:'jsonp_callback',
			async: false,
			success: function(data){
				if (data != ""){
					self.id = data;
				}
			}
		});
		
		
		if (this.runningTimeIntervalID < 0) {
			this.runningTimeIntervalID = setInterval(function() {
				self.runningTime();
			},this.runningTimeInterval);
		}
	};
	
	
	this.buffering = function(Start) {
		var self = this;
		var d=new Date();
		if (Start) {
			if (this.bufferSent) {
				this.bufferingStart = d.getTime()/1000;
			}
			else {
				clearInterval(this.sendBufferIntervalID);
				this.sendBufferIntervalID = -1;
			}
		} else {
			var now = d.getTime()/1000;
			if (this.bufferingStart > 0) {
				var buffering_duration = now - this.bufferingStart;
				if (buffering_duration > this.sendBufferThreshold/1000 && this.id != -1) {
					$.ajax({
						type: 'POST',
						url: self.url,
						data: {
							'id': self.id,
							'buffering': 1,
							'timetoadd': buffering_duration - (this.deltaBufferTime/1000)
						},
						dataType: 'json',
						jsonp:'jsonp_callback',
						success: function(data) {
							// capture slow internet connection
							if (parseInt(data,10) >= self.bufferingsThreshold && self.onTooManyBufferings && typeof(self.onTooManyBufferings) == 'function') self.onTooManyBufferings(); 
						}
					});
					this.deltaBufferTime = 0;
					this.bufferingStart = -1;
					this.bufferSent = true;
				} else {
					this.deltaBufferTime += ((this.id != -1) ? (this.sendBufferThreshold/1000 - buffering_duration)*1000 : 3000);
					if (this.sendBufferIntervalID < 0) {
						this.bufferSent = false;
						this.sendBufferIntervalID = setTimeout(function(){
							self.buffering(Start);
						},this.deltaBufferTime);
					}
				}
			}
		}
	};
}


function displayErrorMessage(message){
	$.ajax({
		type: 'POST',
		url: rootURL + "ajax/geterrormessage/",
		data: {
			'id': message
		},
		dataType: 'json',
		jsonp:'jsonp_callback',
		success: function(data){
			if (data){
				if (current_error != 0 && (data.id >= current_error)) return false;
				
				current_error = data.id;
				$('#errorid').val(message);
				$('#errvid').css('display','block');
				$('<div class="message">' + data.content + '</div>').insertAfter('#errvid .closeBtn');
				
				if (data.ignorable==0){
					$('#ignorable').css('display', 'none');
				}else{
					$('#ignorable').css('display', 'block');
				}
				
				if (data.timeout > 0){
					$('#closeTimeout').html("Това съобщение ще се затвори след: <span id='closein'>" + data.timeout + "</span> секунди");
					setTimeout("errorTimeoutCountdown()", 1000);
				}else{
					$('#closeTimeout').html("");
				}
				
				$('#header').css('z-index','8');
			}
		},
		error:function(xhr,err,e){
			
		}
	});	
}



function disableErrorMessage(){
	var errorid = document.getElementById('errorid');
	var seeAgain = document.getElementById('seeAgain');
	$.ajax({
		type: 'POST',
		url: rootURL + "ajax/disableerrormessage/",
		data: {
			'id': errorid.value,
			'onoff': seeAgain.checked
		},
		dataType: 'json',
		jsonp:'jsonp_callback',
		success: function(data){
		},
		error:function(xhr,err,e){
		}
	});
}
