Delegate = function () {
};

Delegate.create = function (/*Object*/ scope, /*Function*/ method ) {
	var f = function () {
		return method.apply (scope, arguments);
	}
	return f;
};


KalturaPlayerController = function (playerId) {
	this.playerId = playerId;
	this.currentKshowId = -1;
	this.currentEntryId = -1;
	this.args = null;
};

KalturaPlayerController.prototype = {
	insertMedia: function (kshowId, entryId, autoStart) {
		this.invoke("insertMedia", kshowId, entryId, autoStart);
		this.currentKshowId = kshowId;
		this.currentEntryId = entryId;
	},
	
	insertEntry: function (entryId, autoStart) {
		this.insertMedia(-1, entryId, autoStart);
	},
	
	insertKShow: function (kshowId, autoStart) {
		this.insertMedia(kshowId, -1, autoStart);
	},
	
	pause: function () {
		this.invoke("pauseMedia");
	},
	
	stop: function () {
		this.invoke("stopMedia");
	},
	
	play: function () {
		this.invoke("playMedia");
	},
	
	seek: function (time) {
		this.invoke("seekMedia", time);
	}, 
	
	invoke: function () {
		this.playerElement = document.getElementById(this.playerId);

		// store the arguments so we can use them if the player is not ready yet 
		if (!this.args)
			this.args = arguments;
			
		// no arguments means that this function was called after the local args were set to null
		if (!this.args || this.args.length == 0)
			return;
	
		var method = this.args[0];
		
		if (this.playerElement && this.playerElement[method]) {
			// shift to remove the method name from the array
			var args = Array.prototype.slice.call(this.args, [1]);
			
			switch (args.length) {
				case 1:
					this.playerElement[method](args[0]);
					break;
				case 2:
					this.playerElement[method](args[0], args[1]);
					break;
				case 3:
					this.playerElement[method](args[0], args[1], args[2]);
					break;
				default:
					this.playerElement[method]();
					break; 	
			}
			
			this.args = null; // clean the arguments container
		}
		else {
			var f = Delegate.create(this, this.invoke);
			setTimeout(f, 200);
		}
	},
	
	reload: function () {
		this.insertMedia(this.currentKshowId, this.currentEntryId, true);
	}
};