/*
 *
 * MTPro Movie Player
 *
 * last modified : 2010/10/06
 *
 * CHANGE LOG
 * 1.2.2 fixed an issue that MTPlayer doesn't resize to fit to window frame in fullwindow mode.
 * 1.2.0 ADD: html5 support
 * 1.0.0 deploy
 *
 * CONTACT
 * je2,Inc.
 * mailto:woz@je2.jp
 * hiroshi ozaki
 *
**/

var MP_IMAGE_DIR = "/js/movieplayer/";
// var MP_IMAGE_DIR = "images/"; // for test use

var MP_DEFAULT_WIDTH = 320;
var MP_DEFAULT_HEIGHT = 240;
var MP_CONTROLER_HEIGHT = 24;

var _debug = false;

var MTHTML5Player = function(){};
MTHTML5Player.prototype = 
{
	isPLAYING : false,
	isMUTING : false,
	isFULLWINDOW : false,
	isVOLUME_BAR : false,
	isThumbnail : false,
	dir:MP_IMAGE_DIR,
	path: null,
	player : null,
	video : null,
	param : {},
	playBtn : null,
	overlay : null,
	logo : null,
	controls : null,
	miniBar: null,
	seekBar: null,
	progressBar : null,
	progressBarWidth : 0,
	loadedBar : null,
	scrabBar : null,
	speakerBtn : null,
	volumeArea : null,
	volumeControl : null,
	volumeLevel : null,
	volumeOnBar : null,
	volumeScrabBar : null,
	savedVolume : 0,
	savedCurrentTime : 0,
	savedDuration : 0,
	savedBufferedPer : 0,
	savedCurrentPer : 0,
	currentTimeLabel : null,
	durationLabel : null,
	startX : 0,
	startY : 0,
	spanX : 0,
	spanY : 0,
	startTime : 0,
	startVolume : 0,
	volumeHeight:50,
	controlsHeight : MP_CONTROLER_HEIGHT,
	iPad: false,
	
	init:function(path, param)
	{
		this.iPad = navigator.userAgent.match(/iPad/i) != null;
		this.controlsHeight = this.iPad ? 0 : this.controlsHeight;
		this.path = path;
		try { this.param = param; } catch(e){ this.param = {};}
		this.isThumbnail = hasKey("thumbnail", this.param) ? true : false;
		this.param.autoBar = !hasKey("autoBar",this.param) ? true : this.param.autoBar;
		var obj = this;
		window.onresize = function(){obj.updateByResize();}

		this.initInterface();
	},
	
	createVideo:function()
	{
		_obj = this;
		var v = this.getVideo();
		
		v.addEventListener('loadedmetadata', function(e){
			if (!hasKey("width", _obj.param) || !hasKey("height", _obj.param)){
				_obj.param.width = e.target.videoWidth;
				_obj.param.height = e.target.videoHeight;
				_obj.refreshLayout();
			}
			e.target.removeEventListener('loadedmetadata', e.target.loadedHandler);
			LOG("video.width:"+e.target.videoWidth+"  video.height:"+e.target.videoHeight);
		});
		setInterval(function(){_obj.update()}, 33);
		setTimeout(function(){fadeOut(document.querySelector("div.mtplayer>div.content>div.logo"),10);},2000);

	},
	
	getVideo:function(){
		return document.querySelector("div.mtplayer>div.content>video");
	},
	
	update:function()
	{
		var v = this.getVideo();

		if (!v.duration) return;

		if (v.currentTime != this.savedCurrentTime){
			this.savedCurrentTime = v.currentTime;
			this.currentTimeLabel.innerHTML = this.convFig(v.currentTime);
		}

		if (v.durationTime != this.savedDuration){
			this.savedDuration = v.duration;
			this.durationLabel.innerHTML = this.convFig(v.duration);
		}

		this.savedBufferedPer = v.buffered.end(v.buffered.length-1) / v.duration * 100;
		this.loadedBar.style.width = this.savedBufferedPer + "%";

		this.savedCurrentPer = v.currentTime / v.duration * 100;
		if (this.savedCurrentPer){
			this.progressBar.style.width = this.savedCurrentPer + "%";
		}	

		var sx = Math.floor(v.currentTime / v.duration * this.progressBarWidth - 3);
		this.scrabBar.style.marginLeft = sx + "px";

		if (this.param.autoBar && !this.iPad){
			this.miniBar.querySelector("div.mini-loaded-bar").style.width = this.savedBufferedPer + "%";
			this.miniBar.querySelector("div.mini-progress-bar").style.width = this.savedCurrentPer + "%";
		}

		if (v.currentTime >= v.duration && !v.paused){
			this.playAndPause();
		}

	},


	convFig:function(floatVal)
	{	
		var secs = Math.floor(floatVal);
		var min = Math.floor(secs/60);
		var sec = secs%60;
		return min + ":" + ((sec<10) ? "0" + sec : sec);
	},

	playAndPause:function()
	{
		var v = this.getVideo();
		if (this.isPLAYING) {
			this.player.querySelector("div.content>div.overlay").style.visibility = "visible";
			this.playBtn.querySelector("img").setAttribute("src",this.dir + "playBtn_over.png");
			v.pause();
		}
		else {
			this.player.querySelector("div.content>div.overlay").style.visibility = "hidden";
			if (this.iPad){
				this.player.querySelector("div.controls").style.display = "none";
			}
			this.playBtn.querySelector("img").setAttribute("src",this.dir + "pauseBtn_over.png");
			if (v.currentTime >= v.duration){
				v.currentTime = v.startTime;
			}
			if (this.param.autoBar) {fadeOut(this.controls,10);}
			if (this.param.thumbnail && !this.iPad){
				fadeOut(this.player.querySelector("div.content>div.thumbnail"),10);
			}
			v.play();
		}
		this.isPLAYING = !this.isPLAYING;
		this.hideVolumeArea();
	},

	initInterface:function()
	{
		this.draw();
		this.createVideo();
		this.controls = document.querySelector("div.mtplayer>div.controls");

		if(this.iPad) {
			document.querySelector("div.mtplayer>div.content>div.overlay").style.top = "-10000px";
			this.controls.style.display = "none";
		}
		this.refreshLayout();
		this.initTimeControls();
		this.initVolumeControls();
		this.initBtnActions();
	},

	draw:function()
	{
		document.writeln(
			'<style type="text/css">'+
			'div.mtplayer { width:120px;background-color:#dcdcdc;overflow:hidden;positiion:relative;}'+
			'div.mtplayer > div.content { width:100%; height:80px;background-color:#aaa;}'+
			'div.mtplayer > div.content > div.mini-bar { z-index:4; position:relative; width:100%; background-color:#dcdcdc;height:2px;}'+
			'div.mtplayer > div.content > div.mini-bar > div.mini-loaded-bar {width:0; height:2px;margin:0;background:#999;position:absolute;z-index:5;float:left;}'+
			'div.mtplayer > div.content > div.mini-bar > div.mini-progress-bar {width:0; height:2px;margin:0;background:#666;position:absolute;z-index:6;float:left;}'+
			'div.mtplayer > div.content > div.overlay { z-index:7; position:absolute; background-repeat: no-repeat; background-position: center center; cursor:pointer;}'+
			'div.mtplayer > div.content > div.logo { z-index:3; position:absolute; background-repeat: no-repeat; display:block;}'+
			'div.mtplayer > div.content > div.thumbnail { z-index:2; position:absolute; background-repeat: no-repeat; display:block;}'+
			'div.mtplayer > div.content > video { z-index:1; position:absolute;}'+
			'div.mtplayer > div.controls { width:100%; height:24px;background-color:#dcdcdc;z-index:9;}'+
			'div.mtplayer > div.controls > div.control { position:relative;float:left;}'+
			'div.mtplayer > div.controls > div.playBtn { width:26px; height:24px; cursor:pointer;margin-right:8px;}'+
			'div.mtplayer > div.controls > div.timeSlider { width:72px; height:24px; vertical-align:middle;position:relative;float:left;}'+
			'div.timeSlider > div.seek-bar {width:100%;height:6px; margin:9px 0; background:#c4c4c4; -webkit-border-radius:6px;float:left;}'+
			'div.timeSlider > div.seek-bar > div.loaded-bar {width:0; height:6px;margin:0; background:#999;-webkit-border-radius:6px;float:left;z-index:1;position:absolute;}'+
			'div.timeSlider > div.seek-bar > div.progress-bar {width:0; height:6px;margin:0; background:#666;-webkit-border-radius:6px;float:left;z-index:2;position:absolute;}'+
			'div.timeSlider > div.scrab-bar { width:8px;height:17px;margin-top:4px;margin-left:-3px;z-index:3;float:left;cursor:pointer;position:absolute;}'+
			'div.mtplayer > div.controls > div.timecode { width:81px; height:24px; text-align:center;margin-left:4px;}'+
			'div.mtplayer > div.controls > div.timecode > span { font-size:12px;vertical-align:middle;line-height:24px;font-family:sans-serif;}'+
			'div.mtplayer > div.controls > div.timecode > span.time-separator { padding-left:2px;padding-right:2px;}'+
			'div.mtplayer > div.controls > div.speakerBtn { width:16px; height:24px; cursor:pointer;}'+
			'div.mtplayer > div.controls > div.volumeControl { width:15px; height:24px;positon:relative;background-image:url('+this.dir+'volumeOff.png);}'+
			'div.volumeLevel { width:16px;height:24px;background-image:url('+this.dir+'volumeOn.png);background-position:left center;float:left;}'+
			'div.volumeSliderArea { width:35px;height:65px;top:-65px;left:-17px;position:absolute;z-index:4;opacity:0.0;}'+
			'div.volumeSliderArea > div.volume-slider-bar {width:6px;height:56px; margin:5px 15px; background:#c4c4c4; -webkit-border-radius:6px;float:left;position:relative;}'+
			'div.volumeSliderArea > div.volume-slider-bar > div.volume-on-bar {bottom:0;width:6px; height:0;margin:0; background:#8f8f8f;-webkit-border-radius:6px;z-index:15;position:absolute;}'+
			'div.volumeSliderArea > div.volume-scrab-bar { width:17px;height:8px;margin-left:9px;margin-top:4px;z-index:10;float:left;cursor:pointer;position:absolute;}'+
			'div.mtplayer > div.controls > div.fullscreenBtn { width:24px; height:24px; cursor:pointer;}'+
			'</style>'+
			'<div id="mt_player_normal" class="mtplayer">'+
				'<div class="content">'+
					'<div class="overlay" style="background-image:url('+this.dir+'overlayBtn.png);"></div>'+
					'<div id="logo" class="logo" style="background-image:url('+this.dir+'mt_logo.png);"></div>'+
					(this.isThumbnail && this.iPad ? '': '<div id="thumbnail" class="thumbnail"></div>') +
					'<video id="video" '+ (this.iPad ? 'controls':'') +' autobuffer src="'+this.path+'" '+
					(this.iPad && this.isThumbnail ? 'poster="'+this.param.thumbnail+'"':'') +'></video>'+
					'<div class="mini-bar"><div class="mini-loaded-bar"></div><div class="mini-progress-bar"></div></div>'+
				'</div>'+
				'<div class="controls" style="background-image:url('+this.dir+'controlBarBG.png);">'+
					'<div class="control playBtn fixed">'+
						'<img src="' + this.dir + 'playBtn.png" alt="Play" />'+
					'</div>'+
					'<div class="control timeSlider expandable">'+
						'<div class="seek-bar"><div class="loaded-bar"></div><div class="progress-bar"></div></div>'+
						'<div class="scrab-bar" style="background-image:url('+this.dir+'scrabBar.png)"></div>'+
					'</div>'+
					'<div class="control timecode fixed">'+
						'<span class="current-time">0:00</span><span class="time-separator">/</span><span class="duration">0:00</span>'+
					'</div>'+
					'<div class="control speakerBtn fixed">'+
						'<img src="' + this.dir + 'speakerBtn.png" alt="Speaker" />'+
					'</div>'+
					'<div class="control volumeControl fixed">'+
						'<div class="volumeLevel"></div>'+
						'<div id="volumeSliderArea" class="volumeSliderArea" style="background-image:url('+this.dir+'verticalVolumeSliderBG.png)">'+
							'<div class="volume-slider-bar"><div class="volume-on-bar"></div></div>'+
							'<div class="volume-scrab-bar" style="background-image:url('+this.dir+'volumeScrabBar.png)"></div>'+
						'</div>'+
					'</div>'+
					'<div class="control fullscreenBtn fixed">'+
						'<img src="' + this.dir + 'fullScreenBtn.png" alt="Fullscreen" />'+
					'</div>'+
				'</div>'+
			'</div>'
		);
	},
	
	updateByResize:function(){
		if (this.isFULLWINDOW){
			this.fullwindowOn();
		}
	},
	
	refreshLayout:function()
	{
		if (this.param.width && this.param.height)
		{
			LOG("layoutByParams w:"+this.param.width+" h:"+this.param.height);
			this.updateLayout(this.param.width, this.param.height);
		}
		else 
		{
			LOG("layoutByDefault w:"+MP_DEFAULT_WIDTH+" h:"+MP_DEFAULT_HEIGHT);
			this.updateLayout(MP_DEFAULT_WIDTH, MP_DEFAULT_HEIGHT);
		}
	},

	updateLayout:function(w,h)
	{
		LOG("updateLayout width:"+w+ "  height:"+h + "  allHeight:"+(h + this.controlsHeight));

		this.progressBarWidth = w - 162 - 12; // 8px for leftMargin
		this.player = document.querySelector("div.mtplayer");
		this.miniBar = this.player.querySelector("div.content > div.mini-bar");

		var content = this.player.querySelector("div.content");

		// AUTOBAR & MINI BAR
		if (hasKey("autoBar", this.param)){
			if (this.param.autoBar == true || this.param.autoBar == false){}
			else {this.param.autoBar = this.param.autoBar.toLowerCase() == "yes" ? true:false;}
			if (this.iPad){this.miniBar.style.display = "none";}
		} else {
			this.param.autoBar = false;
			this.miniBar.style.display = "none";
		}
		if (this.param.autoBar){
			LOG("autoBar mode");
			document.querySelector("div.mtplayer > div.controls").style.top = -(this.controlsHeight) + "px";
			document.querySelector("div.mtplayer > div.controls").style.position = "relative";
			this.miniBar.style.top = (h - 2) + "px";
		}

		this.player.style.width = w + "px";
		this.player.style.height = (h + (this.param.autoBar ? 0 : this.controlsHeight)) + "px";
		content.style.height = h + "px";
		content.querySelector("video").style.width = w + "px";
		content.querySelector("video").style.height = h + "px";
		//content.querySelector("video").setAttribute("src",this.path);
			// NOTE:iPad cannnot launch video controls.
		content.querySelector("div.overlay").style.width = w + "px";
		content.querySelector("div.overlay").style.height = h + "px";
		this.player.querySelector("div.controls>div.timeSlider").style.width = this.progressBarWidth + "px";

		// THUMBNAIL
		if (!hasKey("thumbnail", this.param)){
			this.param.thumbnail = false;
		}
		if (this.param.thumbnail && !this.iPad){
			content.querySelector("div.thumbnail").style.width = w + "px";
			content.querySelector("div.thumbnail").style.height = h + "px";
			content.querySelector("div.thumbnail").innerHTML = "<img src="+this.param.thumbnail+" border=0 />";
			content.querySelector("div.thumbnail>img").style.width = w + "px";
			content.querySelector("div.thumbnail>img").style.height = h + "px";
		}

		// LOGO
		var logo = content.querySelector("div.logo");
		logo.style.width = w + "px";
		logo.style.height = h + "px";

		var rightFlg = false;
		var bottomFlg = false;
		if (hasKey("logo", this.param)){
			var ary = this.param.logo.toLowerCase().split(",");
			for (var i=0;i<ary.length;i++){
				if (ary[i] == "right") rightFlg = true;
				else if (ary[i] == "bottom") bottomFlg = true;
			}
		}
		if (rightFlg == true && bottomFlg == false){
			logo.style.backgroundPosition = "right top";
		} else if (rightFlg == false && bottomFlg == true){
			logo.style.backgroundPosition = "left bottom";
		} else if (rightFlg == true && bottomFlg == true){
			logo.style.backgroundPosition = "right bottom";
		} else {
			logo.style.backgroundPosition = "left top";
		}

	},

	initBtnActions:function()
	{
		var obj = this;

		this.player.addEventListener('mouseout',function(){
			obj.hideVolumeArea();
			if (obj.param.autoBar) {fadeOut(obj.controls,10);}
		});

		this.player.addEventListener('mousemove',function(){
			if (obj.param.autoBar) {fadeIn(obj.controls,10);}
		});

		this.playBtn = document.querySelector("div.mtplayer>div.controls>div.playBtn");
		var playBtnImg = this.playBtn.querySelector("img");
		this.playBtn.addEventListener('mouseover', function(){
			if(obj.isPLAYING)
				playBtnImg.setAttribute("src",obj.dir + "pauseBtn_over.png");
			else
				playBtnImg.setAttribute("src",obj.dir + "playBtn_over.png");
		});
		this.playBtn.addEventListener('mousedown', function(){
			if(obj.isPLAYING)
				playBtnImg.setAttribute("src",obj.dir + "pauseBtn_click.png");
			else
				playBtnImg.setAttribute("src",obj.dir + "playBtn_click.png");
		});
		this.playBtn.addEventListener('mouseout', function(){
			if(obj.isPLAYING)
				playBtnImg.setAttribute("src",obj.dir + "pauseBtn.png");
			else
				playBtnImg.setAttribute("src",obj.dir + "playBtn.png");
		});
		this.playBtn.addEventListener('click', function(){
			if(obj.isPLAYING){
				playBtnImg.setAttribute("src",obj.dir + "playBtn.png");
			} else {
				playBtnImg.setAttribute("src",obj.dir + "pauseBtn.png");
			}
			obj.playAndPause();
		});

		this.overlay = document.querySelector("div.mtplayer>div.content>div.overlay");
		this.overlay.addEventListener('mouseover', function(){
			if(!obj.isPLAYING){
				obj.overlay.style.backgroundImage = "url(" + obj.dir + "overlayBtn_over.png)";
			}
			obj.hideVolumeArea();
		});	
		this.overlay.addEventListener('mousedown', function(){
			if(!obj.isPLAYING)
				obj.overlay.style.backgroundImage = "url(" + obj.dir + "overlayBtn_click.png)";
		});
		this.overlay.addEventListener('mouseout', function(){
			if(!obj.isPLAYING)
				obj.overlay.style.backgroundImage = "url(" + obj.dir + "overlayBtn.png)";
		});
		this.overlay.addEventListener('click', function(){
			if(!obj.isPLAYING){
				obj.overlay.style.backgroundImage = "url(" + obj.dir + "overlayBtn.png)";
				playBtnImg.setAttribute("src",obj.dir + "pauseBtn.png");
			} else {
				playBtnImg.setAttribute("src",obj.dir + "playBtn.png");
			}
			obj.playAndPause();
		});

		var v = this.getVideo();
		v.addEventListener('mouseover', function(){
			if (obj.param.autoBar) {fadeIn(obj.controls,10);}
			obj.hideVolumeArea();
		});	
		
		v.addEventListener('mouseout', function(){
			if (obj.param.autoBar) {fadeOut(obj.controls,10);}
		});	

		v.addEventListener('click', function(){
			if(!obj.isPLAYING){
				obj.overlay.style.backgroundImage = "url(" + obj.dir + "overlayBtn.png)";
				playBtnImg.setAttribute("src",obj.dir + "pauseBtn.png");
			} else {
				playBtnImg.setAttribute("src",obj.dir + "playBtn.png");
			}
			obj.playAndPause();
		});

		this.speakerBtn = document.querySelector("div.mtplayer>div.controls>div.speakerBtn");
		var speakerBtnImg = this.speakerBtn.querySelector("img");
		this.speakerBtn.addEventListener('mouseover', function(){
			if(obj.isMUTING){
				speakerBtnImg.setAttribute("src",obj.dir + "speakerMuteBtn_over.png");
			} else {
				speakerBtnImg.setAttribute("src",obj.dir + "speakerBtn_over.png");
			}
			obj.showVolumeArea();
		});
		this.speakerBtn.addEventListener('mousedown', function(){
			if(obj.isMUTING)
				speakerBtnImg.setAttribute("src",obj.dir + "speakerMuteBtn_click.png");
			else
				speakerBtnImg.setAttribute("src",obj.dir + "speakerBtn_click.png");
		});
		this.speakerBtn.addEventListener('mouseout', function(){
			if(obj.isMUTING){
				speakerBtnImg.setAttribute("src",obj.dir + "speakerMuteBtn.png");
			} else {
				speakerBtnImg.setAttribute("src",obj.dir + "speakerBtn.png");
			}
		});
		this.speakerBtn.addEventListener('click', function(){
			if(obj.isMUTING){
				obj.setToSoundMode();
				speakerBtnImg.setAttribute("src",obj.dir + "speakerBtn.png");
			} else {
				obj.setToMuteMode();
				speakerBtnImg.setAttribute("src",obj.dir + "speakerMuteBtn.png");
			}
			obj.updateVolume();
			obj.hideVolumeArea();
		});
	
	
		var fullscreenBtn = document.querySelector("div.mtplayer>div.controls>div.fullscreenBtn");
		var fullscreenBtnImg = fullscreenBtn.querySelector("img");
		fullscreenBtn.addEventListener('mouseover', function(){
			if(obj.isFULLWINDOW)
				fullscreenBtnImg.setAttribute("src",obj.dir + "normalScreenBtn_over.png");
			else
				fullscreenBtnImg.setAttribute("src",obj.dir + "fullScreenBtn_over.png");
			obj.hideVolumeArea();
		});
		fullscreenBtn.addEventListener('mousedown', function(){
			if(obj.isFULLWINDOW)
				fullscreenBtnImg.setAttribute("src",obj.dir + "normalScreenBtn_click.png");
			else
				fullscreenBtnImg.setAttribute("src",obj.dir + "fullScreenBtn_click.png");
		});
		fullscreenBtn.addEventListener('mouseout', function(){
			if(obj.isFULLWINDOW)
				fullscreenBtnImg.setAttribute("src",obj.dir + "normalScreenBtn.png");
			else
				fullscreenBtnImg.setAttribute("src",obj.dir + "fullScreenBtn.png");
		});
		fullscreenBtn.addEventListener('click', function(){
			if(obj.isFULLWINDOW){
				fullscreenBtnImg.setAttribute("src",obj.dir + "fullScreenBtn.png");
				obj.fullwindowOff();
			} else {
				fullscreenBtnImg.setAttribute("src",obj.dir + "normalScreenBtn.png");
				obj.fullwindowOn();
			}
			obj.isFULLWINDOW = !obj.isFULLWINDOW;
		});
	},

	showVolumeArea:function(){
		this.updateVolume();
		var obj = this.volumeArea;
		setTimeout( function(){fadeIn(obj,10);} ,0);
	},

	hideVolumeArea:function(){
		var obj = this.volumeArea;
		setTimeout(function(){fadeOut(obj,10);} ,0);
	},

	setToSoundMode:function(){
		this.savedVolume = this.savedVolume > 0.3 ? this.savedVolume : 1.0;
		this.getVideo().volume = this.savedVolume;
		this.isMUTING = false;
		this.speakerBtn.querySelector("img").setAttribute("src",this.dir + "speakerBtn.png");
	},

	setToMuteMode:function(){
		var v = this.getVideo();
		this.savedVolume = v.volume > 0.3 ? v.volume : 1.0;
		this.getVideo().volume = 0.0;
		this.isMUTING = true;
		this.speakerBtn.querySelector("img").setAttribute("src",this.dir + "speakerMuteBtn.png");
	},
	
	initVolumeControls:function()
	{
		this.volumeArea = document.querySelector("div.mtplayer>div.controls>div.volumeControl>div.volumeSliderArea");
		this.volumeOnBar = this.volumeArea.querySelector("div.volume-slider-bar>div.volume-on-bar");
		this.volumeScrabBar = this.volumeArea.querySelector("div.volumeSliderArea>div.volume-scrab-bar");
		this.volumeLevel = document.querySelector("div.mtplayer>div.controls>div.volumeControl>div.volumeLevel");
		this.volumeControl = document.querySelector("div.mtplayer>div.controls>div.volumeControl");

		var v = this.getVideo();
		var obj = this;

		this.volumeLevel.addEventListener('mouseover', function(e){
			obj.showVolumeArea();
		});

		this.volumeControl.addEventListener('mouseover', function(e){
			obj.showVolumeArea();
		});

		this.volumeScrabBar.addEventListener('mousedown', function(e)
		{
			blockTextSelection();
			
			obj.startVolumeBarDrag(e.pageY);
			document.onmousemove = function(e)
			{
				obj.dragVolumeBarInProgress(e.pageY);
			}
			document.onmouseup = function()
			{
				document.onmousemove = null;
				document.onmouseup = null;
				obj.endVolumeBarDrag();
				unblockTextSelection();
			}
		});

		this.updateVolume();

	},

	updateVolume:function()
	{
		var v = this.getVideo();
		var pos =  this.volumeHeight - (this.volumeHeight * v.volume);
		this.volumeScrabBar.style.marginTop = (pos + 4) + "px";
		this.volumeLevel.style.width = v.volume * 10 + 1;

	},
	
	startVolumeBarDrag:function(startY)
	{
		var v = this.getVideo();
		this.startVolume = v.volume;
		this.startY = startY;
	},

	dragVolumeBarInProgress:function(nextY)
	{
		var v = this.getVideo();
		this.spanY = (nextY - this.startY);
		var nextVolume = this.startVolume - this.spanY / this.volumeHeight;

		if (v.volume == 0 && nextVolume >0){
			this.setToSoundMode();
		}

		if (nextVolume <= 0) {
			v.volume = 0;
			this.setToMuteMode();
		}
		else if (nextVolume > 1) {
			v.volume = 1;
		} 
		else {
			v.volume = nextVolume;
		}
		this.updateVolume();
	},
	
	endVolumeBarDrag:function()
	{
		var v = this.getVideo();
		this.hideVolumeArea();
	},

	setSeekPosition:function(offsetX)
	{
		var v = this.getVideo();
		v.currentTime = offsetX / this.progressBarWidth * v.duration;
		if (v.currentTime < 0) v.currentTime = 0;
		else if (v.currentTime > v.duration ) v.currentTime = v.duration;
	},

	initTimeControls:function()
	{
		var timeSlider = document.querySelector("div.mtplayer>div.controls>div.timeSlider");
		this.seekBar = document.querySelector("div.mtplayer>div.controls>div.timeSlider>div.seek-bar");
		this.progressBar = document.querySelector("div.mtplayer>div.controls>div.timeSlider>div.seek-bar>div.progress-bar");
		this.loadedBar = document.querySelector("div.mtplayer>div.controls>div.timeSlider>div.seek-bar>div.loaded-bar");
		this.scrabBar = document.querySelector("div.mtplayer>div.controls>div.timeSlider>div.scrab-bar");
		this.currentTimeLabel = document.querySelector("div.mtplayer>div.controls>div.timecode>span.current-time");
		this.durationLabel = document.querySelector("div.mtplayer>div.controls>div.timecode>span.duration");
		
		var v = this.getVideo();
		var obj = this;

		this.seekBar.addEventListener('click', function(e){
			obj.setSeekPosition(e.offsetX);
		});

		this.loadedBar.addEventListener('click', function(e){
			obj.setSeekPosition(e.offsetX);
		});

		this.progressBar.addEventListener('click', function(e){
			obj.setSeekPosition(e.offsetX);
		});

		this.scrabBar.addEventListener('mousedown', function(e)
		{
			blockTextSelection();
			var wasPlaying;
			
			if (v.paused) {
				wasPlaying = false;
			} else {
				wasPlaying = true;
				v.pause();
			}

			obj.startDrag(e.pageX);
			var x;
			document.onmousemove = function(e)
			{
				obj.dragInProgress(e.pageX);
			}

			document.onmouseup = function(e)
			{
				document.onmousemove = null;
				document.onmouseup = null;
				if (wasPlaying) {
					v.play();
				}
				unblockTextSelection();
			}
		});

	},

	startDrag:function(startX)
	{
		this.startX = startX;
		this.startTime = this.getVideo().currentTime;
		this.hideVolumeArea();
	},
	
	dragInProgress:function(nextX)
	{
		var v = this.getVideo();
		v.currentTime = (nextX - this.startX) / this.progressBarWidth * v.duration + this.startTime;
		if (v.currentTime < 0) v.currentTime = 0;
		else if (v.currentTime > v.duration) v.currentTime = v.duration;
	},
	
	fullwindowOn:function()
	{
		try { window.scrollbars.visible = false;} catch(e){}
		try { document.body.style.overflow = "hidden";} catch(e){}
		
		var v = this.getVideo();
		
		this.param.offsetWidth = v.offsetWidth;
		this.param.offsetHeight = v.offsetHeight;
		this.param.playerWidth = this.player.style.width;
		this.param.playerHeight = this.player.style.height;
		this.param.playerTop = this.player.top;
		this.param.playerLeft = this.player.left;
		LOG(this.param);
		
		this.updateLayout(window.innerWidth,window.innerHeight - (this.param.autoBar ? 0 : this.controlsHeight));
		LOG("window.innerWidth:" + window.innerWidth+ "  window.innerHeight:" + window.innerHeight);
		this.player.style.width = window.innerWidth + "px";
		this.player.style.height = window.innerHeight + "px";
		this.player.style.position = "fixed";
		this.player.style.top = 0;
		this.player.style.left = 0;
	},
	
	fullwindowOff:function()
	{
		try { window.scrollbars.visible = true;} catch(e){}
		try { document.body.style.overflow = "auto";} catch(e){}

		this.player.style.position = "static";
		this.updateLayout(this.param.width ,this.param.height);
		this.player.style.height = (this.param.height + (this.param.autoBar ? 0 : this.controlsHeight)) + "px";

	}

}

function LOG(s){
	if (_debug){
		try {	
			console.log(s);
		} catch(e){}
	}
}

function fadeIn(el, ts)
{
	el.fadeMode = 1;
	if (!el.style.display || el.style.display == "none"){ el.style.display = "block";}
	if (!el.style.opacity){ el.style.opacity = 0.0;}
	fading(el,ts);
}

function fadeOut(el, ts)
{
	el.fadeMode = -1;
	if (!el.style.opacity == undefined){ el.style.opacity = 1.0;}
	fading(el,ts);
}

function fading(el, ts)
{
	if (el.fadeMode == -1)
	{
		el.style.opacity -= 0.03;
		el.style.filter = "alpha(opacity=" + (el.style.opacity * 100) + ")";
		if (el.style.opacity > 0.0){
			setTimeout(function(){fading(el,ts);}, ts);
		} else {
			el.style.opacity = 0.0;
			el.style.display = "none";
		}
	}
	else if (el.fadeMode == 1)
	{
		el.style.opacity += 0.03;
    el.style.filter = "alpha(opacity=" + (el.style.opacity * 100) + ")";
		if (el.style.opacity < 1.0){
			el.style.opacity = 1;
			setTimeout(function(){fading(el,ts);}, ts);
		} else {
			el.style.opacity = 1.0;
		}
	}
}

function hasKey ( key, search ) {
	if( !search || (search.constructor !== Array && search.constructor !== Object) ){
		return false;
	}
	return key in search;
}


function blockTextSelection(){
  document.body.focus();
  document.onselectstart = function(){ return false;}
}
 
function unblockTextSelection(){
  document.onselectstart = function(){ return true;}
}	

function videoAvailability(file)
{
  if (!(document.createElement('video').canPlayType)) {
		return false;
	}
	var suffix = file.split(".").pop().toLowerCase();
	var ac = getAvailableCodec();
	LOG("available codec: "+ ac + "   currentFileSuffix: "+suffix);
	return ac == suffix ? true : false;

}

function getAvailableCodec()
{
  if (!(document.createElement('video').canPlayType)) {
		return false;
	}
	try {
	  var v = document.createElement("video");
	  if (v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) return "mp4";
		else if (v.canPlayType('video/ogg; codecs="theora, vorbis"')) return "ogg";
		else if (v.canPlayType('video/webm; codecs="vp8, vorbis"')) return "webm";
	} catch(e){
	}
	return false;
}

function showMovie(path, param)
{
	if (!param) param = {};

	/* default params */
	var moviePlayer = "js/movieplayer.swf";
	var mid = "movieplayer"+((new Date())/1000*1000);
	param.autoBar = !hasKey("autoBar",param) ? "yes":param.autoBar;

	/* get script path */
	var scriptAry = document.getElementsByTagName("script");
	for (var i=0;i<scriptAry.length;i++){
		var ary = scriptAry[i].src.split("/");
		if (ary[ary.length-1] == "movieplayer.js"){
			ary.pop();
			ary.push("movieplayer.swf");
			moviePlayer = ary.join("/");
			break;
		}
	}

	/* get file path */
	var currentPathAry = location.href.split("/");
	currentPathAry.pop();
	var currentPath = currentPathAry.join("/");

	var filePathAry = path.split("/");
	var dir = 0;
	for (var i=0;i<filePathAry.length;i++){
		if (filePathAry[i] == "..") {
			dir++;
			currentPathAry.pop();
		}
	}
	LOG("dir:"+dir);
	for (var i=0;i<dir;i++){
		filePathAry.shift();
	}

	path = (filePathAry[0] == "http:" || filePathAry[0] == "https:") ? path : currentPathAry.join("/") + "/" + filePathAry.join("/");
	LOG("filePath:" + path);

	/* check video codec */
	if (videoAvailability(path)){
		var mp = new MTHTML5Player();
		mp.init(path, param);
		return;
	}

	/* set frame height */
	var playerHeight = param.height ? (param.height + MP_CONTROLER_HEIGHT) : MP_DEFAULT_HEIGHT + MP_CONTROLER_HEIGHT;
	if (hasKey("autoBar",param)){
		if (param.autoBar.toLowerCase() == "yes"){
			playerHeight -= MP_CONTROLER_HEIGHT;
		}
	}
	
	/* default params */
	var so = new SWFObject(
		param.src ? param.src : moviePlayer, // flash player
		mid, // unique id
		param.width ? param.width: MP_DEFAULT_WIDTH, // width
		playerHeight,
		"9", // flash version
		param.background ? param.background : "#f2f2f2" // background
	);
	so.addParam("allowFullScreen","true");
	so.addParam("quality","best");
	so.addParam("loop","false");
	so.addParam("scale","noscale");
	so.addParam("allowScriptAccess","always");

	/* flashvars */
	var ary = new Array();
	ary.push("path="+path);

	ary.push("mid="+mid);
	if (param.debug){ary.push("debug="+param.debug);}
	if (param.volumeSlider){ary.push("volumeSlider="+param.volumeSlider);}
	if (param.autoStart){ary.push("autoStart="+param.autoStart);}
	if (param.thumbnail){ary.push("thumbnail="+param.thumbnail);}
	if (param.autoBar){ary.push("autoBar="+param.autoBar);}
	if (param.logo){ary.push("logo="+param.logo);}
	if (!param.width || !param.height){
		ary.push("autosize=true");
	} else {
		ary.push("width="+param.width);
		ary.push("height="+param.height);
	}
	so.addParam("flashvars",ary.join("&"));

	/* finally */
	document.writeln(so.getSWFHTML());

}

function setMovieSize(mid, width, height)
{
	document.getElementById(mid).width = width;
	document.getElementById(mid).height = height;

	if (navigator.appName.indexOf("Microsoft") != -1){
		window[mid].resizeDisplay(width,height);
	} else {
		document[mid].resizeDisplay(width,height);
	}

}


