//global -----------------------------------------------------------------------------------------

var baseurl = '';

var autoPlayTime = 5; //自动切换时间

var labels = ['MOKO NEWFACE', 'PHOTOGRAPHY', 'MOKO NEWFACE','PHOTOGRAPHY', 'I.P. EXPERIENCE', 'VIDEOCAST', 'MOKO NEWFACE', 'MOKO NEWFACE'];
var coverImgs = ['images/01antonioanuk.jpg', 'images/02monika.jpg', 'images/03wen.jpg','images/04yzx.jpg', 'images/05rehabtrailer.jpg', 'images/06mokoplusdaxpix.jpg', 'images/07mona.jpg', 'images/08xiemeng.jpg'];
var videoURLs = ['../videos/01antonioanuk.mp4', '../videos/02monika.mp4', '../videos/03wen.mp4','../videos/04yzx.mp4', '../videos/05rehabtrailer.mp4', '../videos/06mokoplusdaxpix.mp4', '../videos/07mona.mp4', '../videos/08xiemeng.mp4'];
var captions = [''];

var referrer = document.referrer;
var ua = navigator.userAgent.toLowerCase();
var is_IE = (ua.indexOf('msie') >= 0 && ua.indexOf('opera') < 0);
var is_FF = ua.indexOf('firefox') >= 0;
var is_SFR = ua.indexOf('safari') >= 0;
var is_iPhone = ua.indexOf('iphone')>=0;
var is_apple = (/\((iPhone|iPad|iPod)/i.test(ua));

//nav -----------------------------------------------------------------------------------------

var menuTid;
var autoTid;

initNav();

function initNav(){
	
	/*
	for(var i=0; i<4; i++){
		var menu = $('menu'+(i+1));
		menu.iid = i;
		menu.onmouseover = onMenuOver;
		menu.onmouseout = onMenuOut;
		var subMenu = $('subMenu'+(i+1));
		subMenu.iid = i;
		subMenu.onmouseover = onSubMenuOver;
		subMenu.onmouseout = onSubMenuOut;
	}
	*/
	
	$('arrowL').onclick = function(){turnPage(-1);}
	$('arrowR').onclick = function(){turnPage(1);}
	if(!is_apple){
		$('arrowL').onmouseover = function(){$('arrowImgL').src='images/arrow_left2.png';}
		$('arrowL').onmouseout = function(){$('arrowImgL').src='images/arrow_left.png';}
		$('arrowR').onmouseover = function(){$('arrowImgR').src='images/arrow_right2.png';}
		$('arrowR').onmouseout = function(){$('arrowImgR').src='images/arrow_right.png';}

		//$('arrowL').style.display = 'none';
		//$('arrowR').style.display = 'none';
		//$('slider').onmouseover = function(){$('arrowL').style.display = ''; $('arrowR').style.display = ''; stopAutoPlay();}
		//$('slider').onmouseout = function(){$('arrowL').style.display = 'none'; $('arrowR').style.display = 'none'; startAutoPlay();}
		
		setOpacity($('arrowL'), 0);
		setOpacity($('arrowR'), 0);
		$('slider').onmouseover = function(){fadeIn($('arrowL')); fadeIn($('arrowR')); stopAutoPlay();}
		$('slider').onmouseout = function(){fadeOut($('arrowL')); fadeOut($('arrowR')); startAutoPlay();}
	}
	startAutoPlay();
}

function onMenuOver(){
	//alert(this.iid);
	clearTimeout(menuTid);
	hideAllMenu();
	var id = Number(this.iid)+1;
	showMenu(id);
}

function onMenuOut(){
	menuTid = setTimeout(hideAllMenu, 200);
}

function showMenu(id){
	var subMenu = $('subMenu'+id);
	subMenu.style.display = '';
}

function hideMenu(id){
	var subMenu = $('subMenu'+id);
	subMenu.style.display = 'none';
}

function hideAllMenu(){
	for(var i=0; i<4; i++){
		hideMenu(i+1);
	}
}

function onSubMenuOver(){
	clearTimeout(menuTid);
}

function onSubMenuOut(){
	menuTid = setTimeout(hideAllMenu, 100);
}

function fadeIn(obj){
	var a = obj.a;
	if(a==null) a = 0;
	clearInterval(obj.itv);
	obj.itv = setInterval(fading, 20);
	function fading(){
		a+=20;
		obj.a = a;
		setOpacity(obj,a);
		if(a>=100) clearInterval(obj.itv);
	}
}

function fadeOut(obj){
	var a = obj.a;
	if(a==null) a = 100;
	clearInterval(obj.itv);
	obj.itv = setInterval(fading, 20);
	function fading(){
		a-=20;
		obj.a = a;
		setOpacity(obj,a);
		if(a<=0) clearInterval(obj.itv);
	}
}

function setOpacity(obj, a){
	obj.style.filter = 'alpha(opacity='+a+')';
	obj.style.opacity = a/100;
	obj.style.mozOpacity = a/100;   
}

//video -----------------------------------------------------------------------------------------

var pId = 1;
var maxId = 8;
var tox;
var tcx;
var dox;
var iid;
var videoPlayed = new Array(); //[0,0,0];
var playing = false;

initVideo();

function initVideo(){
	for(var i=0; i<maxId; i++) videoPlayed[i] = 0;
	$('cont').style.width = 800*maxId+'px';
	for(var i=0; i<maxId; i++){
		$('cover'+(i+1)+'_div').innerHTML = '<img src="'+baseurl+coverImgs[i]+'" onclick="playVideo('+(i+1)+');" />';
		if(is_apple){
			//$('video'+(i+1)+'_div').innerHTML = '<video id="video'+(i+1)+'" width="800" height="450" controls="controls"><source src="'+baseurl+videoURLs[i]'" type="video/mp4"></video>'; //html5
		}else{
			/*
			var id = +1;
			var flash = new SWFObject("swf/videoplayer.swf", "video", "800", "450", "9", "#000000");
			flash.addParam("wmode", "transparent");
			flash.addParam("allowfullscreen", "true");
			flash.addVariable("url", baseurl+'../'+videoURLs[id-1]);
			flash.addVariable("autoplay", 1);
			flash.write("video"+id+"_div");
			*/
		}
	}
	//$('cover1_div').onclick = function(){playVideo(1);}

	try{
		addEventListener("load",function() {setTimeout(hideURLbar, 0);}, false);
	}catch(e){}
	function hideURLbar(){
		window.scrollTo(0, 0);
	}
}

/*
//debug
alert(is_IE+','+is_FF+','+is_SFR+','+is_iPhone+','+is_apple);
alert('supports_h264_baseline_video: '+supports_h264_baseline_video());
if(supports_h264_baseline_video()){
	alert('video/mp4: '+v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'));
	alert('video/ogg: '+v.canPlayType('video/ogg; codecs="theora, vorbis"'));
	alert('video/webm: '+v.canPlayType('video/webm; codecs="vp8, vorbis"'));
}
*/


function $(id){ return document.getElementById(id); }
function html(id, html){ $(id).innerHTML = html; }
function css(id, style){ $(id).style.cssText += ';'+style; }
function anim(id, transform, opacity, dur){
	css(id, '-webkit-transition:-webkit-transform'+
	',opacity '+(dur||0.5)+'s,'+(dur||0.5)+'s;-webkit-transform:'+
	transform+';opacity:'+(1||opacity));
}

function playVideo(id){
	stopAutoPlay();
	//autoTurn = function(){};
	stopVideo();
	playing = true;
	if(is_apple){ //html5
		if(videoPlayed[id-1]==0){
			var v = document.createElement("video");
			v.id = 'video'+id;
			v.width = 800;
			v.height = 450;
			v.controls = 'controls';
			v.autoplay = 'autoplay';
			//v.zIndex = 1;
			var s = document.createElement("source");
			s.src = baseurl+videoURLs[id-1];
			s.type = 'video/mp4';
			v.appendChild(s);
			$('video'+id+'_div').appendChild(v);
			v.addEventListener('ended', onVideoEnd, true);
			v.addEventListener('playing', onVideoPlaying, true);
			v.play();
		}else{
			$('video'+id+'_div').innerHTML = '<video id="video'+id+'" width="800" height="450" controls="controls" autoplay="autoplay"><source src="'+baseurl+videoURLs[id-1]+'" type="video/mp4"></video>';
		}
		videoPlayed[id-1] = 1;
		$('video'+id+'_div').style.visibility = 'visible';
		showLabel('LOADING');
	}else{ //flash
		var flash = new SWFObject("swf/videoplayer.swf", "video", "800", "450", "9", "#000000");
		flash.addParam("wmode", "transparent");
		flash.addParam("allowfullscreen", "true");
		flash.addVariable("url", baseurl+videoURLs[id-1]);
		flash.addVariable("autoplay", 1);
		flash.addVariable("captions", captions[id-1]);
		flash.write("video"+id+"_div");
		$('video'+id+'_div').style.visibility = 'visible';
		$('cover'+id+'_div').style.visibility = 'hidden';
		showLabel('LOADING');
		//$("cover"+id+"_div").style.visibility = 'hidden';
	}
}

function stopVideo(){
	playing = false;
	for(var i=0; i<maxId; i++){
		try{$('video'+(i+1)).pause();}catch(e){}
		$('video'+(i+1)+'_div').innerHTML = '';
		$('video'+(i+1)+'_div').style.visibility = 'hidden';
		$('cover'+(i+1)+'_div').style.visibility = 'visible';
	}
	showLabel(labels[pId]);
}

function onVideoEnd(){
	playing = false;
	for(var i=0; i<maxId; i++){
		$('video'+(i+1)+'_div').innerHTML = '';
		$('video'+(i+1)+'_div').style.visibility = 'hidden';
		$('cover'+(i+1)+'_div').style.visibility = 'visible';
	}
	showLabel(labels[pId-1]);
	startAutoPlay();
}

function onVideoPlaying(){
	showLabel('PLAYING');
	playing = true;
}

function onVideoBuffering(){
	showLabel('LOADING');
}

//slider -----------------------------------------------------------------------------------------

initSlider();

function initSlider(){

	if(is_apple) $('sliderLabelTxt').style.marginTop = 6+'px';
	showLabel(labels[pId]);
	updateDots();

	if(is_apple){

		$('content').ontouchstart = function(e){
			stopAutoPlay();
			clearInterval(iid);
			if(e.touches.length == 1){
				var touch = e.touches[0];
				tox = tcx = touch.screenX;
				var node = $('cont');
				dox = parseInt(node.style.left);
			}
		}

		$('content').ontouchmove = function(e){
			/*
			clientX: touch事件相对于视图（viewport）的X轴坐标（不包括滚动位移）
			clientY: touch事件相对于视图（viewport）的Y轴坐标（不包括滚动位移）
			screenX: 相对于屏幕
			screenY: 相对于屏幕
			pageX: 相对于整个页面（包括滚动）
			pageY: 相对于整个页面（包括滚动）
			target: touch事件所发生的节点
			identifier: 一个id号，为每一个touch事件提供唯一标识
			*/
			e.preventDefault();
			if(e.touches.length == 1){ // 仅处理一根手指
				//var node = touch.target; // 寻找拖放开始时的节点
				var node = $('cont');
				var touch = e.touches[0]; // 获取#1号手指的信息
				//$('trace').innerHTML = touch.screenX;
				tcx = touch.screenX;
				node.style.left = dox + (touch.screenX-tox) + "px";
			}
		}

		$('content').ontouchend = function(e){
			var e = event || window.event; 
			//e.preventDefault && e.preventDefault(); 
			//e.stopPropagation && e.stopPropagation(); 
			//e.cancelBubble = true; 
			//e.returnValue = false; 
			//return false; 
			//var x = dox + (tcx-tox);
			//$('trace').innerHTML = 'END'+dox+','+tcx+','+tox+','+x;
			if(Math.abs(tcx-tox)>100){
				if(tcx<tox){ //next
					if(pId<maxId) pId++;
				}else if(tcx>tox){ //prev
					if(pId>1) pId--;
				}
			}
			gotoPhoto(pId);
		}

	}

}

function gotoPhoto(id, play){
	var node = $('cont');
	var x = -800*(id-1);
	var nowX =  parseInt(node.style.left);
	//$('trace').innerHTML = 'x: '+x;
	clearInterval(iid);
	iid = setInterval(go, 10);
	function go(){
		//$('trace').innerHTML = nowX+','+x+','+(nowX-x)*.2;
		if(Math.abs(nowX-x)<1){
			clearInterval(iid);
			node.style.left = x+'px';
			if(play){
				playVideo(pId);
			}
		}else{
			nowX = (nowX-(nowX-x)*.3);
			node.style.left = nowX + 'px';
		}
	}
	updateDots();
}

function turnPage(dir){
	playing = false;
	stopAutoPlay();
	if(dir==-1){
		if(pId>1) pId--;
		gotoPhoto(pId);
	}else if(dir==1){
		if(pId<maxId) pId++;
		gotoPhoto(pId);
	}else if(dir==2){
		if(pId<maxId){
			pId++;
			gotoPhoto(pId, true);
		}else{
			pId = 1;
			gotoPhoto(pId);
		}
	}
}


function startAutoPlay(){
	stopAutoPlay();
	autoTid = setInterval(autoTurn, 1000*autoPlayTime);
}

function stopAutoPlay(){
	clearInterval(autoTid);
}

function autoTurn(){
	if(playing) return;
	if(pId<maxId){
		pId++;
	}else{
		pId = 1;
	}
	gotoPhoto(pId);
}

function updateDots(){
	stopVideo();
	for(var i=0; i<maxId; i++){
		var dot = $('dot'+(i+1));
		dot.src = i+1==pId?'images/dot1.png':'images/dot0.png';
	}
	if(pId==1){
		$('arrowImgL').style.display = 'none';
		$('arrowImgR').style.display = '';
		$('arrowL').style.display = 'none';
		$('arrowR').style.display = '';
	}else if(pId==maxId){
		$('arrowImgL').style.display = '';
		$('arrowImgR').style.display = 'none';
		$('arrowL').style.display = '';
		$('arrowR').style.display = 'none';
	}else{
		$('arrowImgL').style.display = '';
		$('arrowImgR').style.display = '';
		$('arrowL').style.display = '';
		$('arrowR').style.display = '';
	}
	showLabel(labels[pId-1]);
}

function showLabel(txt){
	$('sliderLabelTxt').innerHTML = txt;
}

function startDrag(obj, e, limit){
	if(!e) e=window.event;
	var x=parseInt(obj.style.left);
	var y=parseInt(obj.style.top);

	var x_=e.clientX-x;
	var y_=e.clientY-y;

	if(document.addEventListener){
		document.addEventListener('mousemove', inFmove, true);
		document.addEventListener('mouseup', inFup, true);
	} else if(document.attachEvent){
		document.attachEvent('onmousemove', inFmove);
		document.attachEvent('onmouseup', inFup);
	}

	inFstop(e);    
	inFabort(e)

	function inFmove(e){
		var evt;
		if(!e)e=window.event;

		if(limit){
			var op=obj.parentNode;
			var opX=parseInt(op.style.left);
			var opY=parseInt(op.style.top);
			
			if((e.clientX-x_)<0) return false;
			else if((e.clientX-x_+obj.offsetWidth+opX)>(opX+op.offsetWidth)) return false;
			
			if(e.clientY-y_<0) return false;
			else if((e.clientY-y_+obj.offsetHeight+opY)>(opY+op.offsetHeight)) return false;
		}

		obj.style.left=e.clientX-x_+'px';
		obj.style.top=e.clientY-y_+'px';

		//$('trace').innerHTML = e.clientX+','+obj.style.left;

		inFstop(e);
	}

	function inFup(e){
		var evt;
		if(!e)e=window.event;
		
		if(document.removeEventListener){
			document.removeEventListener('mousemove', inFmove, true);
			document.removeEventListener('mouseup', inFup, true);
		} else if(document.detachEvent){
			document.detachEvent('onmousemove', inFmove);
			document.detachEvent('onmouseup', inFup);
		}
		
		inFstop(e);
	}

	function inFstop(e){
		if(e.stopPropagation) return e.stopPropagation();
		else return e.cancelBubble=true;            
	}

	function inFabort(e){
		if(e.preventDefault) return e.preventDefault();
		else return e.returnValue=false;
	}

}

function supports_video() {
	return !!document.createElement('video').canPlayType;
}

function supports_h264_baseline_video(){   
	if(!supports_video()){ return false; }   
	var v = document.createElement("video");   
	return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');   
}

function addEvent(o, e, f) {
	var r = false;
	if (window.addEventListener) {
		o.addEventListener(e, f, false);
		r = true;
	} else if (window.attachEvent) {
		r = o.attachEvent('on' + e, f);
	}
	return r;
}
