/*
Philna main javascript
Author: yinheli
Update: 2009/04/22
Author URI: http://philna.com/

If you  found something wrong please contact me that would be very friendly of you.Thank you!

 Copyright (c) 2009 yinheli
*/
(function(){
function SetCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+"="+escape(value)+((expiredays==null)?"":";expires="+exdate.toGMTString());
}
window['PHC'] = {};
window['PHC']['SetCookie'] = SetCookie;
})();

jQuery.getPos = function (e){
 var l = 0;
 var t = 0;
 var w = jQuery.intval(jQuery.css(e,'width'));
 var h = jQuery.intval(jQuery.css(e,'height'));
 var wb = e.offsetWidth;
 var hb = e.offsetHeight;
 while (e.offsetParent){
 l += e.offsetLeft + (e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);
 t += e.offsetTop + (e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);
 e = e.offsetParent;
 }
 l += e.offsetLeft + (e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);
 t += e.offsetTop + (e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);
 return {x:l, y:t, w:w, h:h, wb:wb, hb:hb};
};
jQuery.getClient = function(e){
 if (e) {
 w = e.clientWidth;
 h = e.clientHeight;
 } else {
 w = (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document
.body.offsetWidth;
 h = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : 
document.body.offsetHeight;
 }
 return {w:w,h:h};
};
jQuery.getScroll = function (e){
 if (e) {
 t = e.scrollTop;
 l = e.scrollLeft;
 w = e.scrollWidth;
 h = e.scrollHeight;
 } else {
 if (document.documentElement && document.documentElement.scrollTop) {
 t = document.documentElement.scrollTop;
 l = document.documentElement.scrollLeft;
 w = document.documentElement.scrollWidth;
 h = document.documentElement.scrollHeight;
 } else if (document.body) {
 t = document.body.scrollTop;
 l = document.body.scrollLeft;
 w = document.body.scrollWidth;
 h = document.body.scrollHeight;
 }
 }
 return { t: t, l: l, w: w, h: h };
};
jQuery.intval = function (v){
 v = parseInt(v);
 return isNaN(v) ? 0 : v;
};
jQuery.fn.ScrollTo = function(s) {
 o = jQuery.speed(s);
 return this.each(function(){
 new jQuery.fx.ScrollTo(this, o);
 });
};
jQuery.fx.ScrollTo = function (e, o)
{
 var z = this;
 z.o = o;
 z.e = e;
 z.p = jQuery.getPos(e);
 z.s = jQuery.getScroll();
 z.clear = function(){clearInterval(z.timer);z.timer=null};
 z.t=(new Date).getTime();
 z.step = function(){
 var t = (new Date).getTime();
 var p = (t - z.t) / z.o.duration;
 if (t >= z.o.duration+z.t) {
 z.clear();
 setTimeout(function(){z.scroll(z.p.y, z.p.x)},13);
 } else {
 st = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.y-z.s.t) + z.s.t;
 sl = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.x-z.s.l) + z.s.l;
 z.scroll(st, sl);
 }
 };
 z.scroll = function (t, l){window.scrollTo(l, t)};
 z.timer=setInterval(function(){z.step();},13);
};

$(document).ready(function(){

	(function(){
	/*
	 comment js by MG12 URI: http://www.neoease.com/
	Modified by yinheli URL: http://philna.com/
	2009/03/24
	*/
	function $(id){
		return document.getElementById(id);
	}

	function reply(authorId, commentId, commentBox) {
		var author = $(authorId).innerHTML;
		var insertStr = '<a href="#' + commentId + '">@' + author.replace(/\t|\n|\r\n/g, "") + ' </a> \n';
		appendReply(insertStr, commentBox);
	}

	function quote(authorId, commentId, commentBodyId, commentBox) {
		var author = $(authorId).innerHTML;
		var comment = $(commentBodyId).innerHTML;
		var insertStr = '<blockquote cite="#' + commentBodyId + '">';
		insertStr += '\n<strong><a href="#' + commentId + '">' + author.replace(/\t|\n|\r\n/g, "") + '</a> :</strong>';
		insertStr += comment.replace(/\t/g, "");
		insertStr += '</blockquote>\n';
		insertQuote(insertStr, commentBox);
	}

	function appendReply(insertStr, commentBox){
		if($(commentBox) && $(commentBox).type == 'textarea') {
			field = $(commentBox);
		} else {
			alert("The comment box does not exist!");
			return false;
		}
		if (field.value.indexOf(insertStr) > -1) {
			alert("You've already appended this reply!");
			return false;
		}
		if (field.value.replace(/\s|\t|\n/g, "") == '') {
			field.value = insertStr;
		} else {
			field.value = field.value.replace(/[\n]*$/g, "") + '\n\n' + insertStr;
		}
		ReSizeArea();
	}

	function insertQuote(insertStr, commentBox) {
		if($(commentBox) && $(commentBox).type == 'textarea') {
			field = $(commentBox);
		} else {
			alert("The comment box does not exist!");
			return false;
		}
		if (field.value.indexOf(insertStr) > -1) {
			alert("You've already appended this! Please check it");
			return false;
		}
		if (field.selectionStart || field.selectionStart == '0') {
			var startPos = field.selectionStart;
			var endPos = field.selectionEnd;
			var cursorPos = startPos;
			field.value = field.value.substring(0, startPos)
						  + insertStr
						  + field.value.substring(endPos, field.value.length);
			cursorPos += insertStr.length;
			//field.focus();
			field.selectionStart = cursorPos;
			field.selectionEnd = cursorPos;

		} else {
			field.value += insertStr;
		}
		ReSizeArea();
	}
	window['PH'] = {};
	window['PH']['$'] = $;
	window['PH']['reply'] = reply;
	window['PH']['quote'] = quote;
	})();

	$('.admincomment .author:last').addClass('adminxing');
	$('#feed_readers li a').css({'-moz-border-radius':'7px','-webkit-border-radius':'7px','border-radius':'7px'});
/* 	setTimeout(function(){$('.feedme').slideUp('slow');},1000);
	setTimeout(function(){$('.feedme').slideDown('slow');},2000); */
	$('#welcome-you .close').click(function(){
		$('#welcome-you').animate({top: "+=60px"},500)
		.animate({opacity: 'hide',top:"-=200px"},100);
	});
	$('.singleggad .close').click(function(){
	$('.singleggad').slideUp();
	PHC.SetCookie('philna_singlepage_ad','no',20);
	setTimeout(function(){alert('This advertisement will no longer display in 20 days! \n \n 这个广告在20天内不会再显示.感谢你的支持')},1000);
	});
	$('#comment-ad .close').click(function(){
	$('#comment-ad').slideUp();
	PHC.SetCookie('philna_comment_ad','no',20);
	setTimeout(function(){alert('This advertisement will no longer display in 20 days! \n \n 这个广告在20天内不会再显示.感谢你的支持')},1000);
	});
	$('#commentsinfo .commentsact .addtrackback').toggle(
	function(){$('#get-trackback-url').slideDown();},
	function(){$('#get-trackback-url').slideUp();}
	);
	
	function init(){
	//clone comment
		var A=/^#comment-/;
		var B=/^@/;
		$('.comment p a').each(
			function() {
				if($(this).attr('href').match(A)&& $(this).text().match(B)){
					$(this).addClass('atreply');
				}
			}
		);
		$('.atreply').hover(
			function() {
				$($(this).attr('href')).clone().hide().insertAfter($(this).parents('li')).attr('id','').addClass('tip').fadeIn(300);
			}, 
			function(){
				$('.tip').animate({left:'+=30'},100).animate({opacity: 'hide', top: '+=60px'},500,function(){$(this).remove()});
			}
		);
		$('.atreply').mousemove(
			function(e) {
				$('.tip').css({left:(e.clientX+18),top:(e.pageY+18)})
			}
		);
		$('.atreply').click(function(){$($(this).attr('href')).ScrollTo(600);return false; });
		
		$('#commentslist li').hover(function(){$(this).find('.act').css('visibility','visible')},function(){$(this).find('.act').css('visibility','hidden')});
		$('.act a').click(function(){$('#comment').ScrollTo(800);setTimeout(function(){field.focus();},1200);});
		
		$('#commentpager a').addClass('ajaxcp');
	}
	
	function reinit(){
		init();
	}

	function ajacpload(){
	$('.ajaxcp').click(function(){
		var wpurl=$(this).attr('href').split(/(\?|&)action=cpage_ajax.*$/)[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 =PH.$('cp_post_id').innerHTML;
		var url = wpurl.split(/#.*$/)[0];
		url += /\?/i.test(wpurl) ? '&' : '?';
		url += 'action=cpage_ajax&post=' + postId + '&page=' + commentPage;		
		//alert(url);
	$.ajax({
		url:url,
		type: 'GET',
		beforeSend: function() {
		document.body.style.cursor = 'wait';
		var C=0.7;
		$('#commentslist,#commentnavi').css({opacity:C,MozOpacity:C,KhtmlOpacity:C,filter:'alpha(opacity=' + C * 100 + ')'});
		var loading='<span id="cmploading">Loading</span>';
		$('#commentpager').html(loading);
		},
		error: function(request) {
			alert(request.responseText);
		},
		success:function(data){
		var responses=data.split('<!--PHILNA-AJAX-COMMENT-PAGE-->');
		$('#commentslist').html(responses[0]);
		$('#commentpager').html(responses[1]);
		var C=1;
		$('#commentslist,#commentnavi').css({opacity:C,MozOpacity:C,KhtmlOpacity:C,filter:'alpha(opacity=' + C * 100 + ')'});
		$('#cmploading').remove();
		document.body.style.cursor = 'auto';
		$('#commentsinfo').ScrollTo(800);
		reinit();
		ajacpload();
			}
		});		
		return false;		
		});
	}
	
	init();
	ajacpload();
	
	$('#totop a,.addcomment').click(function(){$($(this).attr('href')).ScrollTo(600);return false; });

	$('#toggle-author_info a').toggle(
	function(){$(this).html(closeMsg);$('#author_info').slideDown();$('#commenter-info,#comment-ad').slideUp();},
	function(){$(this).html(changeMsg);$('#author_info').slideUp();$('#commenter-info,#comment-ad').slideDown();}
	);
	
	function ReSizeArea(){
		$('#comment').attr('rows',function(){
		var R=$('#comment').attr('rows');
		var H = $('#comment').val().split(/\n/g).length;
		if(H>5){
			return H+1;	
		}else{
			return 8;
		}
		});
	}
	ReSizeArea();
		$('#comment').keydown(function(){
			ReSizeArea();
		}); 

	if($('#commentform').length){
		$('#commentform').submit(function(){
		$.ajax({
			url:ajaxCommentsURL,
			data: $('#commentform').serialize(),
			type: 'POST',
			beforeSend: function() {
				$('#commentload').hide();
				if($('#commentslist .msgbox')) $('#commentslist .msgbox').slideUp();
				$('#commentload').slideDown();
				$('.row,#submit').css('opacity','0.4');
				$('#submit').attr('disabled', true);
				$('#comment').attr('disabled', true);
			},
			error: function(request) {
				alert(request.responseText);
				$('.row,#submit').css('opacity','1');
				$('#submit').attr('disabled', false);
				$('#comment').attr('disabled', false);
				$('#commentload').slideUp();
			},
			success:function(data){
				$('textarea').each(function(){this.value='';});
				$('#commentload').slideUp();
				$('#commentslist').append(data);
				var new_comment = $('#commentslist li:last').hide();
				new_comment.slideDown('slow').animate({backgroundColor: '#BBB'},500).animate({backgroundColor:'#F7F7F7'},1200).ScrollTo(1000);
				$('.nub').text(parseInt($('#allcmnub').text())+1).removeClass('nub').addClass('cmnub');
				$('#allcmnub').text(parseInt($('#allcmnub').text())+1);
				setTimeout(function(){$('#submit').attr('disabled', false);$('#comment').attr('disabled', false);$('.row,#submit').css('opacity','1');},6000);
			}
		});
		return false;
		});
	};
	$('#post_to_twitter').click(function(){
	if($(this).attr('checked')==true)
	$('#twitter_form').slideDown();
	if($(this).attr('checked')==false)
	$('#twitter_form').slideUp();
	});
	$('#toggletrackbacks a').toggle(
	function(){$('#trackbackslist').slideDown();},
	function(){$('#trackbackslist').slideUp();}
	);
	$('#trackbackinfo .addtrackback').click(
		function(){
		$('#commentsinfo').ScrollTo(800);
		$('#commentsinfo .addtrackback').click();
		$('#get-trackback-url').animate({backgroundColor: '#BBB'},500).animate({backgroundColor:'#F7F7F7'},1200).ScrollTo(1000);
		return false;
		});
	var say=$('#philna_say');
	say.click(function(){
	$.ajax({
	url:'?refresh',
	type:'GET',
	dataType:'html',
	beforeSend:function(){
		say.css('color','#999').hide('slow');
		setTimeout(function(){say.html('<span id="sayload"></span>').show('fast');},500);
		},
	error:function(request){
		say.html('Whoops! Something went wrong.Sorry');
		},
	success:function(data){
	setTimeout(function(){say.hide();say.html(data).show('slow');},2000);
	say.css('color','#000');
	}
	})
	})
})