//VideoObject
function VideoObject(tmp_video_id) {
	//Functions
	this.tooglePoster = function (tmp_visible) {
		if (!this.poster) { return; }
		
		if (tmp_visible) {
			this.poster.style.display = "block";
			this.posterOverlay.style.display = "block";
			
			this.positionPoster();
		} else {
			this.poster.style.display = "none";
			this.posterOverlay.style.display = "none";
		}
	}
	
	this.positionPoster = function () {
		if (this.poster == false || this.poster.style.display == "none") { return; }
		
		this.poster.style.width = this.video.offsetWidth + "px";
		this.poster.style.height = this.video.offsetHeight + "px";
		
		this.posterOverlay.style.width = this.video.offsetWidth + "px";
		this.posterOverlay.style.height = this.video.offsetHeight + "px";
	}
	
	this.updateControllerPosition = function () {
		/*if (this.fullscreenMode) {
			this.video.parentNode.style.width = "";
		} else {
			this.video.parentNode.style.width = this.video.offsetWidth + "px";
		}*/
		
		//alert(this.video.offsetHeight + " - " + this.controls.offsetHeight);
		
		this.controls.style.top = (this.video.offsetHeight - this.controls.offsetHeight) + "px";
		
		this.updateVolumeDisplay();
	}
	
	this.updateVolumeDisplay = function () {
		var x = this.video.offsetWidth - (246) + (this.video.volume * 140);
		this.volumeCursor.style.marginLeft = parseInt(x) + "px";
		
		this.volumeDisplay.style.width = parseFloat(this.video.volume * 100) + "%";
	}
	
	this.setVolume = function (tmp_volume) {
		this.video.volume = parseFloat(tmp_volume);
	}
	
	this.setVolumeWithEvent = function (e) {
		var volume = VideoUtils.getRelativePosition(event.pageX, this.volumeControl);
		this.setVolume(volume);
	}
	
	this.setPlayProgressWithEvent = function (e) {
		var progress = VideoUtils.getRelativePosition(event.pageX, this.progressControl);
		this.playProgress.style.width = parseFloat(progress * 100) + "%";
		this.progressCursor.style.marginLeft = parseInt(this.getProgressBarWidth() * progress - 15) + "px";
		this.video.currentTime = this.video.duration * progress;
		this.updateTimeDisplay();
	}
	
	this.updateTimeDisplay = function () {
		this.timeControlElapsed.innerHTML = VideoUtils.formatTime(this.video.currentTime) + " / ";
		this.timeControlLength.innerHTML = VideoUtils.formatTime(this.video.duration);
	}
	
	this.toogleFullscreen = function (tmp_enabled) {
		if (tmp_enabled) {
			this.fullscreenMode = true;
			
			if (typeof this.video.webkitEnterFullScreen == 'function' && false) {
				this.video.controls = true;
				this.controls.style.display = 'none';
			} else {
				//this.video.controls = true;
				//this.controls.style.display = 'none';
				
				this.docOrigOverflow = document.documentElement.style.overflow;
				
				document.addEventListener("keydown", this.onEscKey, false);
				document.addEventListener("resize", this.onWindowResize, false);
				
				document.documentElement.style.overflow = 'hidden';
				
				VideoUtils.addClass(this.video.parentNode, "video_fullscreen");
				
				var list = document.documentElement.getElementsByTagName("body")[0].children;
				this.objectsProperties = [];
				for (i = 0; i < list.length; i++) {
					this.objectsProperties[i] = [list[i].style.position, list[i].style.width, list[i].style.height, list[i].style.top];
					list[i].style.position = 'fixed';
					list[i].style.width = '1px';
					list[i].style.height = '1px';
					list[i].style.top = '0';
				}
				
				//this.lastPagePosition = this.getPagePosition();
				window.scrollTo(0, 0);
			}
		} else {
			this.fullscreenMode = false;
			//this.video.controls = false;
			//this.controls.style.display = '';
			
			document.removeEventListener("keydown", this.onEscKey, false);
			document.removeEventListener("resize", this.onWindowResize, false);
			
			document.documentElement.style.overflow = this.docOrigOverflow;
			
			VideoUtils.removeClass(this.video.parentNode, "video_fullscreen");
			
			var list = document.documentElement.getElementsByTagName("body")[0].children;
			for (i = 0; i < list.length; i++) {
				list[i].style.position = this.objectsProperties[i][0];
				list[i].style.width = this.objectsProperties[i][1];
				list[i].style.height = this.objectsProperties[i][2];
				list[i].style.top = this.objectsProperties[i][3];
			}
			
			//alert(this.lastPagePosition.x + " - " + this.lastPagePosition.y);
			//window.scrollTo(this.lastPagePosition.y, this.lastPagePosition.x);
		}
		
		this.updateControllerPosition();
		this.positionPoster();
	}
	
	this.getPagePosition = function () {
		var st = document.body.scrollTop;
		if (st == 0) {
			if (window.pageYOffset) {
				st = window.pageYOffset;
			} else {
				st = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
		}
		var sl = document.body.scrollLeft;
		if (sl == 0) {
			if (window.pageXOffset) {
				sl = window.pageXOffset;
			} else {
				sl = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;
			}
		}
 
 		return {x: sl, y: st};
	}
	
	this.getProgressBarWidth = function () {
		return (this.video.offsetWidth - 40 - 360);
	}
	
	//Events
	this.onPlayControlClick = function (e) {
		if (this.video.paused) {
			this.video.play();
			
			this.controls.style.display = '';
			this.updateControllerPosition();
		} else {
			this.video.pause();
		}
	}
	
	this.onProgressControlMouseDown = function (e) {
		this.trackTimeEnabled = false;
		
		if (this.video.paused) {
			this.videoWasPlaying = false;
		} else {
			this.videoWasPlaying = true;
			this.video.pause();
		}
		
		VideoUtils.blockTextSelection();
		
		document.onmousemove = function (e) {
			this.setPlayProgressWithEvent(e);
		}.context(this);
		
		document.onmouseup = function (e) {
			this.setPlayProgressWithEvent(e);
			
			VideoUtils.unblockTextSelection();
			document.onmousemove = null;
			document.onmouseup = null;
			if (this.videoWasPlaying) {
				this.video.play();
				this.trackTimeEnabled = true;
			}
		}.context(this);
	}
	
	this.onProgressControlMouseUp = function (e) {
		this.setPlayProgressWithEvent(e);
		
		if (this.video.paused) {
			this.onPause();
		} else {
			this.onPlay();
		}
	}
	
	this.onVolumeControlMouseDown = function (e) {
		VideoUtils.blockTextSelection();
		
		document.onmousemove = function (e) {
			this.setVolumeWithEvent(e);
		}.context(this);
		
		document.onmouseup = function (e) {
			VideoUtils.unblockTextSelection();
			document.onmousemove = null;
			document.onmouseup = null;
		}.context(this);
	}
	
	this.onVolumeControlMouseUp = function (e) {
		this.setVolumeWithEvent(e);
	}
	
	this.onFullscreenControlClick = function (e) {
		setTimeout(function () {
			if (!this.fullscreenMode) {
				this.toogleFullscreen(true);
			} else {
				this.toogleFullscreen(false);
			}
		}.context(this), 60);
	}
	
	this.onMouseOver = function (e) {
		if (this.video.paused) {
			//this.playButton.style.display = '';
			Tween.addTween(this.playButton, 0.4, { _alpha: 100, transition: "quadOut" });
		}
	}
	
	this.onMouseOut = function (e) {
		if (this.video.paused) {
			//this.playButton.style.display = 'none';
			Tween.addTween(this.playButton, 0.4, { _alpha: 0, transition: "quadOut" });
		}
	}
	
	//Video Events
	this.onPlay = function (e) {
		this.playControl.className = "play_control pause";
		this.tooglePoster(false);
		this.playButton.style.display = 'none';
		
		if (VideoObject.currentPlaying != null && VideoObject.currentPlaying.videoId != this.videoId) {
			VideoObject.currentPlaying.video.pause();
		}
		
		VideoObject.currentPlaying = this;
	}
	
	this.onPause = function (e) {
		this.playControl.className = "play_control";
		this.playButton.style.display = '';
	}
	
	this.onEnd = function (e) {
		this.video.pause();
		this.onPause();
	}
	
	this.onVolumeChange = function (e) {
		this.updateVolumeDisplay();
	}
	
	this.onTimeUpdate = function (e) {
		if (this.trackTimeEnabled) {
			this.updateTimeDisplay();
			this.playProgress.style.width = parseFloat((this.video.currentTime / this.video.duration) * 100) + "%";
			this.progressCursor.style.marginLeft = parseInt(this.getProgressBarWidth() * (this.video.currentTime / this.video.duration) - 15) + "px";
		}
	}
	
	this.updateTimerEvent = function (e) {
		if (this.video.buffered) {
			if (this.video.buffered.length >= 1) {
				this.loadProgress.style.width = ((this.video.buffered.end(0) / this.video.duration) * 100) + "%";
				
				if (this.video.buffered.end(0) == this.video.duration) {
					clearInterval(this.updateTimer);
				}
			}
		}
	}
	
	


	//Constructor
	this.videoId = tmp_video_id;
	this.video = $(this.videoId);
	this.controls = this.video.parentNode.getElementsByClassName('controls')[0];
	this.autoplay = false;
	
	this.video.controls = false;
	this.controls.style.display = 'none';
	
	this.trackTimeEnabled = true;
	this.fullscreenMode = false;
	
	//.Poster
	if (this.video.poster) {
    	this.poster = document.createElement("img");
		this.video.parentNode.appendChild(this.poster);
		this.poster.src = this.video.poster;
		this.poster.className = "poster";
		
		this.posterOverlay = document.createElement("img");
		this.video.parentNode.appendChild(this.posterOverlay);
		this.posterOverlay.src = VideoObject.posterOverlayUrl;
		this.posterOverlay.className = "poster";
    } else {
      this.poster = false;
    }

	this.tooglePoster(true);
	
	//.Controls
	this.playControl = this.controls.getElementsByClassName('play_control')[0];
	this.playButton = $('#play_button', this.video.parentNode)[0];
	this.progressControl = this.controls.getElementsByClassName('progress_control')[0];
	this.loadProgress = $('#loaded', this.progressControl)[0].getElementsByTagName('li')[0];
	this.playProgress = $('#played', this.progressControl)[0].getElementsByTagName('li')[0];
	this.progressCursor = $('#progress_cursor', this.controls)[0];
	this.timeControlElapsed = $('#elapsed', this.controls.getElementsByClassName('time_control')[0])[0];
	this.timeControlLength = $('#length', this.controls.getElementsByClassName('time_control')[0])[0];
	this.volumeControl = $('#bar', $('#scroll', this.controls.getElementsByClassName('volume_control')[0])[0])[0];
	this.volumeDisplay = this.volumeControl.getElementsByTagName('li')[0];
	this.volumeCursor = $('#volume_cursor', this.controls)[0];
	this.fullscreenControl = this.controls.getElementsByClassName('fullscreen_control')[0];
	
	this.video.addEventListener("play", this.onPlay.context(this), false);
	this.video.addEventListener("pause", this.onPause.context(this), false);
	this.video.addEventListener("ended", this.onEnd.context(this), false);
	this.video.addEventListener("volumechange", this.onVolumeChange.context(this), false);
	this.video.addEventListener("timeupdate", this.onTimeUpdate.context(this), false);
	
	this.updateTimer = setInterval(this.updateTimerEvent.context(this), 33);
	
	
	this.playControl.addEventListener("click", this.onPlayControlClick.context(this), false);
	this.playButton.addEventListener("mousedown", this.onPlayControlClick.context(this), false);
	this.video.addEventListener("mousedown", this.onPlayControlClick.context(this), false);
	if (this.poster) { 
		this.poster.addEventListener("mousedown", this.onPlayControlClick.context(this), false);
		this.posterOverlay.addEventListener("mousedown", this.onPlayControlClick.context(this), false);
	}
	
	this.progressControl.addEventListener("mousedown", this.onProgressControlMouseDown.context(this), false);
	this.progressControl.addEventListener("mouseup", this.onProgressControlMouseUp.context(this), false);
	this.progressCursor.addEventListener("mousedown", this.onProgressControlMouseDown.context(this), false);
	this.progressCursor.addEventListener("mouseup", this.onProgressControlMouseUp.context(this), false);
	
	this.setVolume(0.85);
	this.volumeControl.addEventListener("mousedown", this.onVolumeControlMouseDown.context(this), false);
	this.volumeControl.addEventListener("mouseup", this.onVolumeControlMouseUp.context(this), false);
	this.volumeCursor.addEventListener("mousedown", this.onVolumeControlMouseDown.context(this), false);
	this.volumeCursor.addEventListener("mouseup", this.onVolumeControlMouseUp.context(this), false);
	this.updateVolumeDisplay();
	
	this.fullscreenControl.addEventListener("click", this.onFullscreenControlClick.context(this), false);
	
	if (!OS.isIOS) {
		this.video.parentNode.addEventListener("mouseover", this.onMouseOver.context(this), false);
		this.video.parentNode.addEventListener("mouseout", this.onMouseOut.context(this), false);
		//this.playButton.style.display = 'none';
		if (Browse.isIE) this.playButton.style.filter = "alpha(opacity=0)";
		this.playButton.style.opacity = 0;
		this.playButton._alpha = 0;
	}
	
	this.onEscKey = function(e) {
      if (e.keyCode == 27) {
        this.toogleFullscreen(false);
      }
    }.context(this);

    this.onWindowResize = function(e) {
      this.updateControllerPosition();
    }.context(this);
	
	this.updateControllerPosition();
}

VideoObject.setup = function (tmp_video_id) {
	var obj = new VideoObject(tmp_video_id);
	return obj;
}

VideoObject.currentPlaying = null;
VideoObject.posterOverlayUrl = '';

//Utils
var VideoUtils = {
	blockTextSelection: function(){
		document.body.focus();
		document.onselectstart = function () { return false; };
	},
	
	unblockTextSelection: function(){
		document.onselectstart = function () { return true; };
	},
	
	formatTime: function(seconds) {
		seconds = Math.round(seconds);
		minutes = Math.floor(seconds / 60);
		minutes = (minutes >= 10) ? minutes : "0" + minutes;
		seconds = Math.floor(seconds % 60);
		seconds = (seconds >= 10) ? seconds : "0" + seconds;
		
		return minutes + ":" + seconds;
	},
	
	getRelativePosition: function(x, relativeElement){
		return Math.max(0, Math.min(1, (x - VideoUtils.findPosX(relativeElement)) / relativeElement.offsetWidth));
	},
	
	findPosX: function(obj) {
		var curleft = obj.offsetLeft;
		while(obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
		}
		return curleft;
	},
	
	addClass: function(element, classToAdd){
		if (element.className.split(/\s+/).lastIndexOf(classToAdd) == -1) { element.className = element.className == "" ? classToAdd : element.className + " " + classToAdd; }
	},

	removeClass: function(element, classToRemove){
		if (element.className.indexOf(classToRemove) == -1) return;
		var classNames = element.className.split(/\s+/);
		classNames.splice(classNames.lastIndexOf(classToRemove),1);
		element.className = classNames.join(" ");
	}
}

Function.prototype.context = Function.prototype.bind;
/*Function.prototype.context = function(obj) {
  var method = this
  temp = function() {
    return method.apply(obj, arguments)
  }
 return temp
}*/

var lastFlashPlayingId = '';
function stopAllPlayers(tmp_id) {
	if (lastFlashPlayingId != '' && lastFlashPlayingId != tmp_id) {
		document["swf_htmlVideo" + lastFlashPlayingId + "_video_container"].pause();
	}
	
	lastFlashPlayingId = tmp_id;
}

function updatePlayerTime(tmp_id, tmp_time, tmp_duration) {
	if (!(tmp_duration > 1) || !$('htmlVideo' + tmp_id + '_time')) {
		return;
	}
	
	$('htmlVideo' + tmp_id + '_time').innerHTML = VideoUtils.formatTime(tmp_time) + " / " + VideoUtils.formatTime(tmp_duration);
}

