$(function(){
	if(!($.browser.msie && $.browser.version=="6.0")) return;
	document.execCommand("BackgroundImageCache", false, true);
});
$(function(){
	//底部导航条IE6 fixed
	var fixedBar = $("#foot_bar");
	if(!fixedBar.length) return;
	var	fixedBarH = fixedBar.outerHeight(true),
		winH = $(window).height();
	if($.browser.msie && $.browser.version=="6.0"){
		$(window).scroll(function(){
			fixedBar.css("top",$(this).scrollTop() + winH - fixedBarH);
		}).resize(function(){
			winH = $(this).height();
			$(this).trigger("scroll");
		}).trigger("scroll");
	}

	//底部导航条动画效果
	fixedBar.children().children("ul").lavaLamp({
		fx: "backout", 
		speed: 700,
		click: function(event, menuItem) {}
	});
	
	//底部导航条回到顶部
	var toTop = $("#back-to-top").click(function(){$(window).scrollTop(0)}),
		winHeight = $(window).scroll(function(){
			if($(this).scrollTop() == 0) toTop.hide();
			else toTop.show();
		}).trigger("scroll");

	//底部导航条锚点定位及闪动效果
	var i;
	fixedBar.children().children("ul").children("li").not(".goto_top, .back").children().click(function(e){
		var href = $(this).attr("href");
		if(href.charAt(0)=="#"){
			e.preventDefault();
			var target = $(href);
			$(window).scrollTop(target.position().top - 100);
			function fn(){
				target.flicker(1,2,300);
			}
			window.clearTimeout(i);
			i = window.setTimeout(fn,300);
		}
	});
});

//首页热门推荐tab切换自动播放
function autoTab(){
	var autoTabTimer = window.setInterval(tab_auto,3000),
		autoTabLis = $("#auto_tab").mouseover(function(){
			window.clearInterval(autoTabTimer);
		}).mouseout(function(){
			autoTabTimer = window.setInterval(tab_auto,3000);
		}).children(".tab_nav").children();
	function tab_auto(){
		var i = autoTabLis.filter(".active").index();
		if(i < autoTabLis.length-1) i++;
		else i=0;
		tab(autoTabLis.eq(i));
	}
}

//首页tab切换
function tab(elm){
	if($(elm).hasClass("active")) return;
	$(elm).addClass("active").siblings().removeClass("active").parent().next().children().removeClass("active").eq($(elm).index()).addClass("active");
}

//其他页tab切换
function ulOnMouseOverTab1(_navClass,_contClass,_hdClass){
	var inx = $("#"+_navClass+" li").index($("."+_hdClass));
	$("."+_contClass).hide().eq(inx).show();
	$("#"+_navClass+" li").bind("click", function() {
	$(this).siblings("li").removeClass(_hdClass).end().addClass(_hdClass);
	var index = $("#"+_navClass+" li").index($(this));
	$("."+_contClass).eq(index).siblings("."+_contClass).hide().end().show();
	});
}

//留言评论页tab切换
function ulOnMouseOverTab2(_navClass,_contClass,_hdClass){
	var inx = $("#"+_navClass+" li").index($("."+_hdClass));
	$("."+_contClass).hide().eq(inx).show();
	$("#"+_navClass+" li").bind("click", function() {
	$(this).siblings("li").removeClass(_hdClass).end().addClass(_hdClass);
	var gb_type=$(this).html();
	if(gb_type=="求片"){
		gb_type=0;
	}
	if(gb_type=="建议"){
		gb_type=2;
	}
	if(gb_type=="报错"){
		gb_type=1;
	}
	$("input[name='gb_type']").val(gb_type);
	var index = $("#"+_navClass+" li").index($(this));
	$("."+_contClass).eq(index).siblings("."+_contClass).hide().end().show();
	});
}

//列表页海报模式列表模式之间的切换
function changClass(e,_adClass,_delClass){
	stopDefault(e);
$('#'+_delClass).removeClass('active');
$('#'+_adClass).addClass('active');
$('#vod_list_html').removeClass(_delClass).addClass(_adClass);
}

//cookie操作
var Cookie = {
	set: function(name, value, time){	//过期时间单位小时
		var Days = 365;
		var exp = new Date;
		var expTime = time?(time-0) * 3600 * 1000:Days * 24 * 60 * 60 * 1000;
		exp.setTime(exp.getTime() + expTime);
		document.cookie = name + ("=" + escape(value) + ";expires=" + exp.toUTCString() + ";path=/;");
	},
	get: function(name){
		var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
		if (arr != null) return unescape(arr[2]);
		return null;
	},
	remove: function(name){
		var exp = new Date();
		exp.setTime(exp.getTime() - 1);
		var cval=Cookie.get(name);
		if(cval!=null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
	}
};

//本地存储操作
var LocalMem = {
	 hname:location.hostname?location.hostname:'localStatus',
	 isLocalStorage:window.localStorage?true:false,
	 dataDom:null,
	 initDom:function(){ 
		 if(!this.dataDom){
			 try{
				 this.dataDom = document.createElement('input');
				 this.dataDom.type = 'hidden';
				 this.dataDom.style.display = "none";
				 this.dataDom.addBehavior('#default#userData');
				 document.body.appendChild(this.dataDom);
				 var now = new Date().getTime();
				 var expires = now + 365*24*60*60*1000;
				 this.dataDom.expires = new Date(expires).toUTCString();
			 }catch(ex){
				 return false;
			 }
		 }
		 return true;
	 },
	 set:function(key,value){
		 if(this.isLocalStorage){
			 window.localStorage.setItem(key,value);
		 }else{
			 if(this.initDom()){
				 this.dataDom.load(this.hname);
				 this.dataDom.setAttribute(key,value);
				 this.dataDom.save(this.hname)
			 }
		 }
	 },
	 get:function(key){
		 if(this.isLocalStorage){
			 return window.localStorage.getItem(key);
		 }else{
			 if(this.initDom()){
				 this.dataDom.load(this.hname);
				 return this.dataDom.getAttribute(key);
			 }
		 }
	 },
	 remove:function(key){
		 if(this.isLocalStorage){
			 localStorage.removeItem(key);
		 }else{
			 if(this.initDom()){
				 this.dataDom.load(this.hname);
				 this.dataDom.removeAttribute(key);
				 this.dataDom.save(this.hname)
			 }
		 }
	 }
};

//历史记录操作
var $MH = {
	limit: 5,
	temp: (function(){Cookie.remove("MAX_HISTORY");Cookie.remove("ishistory")})(),		//删除原有cookie
	showHistory: function(ac) {	
		var a = LocalMem.get("MAX_HISTORY"),dc=document.getElementById("MAX_HISTORY"), c = 1 ,dct = document.getElementById("hlist");
		var ishistory = LocalMem.get("ishistory");
		var i, tmp_s;
		var img_li = "";
		if(!dc) return;
		if (ac == 1) {
			if (ishistory != 1) {
				LocalMem.set("ishistory", 1);
				ishistory = 1;
			} else {
				LocalMem.set("ishistory", 0);
				ishistory = 0;
			}
		}
		if (ac == 2) {
			ishistory = 0;
			LocalMem.set("ishistory", 0);
			LocalMem.set("MAX_HISTORY", 'null');
		}
		if(ishistory == 1){
			a = (a !='' && ''+a != 'null') ? eval('('+ a +')')  : {video:[]} ;
			dct.innerHTML = "正在加载...";
			for(var i=0;i<a.video.length;i++){
				if(c>$MH.limit){break;}
				if(a.video[i].link && a.video[i].time && a.video[i].name){				
				img_li += "<p><span class=\"show_more\">" + a.video[i].time + "</span>&nbsp;&nbsp;<a href=\"" + a.video[i].link + "\" target=\"_blank\">" + a.video[i].name + "</a></p>"
					c++;
				}
			}			
			dct.innerHTML = img_li;
		} else {
		}
		if(dc.style.display == "none"){
			dc.style.display = "block";
		}else{
			dc.style.display = "none";
		}
	},
	recordHistory: function(video){
		//if(video.link.indexOf('51rrkan')==-1) return;
		var a = LocalMem.get('MAX_HISTORY'), b = new Array(), c = 1;		
		if(a !='' && a != null && a != 'null'){
			a = eval('('+ a +')');
			for(var i=0;i<a.video.length;i++){
				if(c>$MH.limit){break;}
				if(video.link != a.video[i].link && a.video[i].time){b.push('{"name":"'+ a.video[i].name +'","link":"'+ a.video[i].link +'","time":"'+ a.video[i].time +'","pic":"'+ a.video[i].pic +'"}');c++;}
			}
		}
		b.unshift('{"name":"'+ video.name +'","link":"'+ video.link +'","time":"'+ video.time +'","pic":"'+ video.pic +'"}');
		LocalMem.set("MAX_HISTORY",'{video:['+ b.join(",") +']}');
		b = null;
		a=null;
	}
};

//剧照切换
function photoSlide(){
	var slide = $("#slide"),
		slideNav = slide.find(".slide_nav"),
		slideNavWrap = slideNav.parent(),
		slideCon = slide.find(".slide_con"),
		slideCount = slide.find(".slide_count em"),
		slideLeft = slide.find(".toLeft"),
		slideRight = slide.find(".toRight"),
		slidePrev = slide.find(".perv"),
		slideNext = slide.find(".next");
	var currIndex = 0,
		left = 0,
		length = slideNav.children().length,
		navW = length*(96+10)-10;
	slideNav.width(navW).children().click(function(){
		if($(this).hasClass("active")) return;
		currIndex = $(this).index();
		var pic = slideCon.children().eq(currIndex);
		$(this).addClass("active").siblings().removeClass("active");
		pic.show().siblings().hide();
		slideCount.text(currIndex+1);
		if(!pic.children().attr("src")) setTimeout(function(){pic.children().attr("src",pic.children().data("src"))},1);
	});
	slidePrev.click(function(){
		if(currIndex == 0) return;
		slideNav.children().eq(--currIndex).trigger("click");
		if(currIndex%7==6) slideLeft.trigger("click");
	}).focus(function(){
		this.blur();
	});
	slideNext.click(function(){
		if(currIndex == length-1) return;
		slideNav.children().eq(++currIndex).trigger("click");
		if(currIndex%7==0) slideRight.trigger("click");
	}).focus(function(){
		this.blur();
	});
	slideLeft.click(function(){
		if(left >= 0) return;
		left += 742; 
		slideNav.animate({"left": left},500);
	});
	slideRight.click(function(){
		if(left <= -navW+742) return;
		left -= 742;
		slideNav.animate({"left": left},500);
	});
}

//与朋友分享
function test(){
	if(!videoNote) videoNote="";
	var _url = "《"+videoName+"》"+"-"+videoNote+" 点击在线观看/下载地址："+window.location.href;
    //直接调用p(txt)就行了
    p(_url);
	$("#msg").text("复制成功,您可以发送给您的好友啦！");
	PopUp.open("msg_box",3000);
}
function p(txt){
    if(window.clipboardData){
		window.clipboardData.clearData();
		window.clipboardData.setData("Text", txt + "");
    }else if(navigator.userAgent.indexOf("Opera") != -1){
		window.location = txt;
    }else if (window.netscape){
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		} catch (e) {
			$("#msg").text("被浏览器拒绝！\n您可以在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
			PopUp.open("msg_box");
		}
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip){return;}
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans){return;}
		trans.addDataFlavor('text/unicode');
		var str = new Object();
		var len = new Object();
		str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		var copytext = txt;
		str.data = copytext;
		trans.setTransferData("text/unicode",str,copytext.length * 2);
		var clipid = Components.interfaces.nsIClipboard;
		if (!clip){return false;}
		clip.setData(trans,null,clipid.kGlobalClipboard);
    }
}


//推荐、喜欢
function diggVideo(id,div){
	$.getJSON("/index.php?s=Updown-vod-id-"+id+"-type-up"+"&random="+Math.round(Math.random()*100), function(w){
		if(typeof(w)!="object"){
			try{w = eval("("+w+")");}catch(e){};
		}
		if(w.data==0) alert('(*^__^*) 嘻嘻…… 这么热心啊，您已经顶过了！');
		else{
			$("#" + div).text(parseInt(w.data.split(":")[0]));
			alert('(*^__^*) 嘻嘻……，顶得我真舒服！');
		}
	});
}

//通用fixed固定
function commonFixed(selector,top,offset){
	var el = $("#"+selector);
	if(!el.length) return;
	var	h = top || el.offset().top,
		height = el.outerHeight(true),
		offt = offset || 0,
		isIE6 = $.browser.msie && $.browser.version=="6.0";
	if(isIE6){
		$(window).bind("scroll.fixed",function(){
			if($(this).scrollTop() > h){
				el.css({"position":"relative","top":$(this).scrollTop() - h + offt});
			}else{
				el.css("position","static");
			}
		}).trigger("scroll.fixed");
	}else{
		$(window).bind("scroll.fixed",function(){
			if($(this).scrollTop() > h){
				el.hasClass("fixed")?"":el.addClass("fixed");
			}else{
				el.hasClass("fixed")?el.removeClass("fixed"):"";
			}
		}).trigger("scroll.fixed");
	}
}

//列表页延迟加载
function dlLazyload(){
	var offset = 100,
		box = $("#letter_box"),
		dl = box.children(),
		el = dl.first(),
		winH = $(window).height(),
		elH = box.offset().top;
	$(window).bind("scroll.lazy",function(){
		if($(this).scrollTop() > elH - winH - offset){
			if(!el.length){
				$(this).unbind("scroll.lazy");
				$("#ul").unbind("click");
				return;
			}
			el.show();
			elH = el.offset().top;
			el = el.next();
			$(this).trigger("scroll.lazy");
		}
	}).trigger("scroll.lazy");
	var str = "";
	$("#ul").children().children().each(function(){
		if(!$(this).hasClass("none")) str += $.trim($(this).text());
	}).click(function(e){
		var n = str.indexOf($.trim($(this).text())),
			href = $(this).attr("href");
		if(href){
			e.preventDefault();
			dl.slice(0,n + 1).show();
			window.location.href = href;
		}
	});
}

//插件
$.fn.extend({  
   insertContent : function(myValue, t) {  
	   var $t = $(this)[0];  
	   if (document.selection) {
		   this.focus();  
			var sel = document.selection.createRange();  
			sel.text = myValue;  
			this.focus();  
			sel.moveStart('character', -l);  
			var wee = sel.text.length;  
			if (arguments.length == 2) {  
				var l = $t.value.length;  
				sel.moveEnd("character", wee + t);  
				t <= 0 ? sel.moveStart("character", wee - 2 * t  
						- myValue.length) : sel.moveStart(  
						"character", wee - t - myValue.length);  
				sel.select();  
			}  
		} else if ($t.selectionStart  
				|| $t.selectionStart == '0') {  
			var startPos = $t.selectionStart;  
			var endPos = $t.selectionEnd;  
			var scrollTop = $t.scrollTop;  
			$t.value = $t.value.substring(0, startPos)  
					+ myValue  
					+ $t.value.substring(endPos,  
							$t.value.length);  
			this.focus();  
			$t.selectionStart = startPos + myValue.length;  
			$t.selectionEnd = startPos + myValue.length;  
			$t.scrollTop = scrollTop;  
			if (arguments.length == 2) {  
				$t.setSelectionRange(startPos - t,  
						$t.selectionEnd + t);  
				this.focus();  
			}  
		} else {  
			this.value += myValue;  
			this.focus();  
		}  
	},
	flicker : function(type, times, speed){
		var e = $(this);
		type = type || 0;
		if(type==-1){
			window.clearInterval(flicker_i);
			e.css("color","#fff").fadeIn();
			return;
		}
		times = times || 3;
		speed = speed || 800;
		var t = 1,
			c = e.css("color"),
			d = e.css("background-color"),
			i,
			flag = true;
		f();
		if(t <= times) i = window.setInterval(f,speed);
		if(times == -1) window.flicker_i = window.setInterval(f,speed);
		function f(){
			if(type){
				if(flag){
					e.css("background-color","#619CC9");
					flag = false;
				}else{
					e.css("background-color",d);
					flag = true;
				}
			}else{
				e.fadeOut(300,function(){
					$(this).css("color","#f00");
					if(t == times+1) $(this).css("color",c);
				}).fadeIn(300);	
			}
			if(t++ == times && times != -1) window.clearInterval(i);
		}
	}
});
$.fn.lavaLamp = function(o) {
	o = $.extend({
		fx: "easion",
		speed: 500,
		click: function() {}
	},
	o || {});
	return this.each(function() {			
		var b = $(this),
		noop = function() {},
		$back = $('<li class="back"><div class="left"></div></li>').appendTo(b),
		$li = $("li", this),
		curr = $("li.current", this)[0] || $($li[0]).addClass("current")[0];
		$li.not(".back").hover(function() {
			move(this)
		},
		noop);
		$(this).hover(noop,
		function() {
			move(curr)
		});
		$li.click(function(e) {
			setCurr(this);
			return o.click.apply(this, [e, this])
		});
		setCurr(curr);
		function setCurr(a) {
			$back.css({
				"left": a.offsetLeft + "px",
				"width": a.offsetWidth + "px"
			});
			curr = a
		};
		function move(a) {
			$back.each(function() {
				$.dequeue(this, "fx")
			}).animate({
				width: a.offsetWidth,
				left: a.offsetLeft
			},
			o.speed, o.fx)
		}
	})
};
jQuery.easing.backout = function(x, t, b, c, d) {
	var s = 1.70158;
	return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b
};
//直接调用人气数据
function getVideoHit(vid){	
	$.post("/"+sitePath+"inc/ajax.asp?action=hit&id="+vid,function (obj){														
			var result=obj;
			if(result=="err"){
				set(document.getElementById("hit"),'发生错误');}
			else{				
				set(document.getElementById("hit"),result);}
		}
	);				
}
function set(viewid,v){viewid.innerHTML=v;}

//评分
function markVideo(vd,d,t,s){
	var textStart = Array("很差","较差","差","差","还行","值得一看","好看","好看","非常好看","非常好看");
	var id='BT'+(new Date()).getTime();
	ajax.get("/"+sitePath+"inc/ajax.asp?id="+vd+"&action=videoscore",function (obj){
			var a=obj.responseText
			try{
				a.replace(/\[(\d+),(\d+),(\d+)\]/i,function ($0,d,t,s){
					var x=parseInt(d)+parseInt(t),y=(Math.round(s / x * 10) / 10.0) || 0;
					document.getElementById('MARK_B1').value=x;
					document.getElementById('MARK_B2').value=y;
					document.getElementById('MARK_B3').value=s;
					if(s<=0){
						document.getElementById("filmStarScore").innerHTML = "0<i>.0</i>";
						document.getElementById("start").className = "starB s0";
					}else{
						var ky = y.toString();
						ky = ky.replace(".","<i>.");
						ky = ky + "</i>";
						document.getElementById("filmStarScore").innerHTML = ky;
						document.getElementById("start").className = "starB s" + parseInt(y, 10).toString();
						if(parseInt(y, 10)==0){ var ka = 0; }else{ var ka = parseInt(y, 10)-1; }
						document.getElementById("filmStarScoreTip").innerHTML = textStart[ka]+"(有"+x+"人评分)";
					}
				});
			}catch(ig){}
	});
}
function startm(v){
	var textStart = Array("很差","较差","差","差","还行","值得一看","好看","好看","非常好看","非常好看");
  document.getElementById("filmStarScoreTip").innerHTML = textStart[v-1];
  document.getElementById("start").className = "starB s" + v.toString();
  document.getElementById("filmStarScore").innerHTML = v + "<i>.0</i>"
  
}
function OnStar(mid,v){
	var textStart = Array("很差","较差","差","差","还行","值得一看","好看","好看","非常好看","非常好看");
	ajax.get("/"+sitePath+"inc/ajax.asp?id="+mid+"&action=score&score="+v,function (obj){
		var x=''+obj.responseText;
		if(x.indexOf("havescore")!=-1){
			alert('你已经评过分啦');
		}else{
			var x = parseFloat(document.getElementById("MARK_B1").value);
			var y = parseFloat(document.getElementById("MARK_B2").value);
			var z = parseFloat(document.getElementById("MARK_B3").value);
			var kx = x + 1;//人数
			var kz = z + v;//总分
			var ky = (Math.round(kz / kx * 10) / 10) || 0;
			document.getElementById("MARK_B1").value = kx;
			document.getElementById("MARK_B2").value = ky;
			document.getElementById("MARK_B3").value = kz;
			var kky = ky.toString();
			if(kky.indexOf(".")<0){
				kky = kky + ".0";
			}
			kky = kky.replace(".","<i>.");
			kky = kky + "</i>";
			document.getElementById("filmStarScore").innerHTML = kky;
			document.getElementById("start").className = "starB s" + (parseInt(ky, 10)-1).toString();
			document.getElementById("filmStarScoreTip").innerHTML = "感谢您的参与！";
			alert("已有"+kx+"人参与评分");
			setTimeout(qike,10000); 
		}
	});
}
function qike(){
	var textStart = Array("很差","较差","差","差","还行","值得一看","好看","好看","非常好看","非常好看");
	var x = parseFloat(document.getElementById("MARK_B1").value);
	var y = parseFloat(document.getElementById("MARK_B2").value);
	var z = parseFloat(document.getElementById("MARK_B3").value);
	
	var ky = y.toString();
	if(ky.indexOf(".")<0){
		ky = ky + ".0";
	}
	ky = ky.replace(".","<i>.");
	ky = ky + "</i>";
	document.getElementById("filmStarScore").innerHTML = ky;
	document.getElementById("start").className = "starB s" + parseInt(y, 10).toString();
	if(parseInt(y, 10)>0){
		document.getElementById("filmStarScoreTip").innerHTML = textStart[parseInt(y, 10)-1]; 
	}else{ 
		if(z>0){
			document.getElementById("filmStarScoreTip").innerHTML = textStart[0]; 
		}else{
			document.getElementById("filmStarScoreTip").innerHTML = ""; 
		}
	}	
}

function diggVideo(id,div){
	ajax.get(
		"/"+sitePath+"inc/ajax.asp?id="+id+"&action=digg",function (obj){
			var returnValue=Number(obj.responseText)
			if (!isNaN(returnValue)){set($(div),returnValue);alert('(*^__^*) 嘻嘻……，顶得我真舒服！');}else if(obj.responseText=="err"){alert('顶失败')}else if(obj.responseText=="havescore"){alert('(*^__^*) 嘻嘻…… 这么热心啊，您已经顶过了！')}	
		}
	);
}
function treadVideo(id,div){
	ajax.get("/"+sitePath+"inc/ajax.asp?id="+id+"&action=tread",function (obj){
			var returnValue=Number(obj.responseText)
			if(!isNaN(returnValue)){set($(div),returnValue);alert('小样儿，居然敢踩我！');}else if(obj.responseText=="err"){alert('踩失败')}	else if(obj.responseText=="havescore"){alert('我晕，您已经踩过了，想踩死我啊！')}	
		}
	)
}