// ==UserScript==
// @name           Plurk Mobile Improve v1.2.8
// @namespace      http://blog.dg-space.com/plurk/m/
// @description		改良手機版的顯示
// @include				http://www.plurk.com/m
// @include				http://www.plurk.com/m/*
// @exclude				http://www.plurk.com/m/u/*
// @exclude				http://www.plurk.com/m/p/*
// ==/UserScript==

// ==About==
// author: Simon
// blog: http://blog.dg-space.com/

// == Modified Log == 
// v1.0		2009/02/09	發佈(改良顯示暱稱，大頭照)
// V1.1		2009/02/14   增加觀看回覆內容
// V1.1.1		2009/02/18	修改顯示暱稱(plurk已經自動顯示暱稱)，發文內容有圖片會自動顯示
// V1.2		2009/02/20	在未讀取頁面增加MAAR功能
// V1.2.1		2009/02/22	增加立即回覆功能(回覆內容和則數可立即更新)，大頭照顯示暫時移除
// V1.2.2		2009/02/26	修改發文內容有圖片的顯示
// V1.2.3		2009/03/02	修改回覆字串編碼，修正重複回覆失效
// V1.2.4		2009/03/03	修改回覆超過5則以上出現捲軸
// V1.2.5		2009/03/24	增加通知訊息，恢復顯示個人照片
// V1.2.6		2009/03/27	增加檢視圖片(類似lightbox效果)
// V1.2.7		2009/04/03	快速跳至某日
// V1.2.8		2009/04/14	刪除自己的發噗，檢視youtube影片


// ********** Main Script ***********
var GM_JQ = document.createElement('script');
//GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.src		= 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
GM_JQ.type	= 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);

function GM_wait() {
	if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100);
	}else{ $ = unsafeWindow.jQuery; letsJQuery(); }
}
GM_wait();

function letsJQuery() {

		$.noConflict()
		$('<div>jQuery is running!</div>').css({padding: '10px', background: '#ffc', position: 'absolute',top: '0', width: '100%'}).prependTo('body').fadeIn('fast').animate({opacity: 1.0}, 300).fadeOut('fast', function() {
		      $(this).remove();
		});

		// ~~~~ start scripting.  ~~~~~~~~~~~~

		$('.acc-num').remove();
		$('.plurk > a:first-child').addClass('user_link');
		$('.meta > a:first-child').addClass('rep_link');
		$('.rep_link').each(function(ri){

				$(this).attr('name',ri).parent().after('<div id="resp_'+ri+'" style="display:none;"><div id="rp'+ri+'" class="response_list" style="background-color:#FFFFCC;"></div><div id="dorp'+ri+'"   class="response_form"></div></div>');

				//response form		
				$('#dorp'+ri).html('<form/>').css({'background':'#CF682F','color':'#FFF','padding':'0.3em'}).children().addClass('re_plurk').attr('action',$(this).attr('href')).attr('name',ri).html($('.plurkbox p:eq(0)').html() +'<button>Plurk!</button>');
				$('#dorp'+ri+' > form').children('.input').css('width','60%');
				$('#dorp'+ri+' > form').children('br').remove();
		});

		$('form.re_plurk').submit(function () { 
				var strD ='';
				$(this).children().each(function(i){
					if ($(this).attr('name')==''){
						return false;
					}else{
						if (i>0)	strD = strD + '&' ;	
						strD = strD + $(this).attr('name') +'='+encodeURIComponent($(this).val());
					}
				});
				reply($(this).attr('action'),strD,$(this).attr('name'));
				return false;
		});

		/*  picture */
		if( ($('.plurk').length <= 15) && ($('.plurk a').length >= 1) ){

			if($('.current').attr('href') != '/m/?mode=my'){
				$('.plurk').each(function(ig){
						$(this).prepend('<img id="ig'+ig+'" src="http://statics.plurk.com/7f5c4282d2e9accfdae99cc6abb6c9bb.gif" border="0">');
				});

				$('.plurk > a.user_link').each(function (i) {
					var h = $(this).attr('href');  //  /m/u/xxxx    
					ppic(h,i);
				});
			};
		};

		/* show response */
		$('.rep_link').click(function(){
			var link = $(this).attr('href');
			var id = $(this).attr('name');
			replurk(link,id) ;	
			$(this).parent().css('font-weight','normal');
			$('#resp_'+id).toggle();
			return false ;
		});

		/* maar */
		if ($('.current').attr('href') =='/m/?mode=unread'){
			$('body').prepend('<div id="unread" style="display:none"></div>');
			$('.current').after(' - <a href="#" id="maar">(MAAR)</a>');
			$('.rep_link').each(function(i){
					if(i!=0) $('#unread').append(',');
					$('#unread').append(cover($(this).attr('href').substring(5)) );
			});
			$('#maar').click(function(){ 	maar(); });
		}

		/* alerts  */
		$('#top').append(' | <a href="http://www.plurk.com/Notifications" id="alert" target="plurk">Alerts(0)</a>');
		getCount();

		/*other*/
		$('.plurk a').not('.rep_link').attr('target','plurk');
		$('.pictureservices').each(function(pi){
				if($(this).attr('href').indexOf('flickr.com') <= 0){
					$(this).html('<img src="'+$(this).attr('href')+'" width="40" border="0">');
				};
		});
		/* ShowBox*/
		$('<div>').attr('id','box').css({'position':'absolute','background':'transparent url(http://statics.plurk.com/577ea8acd3e7ade25d3a23345f4d70d8.png) repeat scroll 0 0','top':'1px','left':'1px','padding':'10px','display':'none','border':'1px solid #ACD2EF','padding':'6px'}).appendTo('body');

		$('.pictureservices').click(function(){
			if($(this).attr('href').indexOf('flickr.com') <= 0){
				$('#box').html('<img style="cursor:pointer" src="'+$(this).attr('href')+'">');
			}else{
				$('#box').html('<img style="cursor:pointer" src="'+$(this).children('img').attr('src').replace(/_t/,'')+'">');
			};	
			ShowBox();			
			return false;
		});
	
		$('.youtube').click(function(){
			$('#box').html('<img src="http://www.plurk.com/static/greybox/w_close1.gif" style="padding: 3px; cursor: pointer;float:right"/><br/><embed src="'+$(this).attr('href').replace(/watch\?v=/,'v/')+'&hl=zh_TW&fs=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>');
			ShowBox();
			return false;
		});

		/*jump to */
		$('a[href=/m/?mode=responded]').after(' | <input type="button" id="gotm" value="快找">');
		$('#gotm').click(function(){
			to = prompt("Input date YYYY/MM/DD  EX:  2009/01/01  ");
			if(!to) return;
			to = (new Date(to+' 23:59:59')).getTime();
			var from_date = to.toString(); 
			location.href='http://www.plurk.com/m/?offset=' + from_date.substr(0,10) ;
		});
		/*delete*/
		var mylink = location.href ;
		if (mylink.indexOf('mode=my',0) > 0 ){
			$('.rep_link').each(function(){
					var plurk_id =cover($(this).attr('href').substring(5));
					$(this).after(' | <a href="#" id="'+plurk_id+'" class="delt">del</a>');
			});
		}
		$('.delt').click(function(){
			if(confirm('您確定要刪除嗎？')){
				delP($(this).attr('id'));
			}
			return false;
		});
}

function  ppic(uid,i){
	uid = uid.substring(5);
	var id ="";
	$.ajax({
		   type: "GET", url: "http://www.plurk.com/"+uid ,
			success: function(cont) {
				var pic_link = cont.match(/http\:\/\/avatars.plurk.com\/[1-9][0-9]+\-big[0-9]*\.jpg/i) ;
				//show pic
				$('.plurk > a.user_link').eq(i).before('<a href="http://www.plurk.com/'+uid+'" target="plurk"><img class="user_pic" src="'+pic_link+'" width="20px" alt="plurker" onMouseOver="this.width=60" onMouseOut="this.width=20" align="absmiddle" border="0"></a>&nbsp;');
				$('.plurk > #ig'+i).remove();
			}
	});
}   

function replurk(strx,id){
	var rep_link = strx.substring(2);
	$.ajax({  type: "GET", url: "http://www.plurk.com"+strx });
	$.ajax({
		   type: "GET", url: "http://www.plurk.com"+rep_link ,
			beforeSend: function(){
				$('#rp'+id).html('<img src="http://statics.plurk.com/7f5c4282d2e9accfdae99cc6abb6c9bb.gif" border="0">');},
			 error :function(){ /*alert('error')*/},
			success: function(response) {
				var rep_page = response.split('\<ul class\=\"responses\"\>');
				var dd = rep_page[1].split('\<\/ul\>');
				var cont = dd[0];
				$('#rp'+id).css({'margin':'0','padding':'10px'}).html('<ul class="resp">'+cont+'</ul>');
				$('.resp').css({'list-style':'none','padding':'0px;','margin':'0px','font-size':'12px'});
				$('.resp li').css('min-height','34px');
				$('.resp li a').attr('target','plurk');
				$('.avatar img').css({'border':'0px','width':'30px'});
				$('.message').css({'margin':'-25px 0 0 34px','padding':'0px'});
				$('.message .time').css('float','right');
				$('.r_qualifier').css({'color':'#fff','font-weight':'normal','padding':'1px'});
				$('.plurk_content').css('font-weight','normal');
				$('.pictureservices').each(function(pi){
					if($(this).attr('href').indexOf('flickr.com') <= 0){
						$(this).html('<img src="'+$(this).attr('href')+'" width="40" border="0">');
					};
				});

				$('.rep_link[name='+id+']').text($('#rp'+id+' ul li').length +' response');  //  count response	
				if ($('#rp'+id+' ul li').length > 4)  $('#rp'+id).css({'overflow':'scroll','overflow-x':'hidden','height':'130px'});
			}
	});

}

function maar(strx){
	$.ajax({
		   type: "POST", url: "http://www.plurk.com/Responses/markAllRead" ,
		   data:'ids=['+$('#unread').text()+']',
			beforeSend: function(){
				$('#maar').html('<img src="http://statics.plurk.com/7f5c4282d2e9accfdae99cc6abb6c9bb.gif" border="0">');},
			 error :function(){ /*alert('error')*/},
			success: function(response) {
				$('#maar').html('(MAAR)');
				location.reload();
		}
	});
}

function cover(strx)
{
	var str = "123456789abcdefghijklmnopqrstuvwxyz";
	var sum = 0 ;
	var tmpW = '';
	var tmpIndex = 0;
	for(i=0 ; i< strx.length ;i++)
	{
		tmpW = strx.charAt(i) ;
		tmpIndex = str.indexOf(tmpW,0)+1;
		sum = sum + (tmpIndex * Math.pow(36,strx.length-i-1) )
	}
		return sum;
//	$('#unread').append(sum);
}

function reply_form(url,id){
	$('#dorp'+id).html('<form/>').css({'background':'#CF682F','color':'#FFF','padding':'0.3em'}).children().addClass('re_plurk').attr('action',url).attr('name',id).html($('.plurkbox p:eq(0)').html() +'<button>Plurk!</button>');
	$('#dorp'+id+' > form').children('.input').css('width','60%');
	$('#dorp'+id+' > form').children('br').remove();
}

function reply(url,qr,id){
	$.ajax({
		   type: "POST", url: "http://www.plurk.com"+url ,
		   data:qr,
			beforeSend: function(){},
			 error :function(){ alert('error')},
			success: function(response) {
				replurk(url,id) ;
			//	reply_form(url,id);
			$('input[name=content]').val('');
		}
	});
}

function getCount(){
	$.ajax({
		   type: "GET", url: "http://www.plurk.com/Notifications/getCount",
			beforeSend: function(){},
			 error :function(){ /*alert('error')*/},
			success: function(response) {
				$('#alert').html('Alerts(<b>'+response+'</b>)');
			}
	});
}

function delP(id){
	$.ajax({
		   type: "POST", url: "http://www.plurk.com/TimeLine/deletePlurk",
		   data: "plurk_id=" +id,
			beforeSend: function(){},
			 error :function(){alert('not delete !'); },
			success: function(response) {
				//alert(response);
				$('#'+id).parent('.meta').parent('.plurk').hide("slow");
			}
	});

}

function ShowBox(url){

			if(window.innerHeight){
	                windowHeight=window.innerHeight;
		    }else if(document.documentElement&&document.documentElement.clientHeight){
			        windowHeight=document.documentElement.clientHeight;
	        }else if(document.body){
		            windowHeight=document.body.clientHeight;
			}
			var boxTop = windowHeight/2 - $('#box').innerHeight()/2 + $(window).scrollTop(); ;
			var boxLeft =  $(window).width()/2 - $('#box').innerWidth()/2 + $(window).scrollLeft() ;
			$('#box').css({'top':boxTop,'left':boxLeft}).show();
			$('#box img').click(function(){
				 $('#box').hide();
			});	
}