// ==UserScript==
// @name				Eat Fanfou
// @namespace			http://fanfou.com/PorkFat
// @description			Eat Fanfou
// @version				0.8
// @include				http://fanfou.com/*
// @require				http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/library.js
// @require				http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/base64.js
// @require				http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/functions.js
// @require				http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/fancyzoom.js
// @resource			STYLES http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/styles.css
// @resource			IMG_SPACER http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/spacer.gif
// @resource			IMG_CLOSEBOX http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/closebox.png
// @resource			IMG_MAGNIFYINGGLASS http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/magnifying_glass.png
// @resource			IMG_ZOOMSPIN1 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-1.png
// @resource			IMG_ZOOMSPIN2 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-2.png
// @resource			IMG_ZOOMSPIN3 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-3.png
// @resource			IMG_ZOOMSPIN4 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-4.png
// @resource			IMG_ZOOMSPIN5 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-5.png
// @resource			IMG_ZOOMSPIN6 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-6.png
// @resource			IMG_ZOOMSPIN7 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-7.png
// @resource			IMG_ZOOMSPIN8 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-8.png
// @resource			IMG_ZOOMSPIN9 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-9.png
// @resource			IMG_ZOOMSPIN10 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-10.png
// @resource			IMG_ZOOMSPIN11 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-11.png
// @resource			IMG_ZOOMSPIN12 http://dl.getdropbox.com/u/167627/GM_Scripts/eat_fanfou_remote/zoom-spin-12.png
// ==/UserScript==

// 配置
var EF = {
	version: '0.8',
	name: '雞塊 好吃',
	versionText: function() {
		return this.version + ' - ' + this.name;
	},
	author: 'PorkFat',
	features: [
		'四四方方的头像，变得圆碌碌；',
		'回复的消息，在本消息后面直接显示上下文；',
		'发消息同时，可以附上照片（多ID通过API上传照片会串号，重启浏览器可解决，其他功能无影响）；',
		'消息里的照片，点击直接放大到原本的尺寸；',
		'用户空间左上方的大头像，点击放大显示。',
	],
};

(function init() {

	//变量
	var $D = YAHOO.util.Dom,
		$E = YAHOO.util.Event,
		$C = YAHOO.util.Connect,
		$A = YAHOO.util.Anim;

	// CSS代码
	var cssCode = GM_getResourceText('STYLES');
	GM_addStyle(cssCode);

	Func.Account.init();

	function roundedAvatar(el) {
		var img = el.getElementsByTagName('img')[0];
		var url = img.getAttribute('src');
		img.setAttribute('src', GM_getResourceURL('IMG_SPACER'));
		$D.setStyle(img, 'width', '48px');
		$D.setStyle(img, 'height', '48px');
		$D.setStyle(img, '-moz-border-radius', '5px');
		$D.setStyle(img, 'background', 'url(' + url + ') 50% 50% no-repeat');
		$D.setStyle(img, 'text-decoration', 'none');
	}
	
	$D.getElementsByClassName('avatar', 'a', 'stream', roundedAvatar);
	$D.getElementsByClassName('alist', 'ul', 'container', function(el){
		$D.batch(el.getElementsByTagName('a'), roundedAvatar);
	});

	if ($D.get('main') && $D.get('avatar')) { //这里应该是空间页面
		var lnk = $D.get('avatar').getElementsByTagName('a')[0];
		//在自己的空间不改变默认操作
		if (lnk.getAttribute('href').indexOf('settings') == -1) {
			var img = lnk.getElementsByTagName('img')[0];
			var url = img.getAttribute('src');
			url = url.replace(/avatar.fanfou.com\/l/, 'avatar.fanfou.com/o');
			lnk.setAttribute('href', url);
			$D.addClass(lnk, 'zoom');
		}
	}
	
	$D.getElementsByClassName('photo', 'a', 'stream', function(el){
		var img = el.getElementsByTagName('img')[0];
		var url = img.getAttribute('src');
		var caption = img.getAttribute('alt');
		url = url.replace(/photo.fanfou.com\/m/, 'photo.fanfou.com/o');
		el.setAttribute('href', url);
		el.setAttribute('title', caption);
		$D.addClass(el, 'zoom');
	});
	
	setupZoom();
	
	function getStatus(o) {
		var str = '';
		str += '<a href="' + o.user.url + '" class="avatar" style="background-image:url(' + o.user.profile_image_url + ');">' + o.user.name + '</a>';
		str += ' <span class="content">' + o.text + '</span>';
		str += '<span class="stamp">';
		str += '<a href="http://fanfou.com/statuses/' + o.id + '" class="time">' + readableDate(o.created_at) + '</a>';
		str += ' <span class="method">通过' + o.source + '</span>';
		//if (o.in_reply_to_status_id) {
		//	str += ' <span class="reply"><a href="http://fanfou.com/statuses/' + o.in_reply_to_status_id + '">给' + o.in_reply_to_screen_name + '的回复</a></span>';
		//}
		str += ' <a href="' + o.user.url + '">' + o.user.name + '</a>';
		str += '</span>';
		return str;
	}
	
	function readableDate(str) {
		var arr = str.split(' ');
		var str = arr[1] + ' ' + arr[2] + ', ' + arr[5] + ' ' + arr[3];

		var current_date = new Date();
		var parsed_date = Date.parse(str) - current_date.getTimezoneOffset() * 60 * 1000;
		var date = new Date(parsed_date);

		var parsed_date = date.valueOf();
		var current_date = new Date();
		var past_seconds = parseInt((current_date.getTime() - parsed_date) / 1000);
		if (past_seconds < 60) {
			return past_seconds + ' 秒前';
		} else if (past_seconds < 60 * 60) {
			return (parseInt(past_seconds / 60)).toString() + ' 分钟前';
		} else if (past_seconds < 60 * 60 * 24) {
			return '约 ' + (parseInt(past_seconds / 3600)).toString() + ' 小时前';
		} else {
			return date.getFullYear() + '-' + (date.getMonth() >= 9 ? '' : '0') + (date.getMonth() + 1) + '-' + (date.getDate() > 9 ? '' : '0') + date.getDate() + ' ' + (date.getHours() > 9 ? '' : '0') + date.getHours() + ':' + (date.getMinutes() > 9 ? '' : '0') + date.getMinutes();
		}

	}
	
	$D.getElementsByClassName('reply', 'span', 'stream', function(el){
		var lnk = el.getElementsByTagName('a')[0];
		var id = lnk.getAttribute('href').match(/\/statuses\/([\w-]*)/)[1];
		GM_xmlhttpRequest({
			method: 'GET',
			url: 'http://api.fanfou.com/statuses/show/' + id + '.json?format=html',
			headers: {
				'User-Agent': navigator.userAgent,
				'Accept': 'application/json',
				'Authorization': 'Basic ' + Func.Account.auth()
			},
			onload: function(response) {
				if (response.responseText.charAt(0) == '{') {
					var context = document.createElement('p');
					$D.addClass(context, 'context');
					context.innerHTML = eval('getStatus' + '(' + response.responseText + ')');
					var container = $D.getAncestorByTagName(el, 'li');
					container.appendChild(context);
				}
			}
		});
	});

	// 发送照片
	function attachPhotoUploader() {
		if (!$D.get('message') || !$D.get('update')) return;
		var update = $D.get('update'),
			url = ['http://m.fanfou.com/home', 'http://api.fanfou.com/photos/upload.json'],
			filename = ['picture', 'photo'],
			statusname = ['desc', 'status'];
		
		// 放入传照片form
		var form = document.createElement('form');
		form.setAttribute('id', 'EF-photo-upload');
		form.setAttribute('enctype', 'multipart/form-data');
		form.setAttribute('method', 'post');
		form.setAttribute('action', url[0]);
		$D.setStyle(form, 'display', 'none');

		var str = '';
		str += '<h2 title="点击切换回发消息">你照了什么？</h2>';
		str += '<span class="switch"><a href="#" class="current">通过手机上传</a>|<a href="#">通过API</a></span>';
		str += '<p><input type="file" name="' + filename[0] + '" id="myphoto" class="input_file" size="55" /></p>';
		str += '<p><textarea name="' + statusname[0] + '" id="myphotostatus" class="qs" cols="70" rows="3"></textarea></p>';
		str += '<p class="sorry">通过 API 上传需输入 email 和密码用以登录 API 接口，<br />照片发送后会提示下载文件，<strong>取消</strong>、再按 <strong>Ctrl+R</strong> 刷新页面就行</p>';
		str += '<p class="act">';
			str += '<input type="hidden" name="action" value="photo.upload" />';
			str += '<input type="hidden" name="token" value="' + Func.Account.token() + '" />';
			str += '<img src="http://static.fanfou.com/img/ajax-indicator.gif" class="loading" alt="loading" />';
			str += '<input type="submit" class="formbutton" value="发送" />';
		str += '</p>';
		form.innerHTML = str;
		
		update.appendChild(form);

		$E.on(form, 'submit', function(ev){
			$E.stopEvent(ev);
			
			if ($D.get('myphoto').value != '') {
				// 执行照片上传操作
				$C.setForm(form, true);
				$C.asyncRequest('post', form.action, {
					upload: function(o){
						window.location = window.location;
					}
				});
				$D.getElementsByClassName('loading', 'img', form, function(el){
					el.style.visibility = 'visible';
				});
				$D.getElementsByClassName('formbutton', 'input', form, function(el){
					el.disabled = 'disabled';
				});
			}
		});

		// 让标题可以点击切换
		var h2 = update.getElementsByTagName('h2'),
			fm = update.getElementsByTagName('form');
			
		h2[0].setAttribute('title', '点击切换到传照片');
		$E.on(h2[0], 'click', function(ev){
			$D.setStyle(fm[0], 'display', 'none');
			$D.setStyle(fm[1], 'display', 'block');
		});
		$E.on(h2[1], 'click', function(ev){
			$D.setStyle(fm[0], 'display', 'block');
			$D.setStyle(fm[1], 'display', 'none');
		});

		// 照片上传方式可选择
		var sw = $D.getElementsByClassName('switch', 'span', fm[1])[0],
			lnk = sw.getElementsByTagName('a'),
			photo = $D.get('myphoto'),
			status = $D.get('myphotostatus');

		$E.on(lnk[0], 'click', function(ev){
			$E.stopEvent(ev);
			form.setAttribute('action', url[0]);
			photo.setAttribute('name', filename[0]);
			status.setAttribute('name', statusname[0]);
			$D.getElementsByClassName('sorry', 'p', fm[1], function(el){
				el.style.visibility = 'hidden';
			});
			$D.removeClass(lnk[1], 'current');
			$D.addClass(this, 'current');
		});
		$E.on(lnk[1], 'click', function(ev){
			$E.stopEvent(ev);
			form.setAttribute('action', url[1]);
			photo.setAttribute('name', filename[1]);
			status.setAttribute('name', statusname[1]);
			$D.getElementsByClassName('sorry', 'p', fm[1], function(el){
				el.style.visibility = 'visible';
			});
			$D.removeClass(lnk[0], 'current');
			$D.addClass(this, 'current');
		});
	}

	attachPhotoUploader();
/*	
	GM_xmlhttpRequest({
		method: 'GET',
		url: 'http://api.fanfou.com/account/verify_credentials.json',
		headers: {
			'User-Agent': navigator.userAgent,
			'Accept': 'application/json',
			'Authorization': 'Basic ' + Func.Account.auth()
		},
		onload: function(response) {
			console.log(eval('(' + response.responseText + ')').name);
		}
	});

	console.log('ok.');
*/
})();
