﻿/*
 * Pomoho UI - Space
 *
 * Copyright (c) 2007 sorrycc@gmail.com (pomoho.com)
 * Date: 2007-10-22
 */

Pui.video = {
	init: function() {
		this.zz();
		//this.emotion();
		//this.commentReply();
	},
	hideIntro: function() {
		var str = $('#Layout_1 .vp .v_intro').text();
	},
	zz: function(mv) {
		var urlParm = "";
		var htmlcode = '';		
		//var htmlcode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="450" height="387" id="object"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="movie" value="http://video.pomoho.com/swf/out_player.swf?flvid='+flvid+'" /><embed src="http://video.pomoho.com/swf/out_player.swf?flvid='+flvid+'" quality="high" width="450" height="387" allowScriptAccess="always"/></object>';
		var s = '';
		s += '<div id="ZZ" style="display:none;">';
		s += '	<div class="s1">';
		if (mv) {
			urlParm = "mvid";
			htmlcode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="450" height="387" id="object"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="movie" value="http://video.pomoho.com/swf/mv_out_player.swf?mvid='+flvid+'" /><embed src="http://video.pomoho.com/swf/mv_out_player.swf?mvid='+flvid+'" quality="high" width="450" height="387" allowScriptAccess="always"/></object>';
			s += '		此节目地址（URL）<br /><input type="text" class="url" value="http://video.pomoho.com/mv/'+flvid+'.shtml" /><br />';
			s += '		把播放器显示到个人空间或Blog<br /><input type="text" class="url" value="http://video.pomoho.com/swf/mv_out_player.swf?mvid='+flvid+'" /><br />';
			s += '		HTML代码,适用于个人空间（或其他类型的Blog）<br /><input type="text" class="url" value="" /><br />';
			s += '		BBS代码<br /><input type="text" class="url" value="[flash]http://video.pomoho.com/swf/mv_out_player.swf?mvid='+flvid+'[/flash]" />';
		} else {
			urlParm = "flvid";
			htmlcode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="450" height="387" id="object"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="movie" value="http://video.pomoho.com/swf/out_player.swf?flvid='+flvid+'" /><embed src="http://video.pomoho.com/swf/out_player.swf?flvid='+flvid+'" quality="high" width="450" height="387" allowScriptAccess="always"/></object>';
			if (String(window.location).match(/http:\/\/video\.dvod.*/)) {
				s += '		此节目地址（URL）<br /><input type="text" class="url" value="http://video.dvod.com.cn/news/'+flvid+'.shtml" /><br />';
			} else {
				s += '		此节目地址（URL）<br /><input type="text" class="url" value="http://video.pomoho.com/ent/'+flvid+'.shtml" /><br />';
			}
			s += '		把播放器显示到个人空间或Blog<br /><input type="text" class="url" value="http://video.pomoho.com/swf/out_player.swf?flvid='+flvid+'" /><br />';
			s += '		HTML代码,适用于个人空间（或其他类型的Blog）<br /><input type="text" class="url" value="" /><br />';
			s += '		BBS代码<br /><input type="text" class="url" value="[flash]http://video.pomoho.com/swf/out_player.swf?flvid='+flvid+'[/flash]" />';
		}
		s += '	</div>';
		s += '	<div class="s2">';
		s += '		添加到';
		s += '		<div>';
		s += '			<a href="http://online.pomoho.com/share/xcbbs.html?'+urlParm+'='+flvid+'" class="xc" target="_blank">xcbbs</a>';
		s += '			<a href="http://online.pomoho.com/share/wumin.html?'+urlParm+'='+flvid+'" class="wretch" target="_blank">wumin</a>';
		s += '			<a href="http://online.pomoho.com/share/tianya.html?'+urlParm+'='+flvid+'" class="tianya" target="_blank">tianya</a>';
		s += '			<a href="http://online.pomoho.com/share/sinabk.html?'+urlParm+'='+flvid+'" class="sina" target="_blank">sinabk</a>';
		s += '			<a href="http://online.pomoho.com/share/qqzone.html?'+urlParm+'='+flvid+'" class="qq" target="_blank">qqzone</a>';
		s += '			<a href="http://online.pomoho.com/share/pcpop.html?'+urlParm+'='+flvid+'" class="pcpop" target="_blank">pcpop</a>';
		s += '			<a href="http://online.pomoho.com/share/msn.html?'+urlParm+'='+flvid+'" class="msn" target="_blank">msn</a>';
		s += '			<a href="http://online.pomoho.com/share/MOP.html?'+urlParm+'='+flvid+'" class="mop" target="_blank">MOP</a>';
		s += '			<a href="http://online.pomoho.com/share/hexubk.html?'+urlParm+'='+flvid+'" class="hx" target="_blank">hexubk</a>';
		s += '			<a href="http://online.pomoho.com/share/boke.html?'+urlParm+'='+flvid+'" class="booke" target="_blank">boke</a>';
		s += '			<a href="http://online.pomoho.com/share/Blogcn.html?'+urlParm+'='+flvid+'" class="blogcn" target="_blank">Blogcn</a>';
		s += '			<a href="http://online.pomoho.com/share/51bk.html?'+urlParm+'='+flvid+'" class="fiveone" target="_blank">51bk</a>';
		s += '		</div>';
		s += '	</div>';
		s += '  <p><a href="" onclick="$(\'#ZZ\').slideUp();return false;">关闭</a></p>';
		s += '</div>';
		var vPath = '#Layout_1 .vp .handle';
		if (String(window.location).match(/http:\/\/home.*/)) {
			vPath = '#VideoPlayer .vp .handle';
		}
		$(vPath).after(s).find('.s4').click(function(){
			$('#ZZ').slideToggle();
			this.blur();
			return false;
		});
		$('#ZZ .url').eq(2).attr('value', htmlcode).end().hover(function(){
			$(this).select();
		}, function(){
			$(this).blur();	
		});
		
		// 临时用
		// 彩信到手机->举报该视频 By SMbey0nd @ 2008-9-28 11:39:00
		if (String(window.location).match(/http:\/\/home.*/)) {
			$('#VideoPlayer .vp .handle .s1').attr({'href':'http://www.pomoho.com/customer/report.aspx', 'target':'_blank'}).text('举报该视频'); //彩信到手机 - 举报该视频
			var _t_href = $('#VideoPlayer .vp .handle .s2').attr('href');
			$('#VideoPlayer .vp .handle .s2').attr('href', _t_href.replace(/member=[^&]*/,'userid='+_user.uid));
		} else {
			$('#Layout_1 .vp .handle .s1').attr({'href':'http://www.pomoho.com/customer/report.aspx', 'target':'_blank'}).text('举报该视频'); //彩信到手机 - 举报该视频
			var _t_href = $('#Layout_1 .vp .handle .s2').attr('href');
			$('#Layout_1 .vp .handle .s2').attr('href', _t_href.replace(/member=[^&]*/,'userid='+_user.uid));
			//$('#Layout_1 .vp .handle .s2').attr('href', _t_href+'&userid='+_user.uid);
		}
	},
	hideComment: function(num) {
		if (String(window.location).match(/http:\/\/home.*/)) {
			$('#Comment .mDocument').filter(':gt(19)').hide();
		} else {
			$('#Comment .mDocument').filter(':gt(19)').hide();
		}
		$('#Comment h3 span').html(20);
	},
	emotion: function() {
		var emotionID = 1;
		$('#Comment .emotion').find('.l').click(function() {
			if (emotionID >= 2) {
				$('#emotionBox').animate({left: -(450*(emotionID-2))}, 1000);
				if (emotionID == 2) {
					$('#Comment .l').removeClass('l_b').attr('title', '左边没有了');
				} else if (emotionID == 4) {
					$('#Comment .r').addClass('r_b').attr('title', '向右翻');
				}
				emotionID --;
			}
			this.blur();
			return false;
		}).end().find('.r').click(function() {
			if (emotionID <= 3) {

				$('#emotionBox').animate({left: -(450*emotionID)}, 1000);
				if (emotionID == 1) {
					$('#Comment .l').addClass('l_b').attr('title', '向左翻');
				} else if (emotionID == 3) {
					$('#Comment .r').removeClass('r_b').attr('title', '右边没有了');
				}
				emotionID ++;
			}
			this.blur();
			return false;
		}).end().find('div a').each(function() {
			$(this).click(function(){
				var tmp = $('#Comment textarea').val() + $(this).find('img').attr('src').replace(/.+\/(em\d+)\.gif/g, '[$1]');
				$('#Comment textarea').val(tmp);
				return false;
			});
		});

		//+zhuxf 2008-3-4 添加验证码代码+
		SetValidCodeImg();
	},
	emotionWR: function() {
		//+zhuxf 2008-3-4 添加验证码代码+
		SetValidCodeImg();
		var s = '';
		s += '<div style="position:relative;width:450px;height:60px;overflow:hidden;margin:0 auto;"><div id="emotionBox" style="position:absolute;left:0;top:0;width:1800px;">';
		var l = 'http://static.pomoho.com/images/em/';
		//var l = 'http://127.0.0.1/images/emotion/';
		var alt = ['黑星打','大','泡','蹦','继续','狂','黑星殴','吹','捅','被殴','飞','嘘','赖','顶','变','滚球','生','膜拜','转','口','KI','鬼','抓狂','扯','流','闭嘴','HI','可爱','摇','躲','多','吉'];		
		for(var i=1; i<=4; i++) {
			s += '<div style="width:450px;float:left;text-align:center;">';
			for(var j=(i-1)*8+1; j<=i*8; j++) {
				if(j<=32) {
					s += '<a href="" title="'+alt[j-1]+'"><img src="'+l+'em'+j+'.gif" height="50" /></a>';
				}
			}
			s += '</div>';
		}
		s += '</div></div>';
		s += '<a href="" class="l" title="左边没有了">向左翻</a><a href="" class="r r_b" title="向右翻">向右翻</a>';
		document.write(s);
		var c = $('.l_honor span').text();
		if($.trim(c) == '?'){//临时 过滤问号 by SMbey0nd @ 2008-10-28 15:49:20
			$('.l_honor span').text('无');
		}
	},
	commentReply: function() {
		timer_comment = null;
		$('#Comment input[type=submit]').click(function(){	
			
			textarea = $('#Comment textarea');
			if ($.trim(textarea.val()) == '') {
				alert('评论内容不可为空！');
				textarea.focus();
				return;
			}
			var sValidCode = "";
			if(document.getElementById("tb_validcode") != null)
			{
				sValidCode = document.getElementById("tb_validcode").value;
				if ($.trim(sValidCode) == '') {
					alert('验证码不可为空！');
					return;
				}
			}
			
			/*var d = new Date();
			if(timer_comment != null) {
				if((Date.parse(d.toUTCString())-10000) < timer_comment) {
					alert('评论间隔不得少于10秒！');
					textarea.focus();
					return;
				}
			}
			timer_comment = Date.parse(d.toUTCString());*/
			var scontent = textarea.val().replace("<", "&lt;").replace(">", "&gt;").replace("&", "<--@@-@@-->");
			scontent = escape(scontent);
			if ($('body').attr('id') == 'SpaceAlbum_Detail') {
				Pui.loadScript("http://www.pomoho.com/do/video/dealajaxdata.aspx?itype=6&imdbid=" + imgid + "&content=" + scontent + "&validcode=" + sValidCode, {random:true});
			} else {
				Pui.loadScript("http://www.pomoho.com/do/video/dealajaxdata.aspx?itype=1&imdbid=" + flvid + "&content=" + scontent + "&validcode=" + sValidCode, {random:true});
			}
			//window.location = String(window.location).replace(/#Comment/g, '') + '#Comment';
			//scrollTo "Comment"
			var ct = Pui.pos.elementTop(document.getElementById('Comment'));
			window.scrollTo(0, ct-30);
			$('#Comment .cl, #Comment .cc').fadeTo('slow', 0.3);
			this.blur();
			setTimeout("Pui.video.commentReplyFill()", 1000);
			if ($('body').attr('id') != 'SpaceAlbum_Detail') {
				GetValidCodeImg();
			}
		});
	},
	commentReplyFill: function() {
		var c = textarea.val().replace(/\[em(\d+)\]/g, "<img src='http://static.pomoho.com/images/em/em$1.gif' />");
		var u = _is_login ? '<a href="javascript:;">'+_user.nick+'</a>' : '游客';
		var s = '';
		s += '<div class="mDocument" style="_width:100%;">';
		s += '	<div class="photo"><img src="http://static.pomoho.com/static/images/photo_68.gif" alt="" /></div>';
		s += '	<div class="detail">';
		s += '		<span class="n_user">'+u+'</span>';
		s += '		<p class="text">'+c+'</p>';
		s += '	</div>';
		s += '	<div class="handle">';
		s += '		<span class="t_release">'+Pui.ui.gettime()+'</span>';
		s += '	</div>';
		s += '</div>';
		if($('#Comment h3').length == 0) {
			if (String(window.location).match(/http:\/\/home.*/)) {
				$('<p class="cc"><a href="javascript:;">查看全部</a>共<span>1</span>条评论</p>').prependTo('#span_video_review');
				$('<div class="cl">'+s+'</div>').prependTo('#span_video_review');
				$('<h3>对该视频的评论</h3>').prependTo('#span_video_review');
			} else {
				$('<p class="cc"><a href="javascript:;">查看全部</a>共<span>1</span>条评论</p>').prependTo('#Comment');
				$('<div class="cl">'+s+'</div>').prependTo('#Comment');
				$('<h3>对该视频的评论</h3>').prependTo('#Comment');
			}
		} else {
			$('#Comment .cl').prepend(s);
			$('#Comment .cl, #Comment .cc').fadeTo('slow', 1);
		}
		textarea.attr('value', '').focus();
	},
	collect: function() {
		Pui.loadScript("http://www.pomoho.com/do/video/dealajaxdata.aspx?itype=2&imdbid=" + flvid);
	},
	delblog: function(blogid) {
		if (window.confirm("确认要删除该条评论吗?")) { 	
			if ($('body').attr('id') == 'SpaceAlbum_Detail') {
				Pui.loadScript("http://www.pomoho.com/do/video/dealajaxdata.aspx?itype=4&blogid=" + blogid+"&imdbid=" + imgid);
			} else{
				Pui.loadScript("http://www.pomoho.com/do/video/dealajaxdata.aspx?itype=4&blogid=" + blogid+"&imdbid=" + flvid);
			}
		}
	},
	quote: function(bid) {
		var re_q_txt = document.getElementById("re_q_"+bid).value;
		document.getElementById("post_content").value = "[quote]"+re_q_txt+"[/quote]";
		$('#Comment textarea').focus();
	}
};

$.fn.currentVideo = function(option) {
	return this.find(option.c).each(function(){
		if($(this).find('.title a').attr('href').indexOf(flvid) != -1) {
			$(this).addClass('ac');
		}
	});
}


//by zhuxf 2008-3-3 评论验证码  type 1 - 视频 2 - 用户  3 - 专题
var ValidCodeURL = "http://www.pomoho.com/do/video/ValidCode.aspx?type=1";
//var ValidCodeURL = "http://192.168.1.222/pmhdo/video/ValidCode.aspx?type=1";
function GetValidCodeImg()
{
	if(typeof(imgid)!= "undefined")
	{
			document.getElementById("validcode").src = ValidCodeURL + "&objid=" + imgid + "&ran=" + Math.random();
	}
	else
	{
			document.getElementById("validcode").src = ValidCodeURL + "&objid=" + flvid + "&ran=" + Math.random();
	}
}
function SetValidCodeImg()
{ 
	var ValidCodeHtml =  '';
	if(typeof(imgid)
 != "undefined")
	{
		ValidCodeHtml = '请输入验证码&nbsp;&nbsp;<input id="tb_validcode" type="text" style="width:60px; border:1px #7B9EBD solid;margin:0 5px 0 0;"><a href="javascript:GetValidCodeImg();" title="看不清楚？请点击刷新验证码！" style="position:relative;top:6px;" ><img id="validcode" border=0  width="60" height="20" src="'+ValidCodeURL + "&objid=" + imgid +'"></a>';
	}
	else
	{
		ValidCodeHtml = '请输入验证码&nbsp;&nbsp;<input id="tb_validcode" type="text" style="width:60px; border:1px #7B9EBD solid;margin:0 5px 0 0;"><a href="javascript:GetValidCodeImg();" title="看不清楚？请点击刷新验证码！" style="position:relative;top:6px;" ><img id="validcode" border=0  width="60" height="20" src="'+ValidCodeURL + "&objid=" + flvid +'"></a>';	
	}
 	
	var s = $('#Comment .commentAdd .form .submit').html();
	$('#Comment .commentAdd .form .submit').html(ValidCodeHtml + s);
}
function SendCallBack(v,sv)
{
	if(v == 0)
	{
		alert("您的验证码错误！");
	}
	if(v == -1)
	{
		alert("您的验证码已失效。请点击验证码图片，重新获取验证码！");
	}
	setTimeout("$('#Comment .mDocument').eq(0).remove();", 1000);
	setTimeout("textarea.attr('value', '"+sv+"').focus();", 1000);
	
}
function SendDoing()
			{	
				var n = Pui.cookie('LoginInfo');
				if(n)
				{
					var arr=n.split('$***$');
					var userid = arr[0].replace('LoginInfo=','');
					var content = $.trim($('#span_video_play h2').html());
					var videourl = document.location.href;
					var content = escape(content);
					var url = baseurl+"space/mydoingajax.aspx?opreatetype=add&writecontent=" +content+"&userid="+userid+"&videourl="+videourl;
					Pui.loadScript(url, {random:false});
				}
				else
				{
					alert("请先登录！");
				}
			}
			
//图片播放
var addGallery={
	setting:{href:window.location.toString(),
	thumb_opacity:0.5,
	loader_image:'',
	start_label:'开始自动播放',
	stop_label:'停止自动播放',
	play_span:5000,
	thumb_num:5
	},
	init:function(){
		this.activeImg();
		this.setupElements();
		this.activePos();
		this.checkCookie();
	},
	activeImg:function(){
		var context=this;
		if($.browser.version==6.0){$('.ad-thumbs li a img').css('margin-top',($('.ad-thumbs li a').height()-$('.ad-thumbs li a img').height())*0.5)}//IE6缩略图居中
		if(this.setting.thumb_opacity < 1) {
        	$('.ad-thumbs li').find('img').css('opacity', this.setting.thumb_opacity);
      	};
		$('.ad-thumbs li a').each(function(i){
			$(this).attr('href',$(this).attr('href')+'#Main').hover(function(){if(!$(this).is('.ad-active') && context.setting.thumb_opacity < 1){
				$(this).find('img').fadeTo(300,1)}},
				function(){if(!$(this).is('.ad-active') && context.setting.thumb_opacity < 1){$(this).find('img').fadeTo(300,context.setting.thumb_opacity)}}
			).addClass('ad-thumb'+i);
			if(typeof(context.setting.href)!='undefined' && (context.setting.href==$(this).attr('href') || context.setting.href==$(this).attr('href').split('#')[0])){
				$(this).addClass('ad-active').find('img').css('opacity',1);
				var index=[i];
				context.showImg(index);}
		});
	},
	setupElements: function() {
	  this.initBackAndForward();
      var $controls = $('.ad-controls');
      var $gallery_info = $('<p class="ad-info">'+($('.ad-thumbs li a').index($('.ad-active')[0])+1)+' / '+$('.ad-thumbs li a').length+'</p>');
      $controls.append($gallery_info).append($('<p class="notes">快捷键：上一张：← 下一张：→</p>'));
	  var $start_link = $('<span class="ad-slideshow-start" title="'+this.setting.start_label+'">'+ this.setting.start_label +'</span>');
      var $stop_link = $('<span class="ad-slideshow-stop" title="'+this.setting.stop_label+'">'+ this.setting.stop_label +'</span>');
      var $countdown = $('<span class="ad-slideshow-countdown"></span>');
      var $control = $('<div class="ad-slideshow-controls"></div>');
      $controls.append($control.append($start_link).append($stop_link).append($countdown));
	  $start_link.hide();
      $countdown.hide();
	  var autoRun=this.getCookie('autoRun');
	  if(!autoRun){$stop_link.show();$start_link.hide();}
	  else{$stop_link.hide();$start_link.show();}
	  var context = this;
      $start_link.click(
        function() {
          $stop_link.show().css('display','inline-block');$start_link.hide();
      	  $controls.addClass('ad-slideshow-running');
		  context.next();
		  context.delCookie('autoRun',0);
        }
      );
      $stop_link.click(
        function() {
          $countdown.hide();
	  	  $stop_link.hide();$start_link.show();
      	  $controls.removeClass('ad-slideshow-running');
		  context.setCookie('autoRun',0,24*60*60*1000);
		  window.clearInterval(false);
        }
      );
    },
	next: function() {
      var context = this;
      clearInterval(false);
      var interval=window.setInterval(function(){
		var now_active=$('.ad-thumbs li a').index($('.ad-active')[0])
		var next_active=now_active+1;
		if(next_active==$('.ad-thumbs li').length){
			window.location=$('.ad-thumbs li a')[0].href;	
		}else{
		window.location=$('.ad-thumbs li a')[next_active].href;}
	  },this.setting.play_span);
    },
	showImg:function(index){
			var context = this;
        	var img_container = $(document.createElement('div')).addClass('ad-image');
			img_container.append('<span id="loader" style="background:red;padding:4px 10px;color:white;">图片加载中 稍候...</span>');
			var $image=$('.ad-thumbs li a:eq('+index+')');
       	 	var img = $(new Image()).attr('src', $image.attr('pic'));
        	
			if(img[0].readyState!='complete'){
				setTimeout(function(){
				img_container.append(img);
				var size = context.getContainedImageSize(img.width(),img.height());
        		img.attr('width', size.width);
        		img.attr('height', size.height);
        		img_container.css({width: size.width +'px', height: size.height +'px'});
				context.centerImage(img_container, size.width, size.height);
				$('#loader').hide();
				},500);
			}
			else if(img[0].readyState=='complete'){//IE8图片加载完成
				setTimeout(function(){
				img_container.append(img);
				var size = context.getContainedImageSize(img.width(),img.height());
        		img.attr('width', size.width);
        		img.attr('height', size.height);
        		img_container.css({width: size.width +'px', height: size.height +'px'});
				context.centerImage(img_container, size.width, size.height);
				$('#loader').hide();
				},500);
			}
        	$('.ad-image-wrapper').prepend(img_container);
			var desc = this.getDescription($image, img_container);
        		if(desc) {
		  			//把图片描述定位在大框架内
		  			$('.ad-image-wrapper').append(desc);
          			var width = $('.ad-image-wrapper').width() - parseInt(desc.css('padding-left'), 10) - parseInt(desc.css('padding-right'), 10);
          			desc.css('width', width +'px');
        		};
			this.initNextAndPrev();
	},
	getContainedImageSize: function(image_width, image_height) {
	  var image_wrapper=$('.ad-image-wrapper');
      if(image_height > image_wrapper.height()) {
        var ratio = image_width / image_height;
        image_height = image_wrapper.height();
        image_width = image_wrapper.height() * ratio;
      };
      if(image_width > image_wrapper.width()) {
  	    var ratio = image_height / image_width;
  	    image_width = image_wrapper.width();
  	    image_height = image_wrapper.width() * ratio;
  	  };
      return {width: image_width, height: image_height};
	  //alert(image_width)
    },
	centerImage: function(img_container, image_width, image_height) {
      img_container.css('top', '0px');
	  var image_wrapper=$('.ad-image-wrapper');
      if(image_height < image_wrapper.height()) {
        var dif = image_wrapper.height() - image_height;
        img_container.css('top', (dif / 2) +'px');
      };
      img_container.css('left', '0px');
      if(image_width < image_wrapper.width()) {
        var dif = image_wrapper.width() - image_width;
        img_container.css('left', (dif / 2) +'px');
      };
    },
	getDescription: function(image) {
      var desc = false;
      if(image.find('img').attr('alt').length) {
        var title = '';
        if(image.find('img').attr('alt').length) {
          title = '<strong class="ad-description-title">'+ image.find('img').attr('alt') +'</strong>';
        };
        desc = $('<p class="ad-image-description">'+ title +'</p>');
      };
      return desc;
    },
	activePos:function(){
		var now_active=$('.ad-thumbs li a').index($('.ad-active')[0])+1;
		var group=now_active/this.setting.thumb_num;
		var group_move=group>parseInt(group)?parseInt(group):parseInt(group)-1;
		var width = $('.ad-nav').width()+9;
		$('.ad-thumbs').scrollLeft(width*group_move);
	},
	initBackAndForward: function() {
      var context = this;
      var $scroll_forward = $('<div class="ad-forward" title="往右移动"></div>');
      var $scroll_back = $('<div class="ad-back" title="往左移动"></div>');
      $('.ad-nav').append($scroll_forward).prepend($scroll_back);
      var has_scrolled = 0;
      var thumbs_scroll_interval = false;
      $scroll_back.add($scroll_forward[0]).click(
        function() {
          var width = $('.ad-nav').width()+9;
          if($(this).is('.ad-forward')) {
            var left = $('.ad-thumbs').scrollLeft() + width;
          } else {
            var left = $('.ad-thumbs').scrollLeft() - width;
          };
		  var thumb_group=Math.ceil($('.ad-thumbs li').length/context.setting.thumb_num);
		  left<=0?$scroll_back.attr('title','左边没有了'):$scroll_back.attr('title','往左移动')
		  left>=thumb_group*width?$scroll_forward.attr('title','右边没有了'):$scroll_forward.attr('title','往右移动')
		  if(left>=thumb_group*width){left=(thumb_group-1)*width;}
          $('.ad-thumbs').animate({scrollLeft: left +'px'});
          return false;
        }
      ).css('opacity', 0.6).hover(function(){
			$(this).fadeTo(300,1);  
		},function(){$(this).fadeTo(300,0.6)});
    },
	initKeyEvents: function() {
      var context = this;
      $(document).keydown(
        function(e) {
          if(e.keyCode == 39) {
            // right arrow
            context.nextImage();
          } else if(e.keyCode == 37) {
            // left arrow
            context.prevImage();
          };
        }
      );
    },
	initNextAndPrev: function() {
	  this.initKeyEvents();
      var $next_link = $('<div class="ad-next" title="下一张图片"><div class="ad-next-image"></div></div>');
      var $prev_link = $('<div class="ad-prev" title="上一张图片"><div class="ad-prev-image"></div></div>');
      $('.ad-image-wrapper').append($next_link).append($prev_link);
      var context = this;
      $prev_link.add($next_link).mouseover(
        function(e) {
          // IE 6 hides the wrapper div, so we have to set it's width
          $(this).css('height', $('.ad-image-wrapper').height());
          $(this).find('div').show();
        }
      ).mouseout(
        function(e) {
          $(this).find('div').hide();
        }
      ).click(
        function() {
          if($(this).is('.ad-next')) {
            context.nextImage();
          } else {
            context.prevImage();
          };
        }
      ).find('div').css('opacity', 0.7);
    },
	nextImage: function(callback) {
    	var now_active=$('.ad-thumbs li a').index($('.ad-active')[0])
		var next_active=now_active+1;
		if(next_active==$('.ad-thumbs li').length){window.location=$('.ad-thumbs li a')[0].href}
		else{window.location=$('.ad-thumbs li a')[next_active].href;}
    },
	prevImage:function(){
		var now_active=$('.ad-thumbs li a').index($('.ad-active')[0])
		var prev_active=now_active-1;
		var last_thumb=$('.ad-thumbs li').length-1;
		if(prev_active<0){window.location=$('.ad-thumbs li a')[last_thumb].href}
		else{window.location=$('.ad-thumbs li a')[prev_active].href;}
	},
	getCookie:function(c_name){
		if(document.cookie.length>0){
    	c_start=document.cookie.indexOf(c_name + "=")
    	if(c_start!=-1){
        c_start=c_start + c_name.length+1
        c_end=document.cookie.indexOf(";",c_start)
        if(c_end==-1) c_end=document.cookie.length
        return unescape(document.cookie.substring(c_start,c_end))}}
		return "";
	},
	setCookie:function(c_name,value,expiredays){
		var exdate=new Date()
		exdate.setDate(exdate.getDate()+expiredays)
		document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())	
	},
	delCookie:function(c_name,value){
		var exdate=new Date();
		exdate.setTime(exdate.getTime()-10000);
		document.cookie = c_name+ "=" +escape(value)+"; expires=" + exdate.toGMTString();
	},
	checkCookie:function(){
		var autoRun=this.getCookie('autoRun');
		var $start_link = $('<span class="ad-slideshow-start" title="'+this.setting.start_label+'">'+ this.setting.start_label +'</span>');
      	var $stop_link = $('<span class="ad-slideshow-stop" title="'+this.setting.stop_label+'">'+ this.setting.stop_label +'</span>');
		if(!autoRun || autoRun==1){
			this.nextLoop();
		}
	},
	nextLoop:function(){
		window.setInterval(function(){
		var now_active=$('.ad-thumbs li a').index($('.ad-active')[0])
		var next_active=now_active+1;
		if(next_active==$('.ad-thumbs li').length){
			window.location=$('.ad-thumbs li a')[0].href;	
		}else{
		window.location=$('.ad-thumbs li a')[next_active].href;}
	  },this.setting.play_span);		
	}
}
$(function(){
	addGallery.init();	
});
