/**
 *
 * Copyright (c) 2009 May(qq104010230)
 * http://www.winwill.com
 * http://www.winwill.com/jquery/jscroll.html
 * admin@winwill.com
 */
/*--------------------------------------------------------------------------------------------------*/
$.fn.extend({//添加滚轮事件//by jun
	mousewheel:function(Func){
		return this.each(function(){
			var _self = this;
		    _self.D = 0;//滚动方向
			if($.browser.msie||$.browser.safari){
			   _self.onmousewheel=function(){_self.D = event.wheelDelta;event.returnValue = false;Func && Func.call(_self);};
			}else{
			   _self.addEventListener("DOMMouseScroll",function(e){
					_self.D = e.detail>0?-1:1;
					e.preventDefault();
					Func && Func.call(_self);
			   },false); 
			}
		});
	}
});
$.fn.extend({
	jscroll:function(j){
		return this.each(function(){
			j = j || {}
			j.Bar = j.Bar||{};//2级对象
			j.Btn = j.Btn||{};//2级对象
			j.Bar.Bg = j.Bar.Bg||{};//3级对象
			j.Bar.Bd = j.Bar.Bd||{};//3级对象
			j.Btn.uBg = j.Btn.uBg||{};//3级对象
			j.Btn.dBg = j.Btn.dBg||{};//3级对象
			var jun = { W:"15px"
						,BgUrl:""
						,Bg:"#efefef"
						,Bar:{  Pos:"up"
								,Bd:{Out:"#b5b5b5",Hover:"#ccc"}
								,Bg:{Out:"#fff",Hover:"#fff",Focus:"orange"}}
						,Btn:{  btn:true
								,uBg:{Out:"#ccc",Hover:"#fff",Focus:"orange"}
								,dBg:{Out:"#ccc",Hover:"#fff",Focus:"orange"}}
						,Fn:function(){}}
			j.W = j.W||jun.W;
			j.BgUrl = j.BgUrl||jun.BgUrl;
			j.Bg = j.Bg||jun.Bg;
				j.Bar.Pos = j.Bar.Pos||jun.Bar.Pos;
					j.Bar.Bd.Out = j.Bar.Bd.Out||jun.Bar.Bd.Out;
					j.Bar.Bd.Hover = j.Bar.Bd.Hover||jun.Bar.Bd.Hover;
					j.Bar.Bg.Out = j.Bar.Bg.Out||jun.Bar.Bg.Out;
					j.Bar.Bg.Hover = j.Bar.Bg.Hover||jun.Bar.Bg.Hover;
					j.Bar.Bg.Focus = j.Bar.Bg.Focus||jun.Bar.Bg.Focus;
				j.Btn.btn = j.Btn.btn!=undefined?j.Btn.btn:jun.Btn.btn;
					j.Btn.uBg.Out = j.Btn.uBg.Out||jun.Btn.uBg.Out;
					j.Btn.uBg.Hover = j.Btn.uBg.Hover||jun.Btn.uBg.Hover;
					j.Btn.uBg.Focus = j.Btn.uBg.Focus||jun.Btn.uBg.Focus;
					j.Btn.dBg.Out = j.Btn.dBg.Out||jun.Btn.dBg.Out;
					j.Btn.dBg.Hover = j.Btn.dBg.Hover||jun.Btn.dBg.Hover;
					j.Btn.dBg.Focus = j.Btn.dBg.Focus||jun.Btn.dBg.Focus;
			j.Fn = j.Fn||jun.Fn;
			var _self = this;
			var Stime,Sp=0,Isup=0;
			$(_self).css({overflow:"hidden",position:"relative",padding:"0px"});
			var dw = $(_self).width(), dh = $(_self).height()-1;
			var sw = j.W ? parseInt(j.W) : 21;
			var sl = dw - sw
			var bw = j.Btn.btn==true ? sw : 0;
			if($(_self).children(".jscroll-c").height()==null){//存在性检测
		$(_self).wrapInner("<div class='jscroll-c' style='top:0px;z-index:9999;zoom:1;position:relative'></div>");
			$(_self).children(".jscroll-c").prepend("<div style='height:0px;overflow:hidden'></div>");
			$(_self).append("<div class='jscroll-e' unselectable='on' style=' height:100%;top:0px;right:0;-moz-user-select:none;position:absolute;overflow:hidden;z-index:10000;'><div class='jscroll-u' style='position:absolute;top:0px;width:100%;left:0;background:blue;overflow:hidden'></div><div class='jscroll-h'  unselectable='on' style='background:green;position:absolute;left:0;-moz-user-select:none;border:1px solid'></div><div class='jscroll-d' style='position:absolute;bottom:0px;width:100%;left:0;background:blue;overflow:hidden'></div></div>");
			}
			var jscrollc = $(_self).children(".jscroll-c");
			var jscrolle = $(_self).children(".jscroll-e");
			var jscrollh = jscrolle.children(".jscroll-h");
			var jscrollu = jscrolle.children(".jscroll-u");
			var jscrolld = jscrolle.children(".jscroll-d");
			if($.browser.msie){document.execCommand("BackgroundImageCache", false, true);}
			jscrollc.css({"padding-right":sw});
			jscrolle.css({width:sw,background:j.Bg,"background-image":j.BgUrl});
			jscrollh.css({top:bw,background:j.Bar.Bg.Out,"background-image":j.BgUrl,"border-color":j.Bar.Bd.Out,width:sw-2});
			jscrollu.css({height:bw,background:j.Btn.uBg.Out,"background-image":j.BgUrl});
			jscrolld.css({height:bw,background:j.Btn.dBg.Out,"background-image":j.BgUrl});
			jscrollh.hover(function(){if(Isup==0)$(this).css({background:j.Bar.Bg.Hover,"background-image":j.BgUrl,"border-color":j.Bar.Bd.Hover})},function(){if(Isup==0)$(this).css({background:j.Bar.Bg.Out,"background-image":j.BgUrl,"border-color":j.Bar.Bd.Out})})
			jscrollu.hover(function(){if(Isup==0)$(this).css({background:j.Btn.uBg.Hover,"background-image":j.BgUrl})},function(){if(Isup==0)$(this).css({background:j.Btn.uBg.Out,"background-image":j.BgUrl})})
			jscrolld.hover(function(){if(Isup==0)$(this).css({background:j.Btn.dBg.Hover,"background-image":j.BgUrl})},function(){if(Isup==0)$(this).css({background:j.Btn.dBg.Out,"background-image":j.BgUrl})})
			var sch = jscrollc.height();
			//var sh = Math.pow(dh,2) / sch ;//Math.pow(x,y)x的y次方
			var sh = (dh-2*bw)*dh / sch
			if(sh<10){sh=10}
			var wh = sh/6//滚动时候跳动幅度
		//	sh = parseInt(sh);
			var curT = 0,allowS=false;
			jscrollh.height(sh);
			if(sch<=dh){jscrollc.css({padding:0});jscrolle.css({display:"none"})}else{allowS=true;}
			if(j.Bar.Pos!="up"){
			curT=dh-sh-bw;
			setT();
			}
			jscrollh.bind("mousedown",function(e){
				j['Fn'] && j['Fn'].call(_self);
				Isup=1;
				jscrollh.css({background:j.Bar.Bg.Focus,"background-image":j.BgUrl})
				var pageY = e.pageY ,t = parseInt($(this).css("top"));
				$(document).mousemove(function(e2){
					 curT =t+ e2.pageY - pageY;//pageY浏览器可视区域鼠标位置，screenY屏幕可视区域鼠标位置
						setT();
				});
				$(document).mouseup(function(){
					Isup=0;
					jscrollh.css({background:j.Bar.Bg.Out,"background-image":j.BgUrl,"border-color":j.Bar.Bd.Out})
					$(document).unbind();
				});
				return false;
			});
			jscrollu.bind("mousedown",function(e){
			j['Fn'] && j['Fn'].call(_self);
				Isup=1;
				jscrollu.css({background:j.Btn.uBg.Focus,"background-image":j.BgUrl})
				_self.timeSetT("u");
				$(document).mouseup(function(){
					Isup=0;
					jscrollu.css({background:j.Btn.uBg.Out,"background-image":j.BgUrl})
					$(document).unbind();
					clearTimeout(Stime);
					Sp=0;
				});
				return false;
			});
			jscrolld.bind("mousedown",function(e){
			j['Fn'] && j['Fn'].call(_self);
				Isup=1;
				jscrolld.css({background:j.Btn.dBg.Focus,"background-image":j.BgUrl})
				_self.timeSetT("d");
				$(document).mouseup(function(){
					Isup=0;
					jscrolld.css({background:j.Btn.dBg.Out,"background-image":j.BgUrl})
					$(document).unbind();
					clearTimeout(Stime);
					Sp=0;
				});
				return false;
			});
			_self.timeSetT = function(d){
				var self=this;
				if(d=="u"){curT-=wh;}else{curT+=wh;}
				setT();
				Sp+=2;
				var t =500 - Sp*50;
				if(t<=0){t=0};
				Stime = setTimeout(function(){self.timeSetT(d);},t);
			}
			jscrolle.bind("mousedown",function(e){
					j['Fn'] && j['Fn'].call(_self);
							curT = curT + e.pageY - jscrollh.offset().top - sh/2;
							asetT();
							return false;
			});
			function asetT(){				
						if(curT<bw){curT=bw;}
						if(curT>dh-sh-bw){curT=dh-sh-bw;}
						jscrollh.stop().animate({top:curT},100);
						var scT = -((curT-bw)*sch/(dh-2*bw));
						jscrollc.stop().animate({top:scT},1000);
			};
			function setT(){				
						if(curT<bw){curT=bw;}
						if(curT>dh-sh-bw){curT=dh-sh-bw;}
						jscrollh.css({top:curT});
						var scT = -((curT-bw)*sch/(dh-2*bw));
						jscrollc.css({top:scT});
			};
			$(_self).mousewheel(function(){
					if(allowS!=true) return;
					j['Fn'] && j['Fn'].call(_self);
						if(this.D>0){curT-=wh;}else{curT+=wh;};
						setT();
			})
		});
	}
});


function abookscroll(){
$(".entry,#thecomments,#trackback_area").jscroll({
			W:"12px",
			Bar:{ 

					Bg:{Out:"#fff",Hover:"#F76C00",
					Focus:"#F76C00"}},//设置滚动条滚轴背景：鼠标离开(默认)，经过，点击
			Btn:{
				btn:true,//是否显示上下按钮 false为不显示
				uBg:{Out:"#fff",Hover:"#F76C00",Focus:"#F76C00"},//设置上按钮背景：鼠标离开(默认)，经过，点击
				dBg:{Out:"#fff",Hover:"#F76C00",Focus:"#F76C00"}//设置下按钮背景：鼠标离开(默认)，经过，点击
			}});
}
var commentjs=function(){
	$.getScript(themeurl+"js/comment.js");
	$('#toolBar').animate({opacity: 'show'}, 300);
	$('#comment').unbind('focus',commentjs);//取消绑定focus的动作
}

var gravatarjs=function(){
	$.getScript(themeurl+"js/realgravatar.js");
	$('#email').unbind('focus',gravatarjs);//取消绑定focus的动作
}		


function abooksingleinit(){
$('#loading').hide();
$('.pagecontent,#next_page_button,#prev_page_button').show();
if($('#next_page_button').html()==''){$('#next_page_button').hide();};
if($('#prev_page_button').html()==''){$('#prev_page_button').hide();};
abookscroll();
// 消除鏈接虛線
$('a,input[type="submit"],button[type="button"],object').bind('focus',function(){if(this.blur){ this.blur();}});
$('.tg_t').click(function(){$(this).next('.tg_c').slideToggle(400)});
 $("pre:not([name='code'])").wrapInner("<span></span>");
  $("pre").hover(function() { 
  var contentwidth = $(this).contents().width();
  var blockwidth = $(this).width(); 
  if(contentwidth > blockwidth) { 
	$(this).stop().animate({ width: '848px' }, 250, 'swing',function(){$(this).css("overflow","auto");});        
  }}, function() {
	$(this).stop().animate({ width: '740px' }, 250, 'swing',function(){$(this).css("overflow","hidden");});
});
//限制图片大小
$('.entry p img,.comment-content p img').each(function() {
    var maxWidth = 380; // 图片最大宽度
    var maxHeight = 400;    // 图片最大高度
    var ratio = 0;  // 缩放比例
    var width = $(this).width();    // 图片实际宽度
    var height = $(this).height();  // 图片实际高度
 
    // 检查图片是否超宽
    if(width > maxWidth){
        ratio = maxWidth / width;   // 计算缩放比例
        $(this).css("width", maxWidth); // 设定实际显示宽度
        height = height * ratio;    // 计算等比例缩放后的高度 
        $(this).css("height", height);  // 设定等比例缩放后的高度
    }
 
    // 检查图片是否超高
    if(height > maxHeight){
        ratio = maxHeight / height; // 计算缩放比例
        $(this).css("height", maxHeight);   // 设定实际显示高度
        width = width * ratio;    // 计算等比例缩放后的高度
        $(this).css("width", width);    // 设定等比例缩放后的高度
    }
});
$('#comment_header li').click(function(){
	$(this).addClass("comment_switch_active").siblings().removeClass();
	$("#comment_content > ul").animate({opacity: 'hide'}, 0).eq($('#comment_header li').index(this)).animate({opacity: 'show'}, 500);
 return false;
	});
$('.com_num').click(function(){
	$('#add_comment').addClass("comment_switch_active").siblings().removeClass();
	$("#comment_content > ul").animate({opacity: 'hide'}, 0).eq(0).animate({opacity: 'show'}, 500);
	$("#comment_parent").attr("value", '0');
	$("#comment").attr("value", '').focus();
 return false;
	});			
			

$('#comment').bind('focus',commentjs);
$('#email').bind('focus',gravatarjs);

  //	profile change
   $("#edit_profile").toggle(function() {
            $("#welcome_msg").slideUp(200);
            $("#guest_info").slideDown(200);
			$("#edit_profile").html(' (改好了吧~)')
            return false
        },
        function() {
            $("#welcome_msg").slideDown(200);
            $("#guest_info").slideUp(200);
			$("#edit_profile").html(' (再改一次？)')
            return false
        })
		
  

var $s=$('.entry'),lb=$s.find('a:has(img)');
 if(lb.length){
            $.getScript(themeurl+"js/slimbox.js",function(){ 
			$(".entry a[href]").filter(function() {
			return /\.(jpg|png|gif)$/i.test(this.href);
		}).slimbox({}, null, function(el) {
			return (this == el) || (this.parentNode && (this.parentNode == el.parentNode));
		});
	});
  }


		commentajax();
		comment_pager();
		singleajax();		
}//abooksingleinit结束
function commentajax(){
$('.fn a').attr({ target: "_blank"});  //对class=“fn”标签内的a中添加target: "_blank"
$(".comment .avatar").load(function() {
    $(this).wrap(function(){
      return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
    });
    $(this).css("opacity","0");
  });


$('.comment-reply-link').click(function() {
	var t=$(this).parent().parent().attr("id");
	var postid=$(this).attr("id").split(/reply-/)[1].split(/-/)[0];
	var parent =$(this).attr("id").split(/reply-/)[1].split(/-/)[1];
	//alert (parent);
	var a = '"#' + t + '"';
    var b = $(this).parent().parent().find('cite:first').text();
	$('#add_comment').addClass("comment_switch_active").siblings().removeClass();
	$("#comment_content > ul").animate({opacity: 'hide'}, 0).eq(0).animate({opacity: 'show'}, 500);
	$("#comment").attr("value", "<a href=" + a + ">@" + b + " </a>,").focus();
	$("#comment_post_ID").attr("value", postid);
	$("#comment_parent").attr("value",parent);

	var temp=$("#"+t).html();
		$('#ajaxpre').html('').html('<li id="ajaxtempview" class="commentlist comment" style="background:#ddd"><div>'+temp + '</div></li>').show();
	$("#cancel-comment-reply-link").show();
	$("#cancel-comment-reply-link").unbind('click').bind('click', function(){

		$('#comment_switch').addClass("comment_switch_active").siblings().removeClass();
		$('#respond_area').animate({opacity: 'hide'}, 0);
		$("#comment_area").animate({opacity: 'show'}, 500);
		
		$("#comment").attr("value", '');
		$("#comment_parent").attr("value", '0');
		$("#cancel-comment-reply-link,#ajaxpre").hide();
		$("#"+t).focus();
return false;
});

	 return false;
});

}


function comment_pager(){
$('#comment_pager a').click(function() {
    var wpurl=$(this).attr("href").split(/(\?|&)action=AjaxCommentsPage.*$/)[0];
    var commentPage = 1;
    if (/comment-page-/i.test(wpurl)) {
    commentPage = wpurl.split(/comment-page-/i)[1].split(/(\/|#|&).*$/)[0];
    } else if (/cpage=/i.test(wpurl)) {
    commentPage = wpurl.split(/cpage=/)[1].split(/(\/|#|&).*$/)[0];
    };
    //alert(commentPage);
    var postId =$("#comment_post_ID").attr("value");
	//alert(postId);
    var url = wpurl.split(/#.*$/)[0];
    url += /\?/i.test(wpurl) ? '&' : '?';
    url += 'action=AjaxCommentsPage&post=' + postId + '&page=' + commentPage;        
    //alert(url);
    $.ajax({
    url:url,
    type: 'GET',

    beforeSend: function() {
	$('#comment_pager').hide();
    var loading='<div id="com_loading">正在努力读取中......</div>';
    $('#thecomments').html(loading);
    },
    error: function(request) {
        alert(request.responseText);
    },
    success:function(data){
    var responses=data.split('<!--Abook-AJAX-COMMENT-PAGE-->');
    $('#thecomments').html(responses[0]);
    $('#comment_pager').html(responses[1]);
	abookscroll();
	commentajax();
	comment_pager();
    $('#thecomments,#comment_pager').show();
	

	
        }
    });    
    return false;
    });
}
function singleajax(){
	$("#next_page_button,#prev_page_button").click(function() {
                        var href = $(this).children().attr("href");
                       
								$.ajax({
                                       url : href+'?act=singlePage',
                                       dataType:'html',
									   contentType:'application/json; charset=utf-8',
										cache:true,
										beforeSend: function() {								
										//$('#main').empty();
										$('#prev_page_button,#next_page_button').fadeOut(0);
										$("#loading").show();		
									
												},
                                        success : function(resource) {
                                            $("#main").empty().html(resource);
										
											abooksingleinit();
											
											    },
                                        
                                });
                        return false;
                });	
}	

jQuery(document).ready(function($) {



abooksingleinit();

$("#nav li").hover(function() {
		$(this).stop().animate({ marginTop: '-15px' }, 250, 'swing',function(){$(this).css("overflow","auto");});   
	}, function() {
		$(this).stop().animate({ marginTop: '0' }, 250, 'swing',function(){$(this).css("overflow","Hidden");});  
	
	});



	
});//js end


		
	
	



		
		
	

		
