/**
 * 初始化当前登录用户id
 */
var userId = 0;
/**
 * 初始化缓存对象
 */
var cache = {boxes: {}};
/**
 * 按需加载所需的 js/css 资源，并执行回调函数
 * 程序中一般不应直接使用这个对象
 * 而应该使用对应的函数包，例如 mbox, ajaxform, login 等
 */
var loader = {
	version : '20110217',
	widgets : {
		"smoothbox":{
			"css":"/css/smoothbox.css",
			"js":"/js/smoothbox.js"
		},
		"form":{
			"css":"",
			"js":"/js/widget/ajaxForm.js"
		},
		"humanmessage":{
			"css":"",
			"js":"/js/humanmessage.js"
		},
		"tiny_mce":{
			"css":"",
			"js":"/js/tiny_mce/tiny_mce.js"
		},
		"mbox":{
			"css":"/css/widget/mbox.css",
			"js":"/js/widget/mbox.js"
		},
		"suggest":{
			"css":"/css/widget/suggest.css",
			"js":"/js/widget/suggest.js"
		},
		"overlay":{
			"css":"/css/widget/overlay.css",
			"js":"/js/widget/overlay.js"
		}
	},
	loaded : {},
	loading : {},
	use : function() {
		var args = [].slice.call(arguments, 0);
		var chain = this.makeQueue(args);
		new LoaderProcessor(chain).process();
	},
	makeQueue: function(args) {
		var list = [];
		for (var i = 0 , len = args.length; i < len; i++) {
			var item = args[i];
			if ($type(item) == 'function') {
				list.push(item);
			} else {
				if ($type(item) == 'string') {
					var widget = this.widgets[item];
					if (widget['css']) {
						list.push({
							src : widget['css'] + "?v=" + this.version,
							type : 'css'
						});
					}
					if (widget['js']) {
						list.push({
							src : widget['js'] + "?v=" + this.version,
							type : 'js'
						});
					}
				}
			}
		}
		return list;
	},
	load : function(url, type, callback) {
		if (this.loaded[url]) {
			if (callback) {
				callback();
			}
			this.loading[url] = false;
			return;
		}
		if (this.loading[url]) {
			setTimeout(function() {
				loader.load(url, type, callback);
			}, 200);
			return;
		}
		this.loading[url] = true;
		if (type == 'css') {
			this.loadCSS(url, callback);
		} else {
			if (type == 'js') {
				this.loadJS(url, callback);
			}
		}
	},
	loadCSS : function(url, callback) {
		var ss = document.styleSheets;
		for (var i = 0, max = ss.length; i < max; i++) {
			if (ss[i].href == url) {
				return;
			}
		}
		var css;
		if (Browser.Engine.trident4) {
			css = document.createStyleSheet(url);
			if (callback) {
				callback();
			}
			loader.loaded[url] = true;
		} else {
			css = new Element('link', {
				href : url,
				rel : 'stylesheet',
				type : 'text/css'
			});
			css.inject($$('head')[0], 'bottom');
			if (callback) {
				callback();
			}
			loader.loaded[url] = true;
		}
	},
	loadJS : function(url, callback) {
		var js = new Element('script', {
			type : 'text/javascript',
			src : url,
			async : true
		});
		if (Browser.Engine.trident) {
			js.onreadystatechange = function() {
				if (this.readyState == 'loaded' || this.readyState == 'complete') {
					loader.loaded[url] = true;
					if (callback) {
						callback();
					}
				}
			}
		} else {
			js.addEvent('load', function() {
				loader.loaded[url] = true;
				if (callback) {
					callback();
				}
			});
		}
		js.inject($$('head')[0], 'bottom');
	}
};
var LoaderProcessor = new Class({
	initialize : function(args) {
		this.queue = args;
	},
	process : function() {
		var current = this.queue.shift();
		if (!current) {
			return;
		}
		if ($type(current) == 'function') {
			current();
			this.process();
		} else {
			loader.load(current.src, current.type, this.process.bind(this));
		}
	}
});
/**
 * 浮出层 mbox 的便捷函数封装
 * 用户不应当直接使用 MBox 对象，而应该使用这个封装中的函数
 */
var mbox = {
	/**
	 * 根据指定标题、指定文本显示一个浮出层 mbox
	 *
	 * @param uniqueId   为当前页面中的这个浮出层起一个唯一的名字
	 * @param title      浮出层标题
	 * @param content    浮出层内容文字
	 * @param boxOptions 浮出层的选项，以及事件
	 *        常见选项包括
	 *        1. width : 宽度像素
	 *        2. onInit: 浮出层初始化后腰执行的函数，函数有且只有一个缺省参数，为该浮出层 mbox 的实例
	 */
	show : function(uniqueId, title, content, boxOptions) {
		if (cache.boxes.uniqueId) {
			cache.boxes.uniqueId.show();
			return;
		}
		var options = $extend(boxOptions, {title : title});
		loader.use('mbox', function() {
			cache.boxes.uniqueId = new MBox(content, options)
		});
	},
	/**
	 * 根据指定标题、指定的 Request Ajax调用，显示一个浮出层 mbox
	 * 将Request调用后获得的文本作为该浮出层的内容文本
	 *
	 * @param uniqueId   为当前页面中的这个浮出层起一个唯一的名字
	 * @param title      浮出层标题
	 * @param request    Ajax远程调用， 必须为Request 的实例，建议设置好 url, method(可选，缺省为post), data(可选，缺省为空)
	 * @param boxOptions 浮出层的选项，以及事件
	 *        常用选项包括
	 *        1. width : 宽度像素
	 *        2. onInit: 浮出层初始化后腰执行的函数，函数有且只有一个缺省参数，为该浮出层 mbox 的实例
	 */
	showAjax : function (uniqueId, title, request, boxOptions) {
		if (cache.boxes.uniqueId) {
			cache.boxes.uniqueId.show();
			return;
		}
		var options = $extend(boxOptions, {showAfterInit: true, title : title});
		loader.use('mbox', function() {
			cache.boxes.uniqueId = new MBox(request, options)
		});
	}
};
/**
 * Form 通过 Ajax 方式提交的便捷函数封装
 * 用户不应当直接使用 AjaxForm 对象，而应该使用这个封装中的函数
 */
var ajaxForm = {
	/**
	 * 将一个 HTML Form 初始化为使用 ajax 方式提交，不刷新当前页面
	 * @param form     HTML Form Element
	 * @param options  选项以及事件
	 *        常用选项包括
	 *        1. onRequest : 函数，负责Form提交之前的客户端数据验证。函数必须返回 boolean 值。
	 *                       如果返回 false，则 Form 不会提交；如果返回 true，则以 Ajax 方式提交 Form
	 *                       函数没有传入参数，但可以在函数中使用 this, this 指向待验证提交的 Form Element
	 *        2. onComplete: 函数。用于 Form 提交完成后，处理服务器返回的 JSON 对象或文本
	 *                       函数可以有两个传入参数： 1) responseJSON 服务器返回文本转换成的JSON对象
	 *                                           2) responseText 服务器返回的文本(例如一个JSON形式编码的字符串)
	 *        3. loginBeforeSubmit: 布尔值。如果为true，则要求用户试图提交之前，必须处于已登录状态，否则应弹出登录浮出层。
	 *                              如果为 false 或不指定，则不要求用户处于已登录状态。
	 */
	init : function(form, options) {
		loader.use('form', function() {
			new AjaxForm(form, options);
		});
	}
};
/**
 * 弹出登录浮出层的便捷函数封装
 */
var login = {
	/**
	 * 事先指定的函数数组，可以往里 push 任意数量的函数
	 * 在登录成功之后会依次执行
	 */
	callbacks:[],
	/**
	 * 弹出登录浮出层
	 * @param callback       函数，登录成功之后执行
	 * @param optionOverrids 浮出层设置，常用设置如下
	 *                       1. title : 设置浮出层的标题栏文字
	 *                       2. width : 浮出层的宽度像素
	 *                       3. overlay : 遮罩的设置（缺省为 0.3 透明黑底），如果不需要遮罩，可设置为 false
	 */
	popupLogin : function(callback, optionOverrids) {
		if (userId) {
			callback();
			return false;
		}
		var options = $merge({
			title : '登录音悦台',
			width : 296,
			overlay:{
				"color" : "#000",
				"opacity" : "0.3"
			}
		}, optionOverrids);
		var request = new Request({
			url : '/ajax/login-form-new',
			method : 'post'
		});
		var uniqueId = ('popupLogin' + callback.toString() + options.toString()).toSHA1();
		mbox.showAjax(uniqueId, '登录音悦台', request, {
			width:296,
			overlay:options.overlay,
			onInit : function(box) {
				var form = box.getElement('form[name=pop-form-login]');
				if (!form) {
					return;
				}
				ajaxForm.init(form, {
					onComplete: function(action) {
						if (action.error) {
							var login_error = box.getElement('div[name=login_error]');
							login_error.setStyle('display', 'block');
							login_error.getElement('em').set('html', action.message);
							return false;
						}
						box.hide();
						login.loginComplete(action);
						callback();
					}
				});
				if (Browser.Engine.trident) {
					form.addEvent('keydown', function(event) {
						if (event.key == "enter") {
							$(this).fireEvent('submit');
						}
					});
				}
				box.getElements('input[name=email],input[name=password]').each(function(item) {
					var val = item.get('value');
					item.addEvents({
						'focus' : function() {
							if (item.get('value') == val) {
								item.set('value', '');
							}
							item.getParent().addClass('focus');
						},
						'blur' : function() {
							if (item.get('value') == val || !item.get('value')) {
								item.getParent().removeClass('focus');
								item.set('value', val);
							}
						}
					});
				});
			},
			onShow : function(box) {
				box.getElement('input[name=email]').focus();
			},
			onHide : function(box) {
				if (options.hideCallback) {
					options.hideCallback();
				}
				var login_error = box.getElement('div[name=login_error]');
				login_error.setStyle('display', 'none');
				var passwordInput = box.getElement('input[name=password]');
				passwordInput.value = "";
			}
		});
	},
	/**
	 * (通常在页面加载完毕后)进行用户 Ajax 登录的操作
	 * 登录完成后会依次执行 callbacks 中放置的函数
	 */
	refreshLoginInfo: function() {
		new Request.JSON({
			url: '/login-info',
			onSuccess: function(result) {
				if (!result.error && result.userId != 0) {
					login.loginComplete(result);
				}
			}.bind(this)
		}).send();
	},
	/* private */ loginComplete : function(action) {
		userId = action.userId;
		var callbackLength, i, callbackFunc;
		if (login.callbacks && login.callbacks.length > 0) {
			callbackLength = login.callbacks.length;
			for (i = 0; i < callbackLength; i++) {
				callbackFunc = login.callbacks.shift();
				callbackFunc(action);
			}
		}
		if (login.callonceCallbacks && login.callonceCallbacks.length > 0) {
			callbackLength = login.callonceCallbacks.length;
			for (i = 0; i < callbackLength; i++) {
				callbackFunc = login.callonceCallbacks.shift();
				callbackFunc(action);
			}
		}
	},
	/* private */ logout : function() {

	},
	/* private */ prepareCallback : function(callback) {
		login.callonceCallbacks.empty();
		if (callback) {
			login.callonceCallbacks.push(callback);
		}
		login.callonceCallbacks.push(function() {
			cache.popupLogin.hide();
		});
		cache.popupLogin.show();
	},
	/* private */ callonceCallbacks:[]
};
/**
 * 为数组声明一个便捷方法
 */
Array.implement({
	/**
	 * 使用指定的分隔符，将数组连接为字符串
	 * 例如[12,'cat',34]，指定.为分隔符，会得到 '12.cat.34'
	 * @param delimiter
	 */
	explode: function(delimiter) {
		var output = "";
		this.each(function(item, index) {
			if (index > 0) {
				output += delimiter;
			}
			output += item.toString();
		});
		return output;
	}
});
(function() {
	var transforms = {
		'rotateLeft': function(a, b) {
			return (a << b) | (a >>> (32 - b));
		},
		'hex': function(a) {
			var b, c, result = '';

			for (b = 7; b >= 0; b--) {
				c = (a >>> (b * 4)) & 0x0f;
				result += c.toString(16);
			}

			return result;
		}
	};

	function utf8(string) {
		var a, b, result = '',
				from = String.fromCharCode;
		for (a = 0; b = string.charCodeAt(a); a++) {
			if (b < 128) {
				result += from(b);
			}
			else {
				if ((b > 127) && (b < 2048)) {
					result += from((b >> 6) | 192);
					result += from((b & 63) | 128);
				}
				else {
					result += from((b >> 12) | 224);
					result += from(((b >> 6) & 63) | 128);
					result += from((b & 63) | 128);
				}
			}
		}
		return result;
	}

	function sha1(string) {
		var a, b, c,
				h1 = 0x67452301,
				h2 = 0xEFCDAB89,
				h3 = 0x98BADCFE,
				h4 = 0x10325476,
				h5 = 0xC3D2E1F0,
				t1, t2, t3, t4, t5;
		string = utf8(string);
		var length = string.length,
				words = new Array(),
				buffer = new Array(80),
				code = function(a) {
					return string.charCodeAt(a);
				},
				assign = function(c) {
					t5 = t4;
					t4 = t3;
					t3 = transforms.rotateLeft(t2, 30);
					t2 = t1;
					t1 = c
				};
		for (a = 0; a < length - 3; a += 4) {
			b = code(a) << 24 | code(a + 1) << 16 | code(a + 2) << 8 | code(a + 3);
			words.push(b);
		}
		switch (length % 4) {
			case 0:
				a = 0x080000000;
				break;
			case 1:
				a = code(length - 1) << 24 | 0x0800000;
				break;
			case 2:
				a = code(length - 2) << 24 | code(length - 1) << 16 | 0x08000;
				break;
			case 3:
				a = code(length - 3) << 24 | code(length - 2) << 16 | code(length - 1) << 8 | 0x80;
				break;
		}
		words.push(a);
		while ((words.length % 16) != 14) {
			words.push(0);
		}
		words.push(length >>> 29);
		words.push((length << 3) & 0x0ffffffff);
		for (c = 0; c < words.length; c += 16) {
			for (a = 0; a < 16; a++) {
				buffer[a] = words[c + a];
			}
			for (a = 16; a <= 79; a++) {
				buffer[a] = transforms.rotateLeft(buffer[a - 3] ^ buffer[a - 8] ^ buffer[a - 14] ^ buffer[a - 16], 1);
			}
			t1 = h1;
			t2 = h2;
			t3 = h3;
			t4 = h4;
			t5 = h5;
			for (a = 0; a <= 19; a++) {
				assign((transforms.rotateLeft(t1, 5) + ((t2 & t3) | (~t2 & t4)) + t5 + buffer[a] + 0x5A827999) & 0x0ffffffff);
			}
			for (a = 20; a <= 39; a++) {
				assign((transforms.rotateLeft(t1, 5) + (t2 ^ t3 ^ t4) + t5 + buffer[a] + 0x6ED9EBA1) & 0x0ffffffff);
			}
			for (a = 40; a <= 59; a++) {
				assign((transforms.rotateLeft(t1, 5) + ((t2 & t3) | (t2 & t4) | (t3 & t4)) + t5 + buffer[a] + 0x8F1BBCDC) & 0x0ffffffff);
			}
			for (a = 60; a <= 79; a++) {
				assign((transforms.rotateLeft(t1, 5) + (t2 ^ t3 ^ t4) + t5 + buffer[a] + 0xCA62C1D6) & 0x0ffffffff);
			}
			h1 = (h1 + t1) & 0x0ffffffff;
			h2 = (h2 + t2) & 0x0ffffffff;
			h3 = (h3 + t3) & 0x0ffffffff;
			h4 = (h4 + t4) & 0x0ffffffff;
			h5 = (h5 + t5) & 0x0ffffffff;
		}
		return (transforms.hex(h1) + transforms.hex(h2) + transforms.hex(h3) + transforms.hex(h4) + transforms.hex(h5)).toLowerCase();
	}

	String.implement({
		/**
		 * 提供字符串的 utf8 形式
		 * 用法： 'mystring'.toUTF8();
		 */
		'toUTF8': function() {
			return utf8(this);
		},
		/**
		 * 提供字符串的 sha1 散列值
		 * 用法： 'mystring'.toSHA1();
		 */
		'toSHA1': function() {
			return sha1(this);
		}
	});
})();
var floatUserInfoBox;
var searchKeyHint = "从你感兴趣的开始...";
function bindGlobalSearchForm(form) {
	var searchKeyText = $(form["key"]);
	if (searchKeyText == null) {
		searchKeyText = $(form["keyword"]);
	}
	searchKeyText.addEvent("focus", function() {
		if (this.value == searchKeyHint) {
			this.value = "";
			this.setStyle("color", "#333333");
		}
	}.bind(searchKeyText));
	searchKeyText.addEvent("click", function() {
		if (this.value == searchKeyHint) {
			this.value = "";
			this.setStyle("color", "#333333");
		}
	}.bind(searchKeyText));
	searchKeyText.addEvent("blur", function() {
		if (this.value == "") {
			this.value = searchKeyHint;
			this.setStyle("color", "#999999");
		}
	}.bind(searchKeyText));
}
function show_user_info(index) {
	if (floatUserInfoBox) {
		floatUserInfoBox.dispose();
	}
	var divId = "item_div_" + index;
	var userInfoDiv = "user_info_" + index;
	if ($(divId) && $(userInfoDiv)) {
		var position = $(divId).getPosition();
		floatUserInfoBox = new Element("div");
		floatUserInfoBox.set("html", $(userInfoDiv).get("html"));
		floatUserInfoBox.addEvent("mouseleave", function() {
			this.dispose();
		}.bind(floatUserInfoBox));
		floatUserInfoBox.setStyles({
			position: "absolute",
			overflow: "hidden",
			display: "block",
			width: "0px",
			height: "0px",
			"z-index": 100,
			left: position.x.toInt() - 2 + "px",
			top: position.y.toInt() - 2 + "px"
		});
		floatUserInfoBox.inject(document.body);
		new Fx.Morph(floatUserInfoBox, {duration: 300, transition: Fx.Transitions.Sine.easeIn}).start({
			'width': [0, 420],
			'height': [0, 220]
		}).start();
	}
}
function addPlaylistImageHover(imageDiv) {
	imageDiv.addEvent("mouseenter", function() {
		var floatMenu = this.getElement("div.pl_image_float_menu");
		if (floatMenu) {
			floatMenu.style.display = "block";
		}
	});
	imageDiv.addEvent("mouseleave", function() {
		var floatMenu = this.getElement("div.pl_image_float_menu");
		if (floatMenu) {
			floatMenu.style.display = "none";
		}
	});
}
function addVideoImageHover(imageDiv) {
	imageDiv.addEvent("mouseenter", function() {
		var floatMenu = this.getElement("div.video_image_float_menu");
		if (floatMenu) {
			floatMenu.style.display = "block";
		}
	});
	imageDiv.addEvent("mouseleave", function() {
		var floatMenu = this.getElement("div.video_image_float_menu");
		if (floatMenu) {
			floatMenu.style.display = "none";
		}
	});
}
function addAlbumImageHover(imageDiv) {
	imageDiv.addEvent("mouseenter", function() {
		var floatMenu = this.getElement("div.album_image_float_menu");
		if (floatMenu) {
			floatMenu.style.display = "block";
		}
	});
	imageDiv.addEvent("mouseleave", function() {
		var floatMenu = this.getElement("div.album_image_float_menu");
		if (floatMenu) {
			floatMenu.style.display = "none";
		}
	});
}
function addPhotoSmallHover(image) {
	image.addEvent("mouseenter", function() {
		this.addClass("photo_small_hover");
	});
	image.addEvent("mouseleave", function() {
		this.removeClass("photo_small_hover");
	});
}
function addPhotoMediumHover(image) {
	image.addEvent("mouseenter", function() {
		this.addClass("photo_medium_hover");
	});
	image.addEvent("mouseleave", function() {
		this.removeClass("photo_medium_hover");
	});
}
function send_apply_fan(fid) {
	var uniqueId = 'sendApplyFan' + fid;
	var request = new Request({
		url: '/fan/ajax/send-fan-apply',
		method: 'get',
		data: 'fid=' + fid
	});
	login.popupLogin(function() {
		mbox.showAjax(uniqueId, "申请团长", request, {
			width: 440,
			onInit : function(mbox) {
				var form = mbox.getElement("form");
				form.action = "/fan/apply-for-fan";
				ajaxForm.init(form, {
					onRequest: function() {
						var field = form.elements['content'];
						if (field.value.trim() == "") {
							errorMessage("请输入申请的理由");
							field.focus();
							return false;
						}
						if (field.value.trim().length > 1000) {
							errorMessage("内容不能超过1000字");
							field.focus();
							return false;
						}
						return true;
					},
					onComplete: function(result) {
						if (!result.error) {
							successMessage("申请已发送成功，请等待审核!");
							mbox.hide();
						} else {
							errorMessage(result.message);
						}
					}
				});
			}
		})
	}, null);
}
function send_resign_fan(fid) {
	var uniqueId = 'resignApplyFan' + fid;
	var request = new Request({
		url: '/fan/ajax/send-fan-apply',
		method: 'get',
		data: 'fid=' + fid
	});
	login.popupLogin(function() {
		mbox.showAjax(uniqueId, "辞去团长", request, {
			width: 440,
			onInit : function(mbox) {
				var form = mbox.getElement("form");
				form.action = "/fan/resign-for-fan";
				ajaxForm.init(form, {
					onRequest: function() {
						var field = form.elements['content'];
						if (field.value.trim() == "") {
							errorMessage("请输入辞职的理由");
							field.focus();
							return false;
						}
						if (field.value.trim().length > 1000) {
							errorMessage("内容不能超过1000字");
							field.focus();
							return false;
						}
						return true;
					},
					onComplete: function(result) {
						if (!result.error) {
							successMessage("辞职申请已发送成功，请等待审核!");
							mbox.hide();
						} else {
							errorMessage(result.message);
						}
					}
				});
			}
		})
	}, null);
}
function send_message(friendId) {
	var uniqueId = 'sendMessage' + friendId;
	var request = new Request({
		url: '/home/message/ajax/write-message',
		method: 'get',
		data: 'friendId=' + friendId
	});
	login.popupLogin(function() {
		mbox.showAjax(uniqueId, "发送短消息", request, {
			width: 440,
			onInit : function(mbox) {
				var form = mbox.getElement("form");
				form.action = "/fan/resign-for-fan";
				ajaxForm.init(form, {
					onRequest: function() {
						var field = form.elements['content'];
						if (field.value.trim() == "") {
							errorMessage("请输入消息内容");
							field.focus();
							return false;
						}
						if (field.value.trim().length > 1000) {
							errorMessage("消息内容不能超过1000字");
							field.focus();
							return false;
						}
						return true;
					},
					onComplete: function(action) {
						if (!action.error) {
							successMessage("短消息发送成功");
							mbox.hide();
						} else {
							errorMessage(action.message);
						}
					}
				});
			}
		})
	}, null);
}
function follow(friendId, callback) {
	login.popupLogin(function() {
		if (userId == friendId) {
			errorMessage("似乎没必要关注自己哦");
			return
		}
		var requestUrl = "/home/friend/follow";
		var params = "friendId=" + friendId;
		new Request.JSON({
			url: requestUrl,
			method : 'post',
			data : params,
			onSuccess : function(action) {
				if (!action.error) {
					successMessage(action.message);
					if (callback) {
						callback();
					}
				} else {
					errorMessage(action.message);
				}
			}
		}).send();
	}, null);
}
function reloadDocument(delay) {
	delay = delay || 2000;
	setTimeout(function () {
		window.location.href = window.location.href;
	}, delay);
}
function show_feed_content(sessionId) {
	var link = $("feed_link_" + sessionId);
	var feedDiv = $("feed_content_" + sessionId);
	if (!link || !feedDiv) {
		return;
	}
	if (feedDiv.getStyle("display") == "none") {
		var requestUrl = "/home/message/read-message-session";
		var params = "sessionId=" + sessionId;
		new Request.HTML({
			url: requestUrl,
			method : 'post',
			data : params,
			update: feedDiv,
			onSuccess : function() {
			}
		}).send();
	}
	link.setStyle("font-weight", "normal");
	feedDiv.setStyle("display", "");
}
function show_notification_content(sessionId) {
	var link = $("notification_link_" + sessionId);
	var feedDiv = $("notification_content_" + sessionId);
	if (!link || !feedDiv) {
		return;
	}
	if (feedDiv.getStyle("display") == "none") {
		var requestUrl = "/home/message/read-message-session";
		var params = "sessionId=" + sessionId;
		new Request.JSON({
			url: requestUrl,
			method : 'post',
			data : params,
			onSuccess : function() {
			}
		}).send();
	}
	link.setStyle("font-weight", "normal");
	feedDiv.setStyle("display", "");
}
function onSearchFormSubmit() {
	var glolbaSearchForm = $("global_search_form");
	var searchKey = glolbaSearchForm["key"].value.trim();
	if (searchKey == searchKeyHint) {
		glolbaSearchForm["key"].value = "";
	}
	return true;
}
function onSearchFormSubmitNew() {
	var glolbaSearchForm = $("global_search_form");
	var searchKey = glolbaSearchForm["keyword"].value.trim();
	if (searchKey == searchKeyHint) {
		glolbaSearchForm["keyword"].value = "";
	}
	return true;
}
function showComplainDialog() {
	login.popupLogin(function() {
		loader.use("mbox", "form", function() {
			var mbox = new MBox($('siteAdviceDiv').get('html'), {
				title : '请说明投诉团长的理由',
				width: 408,
				className: 'suggestnew',
				onInit: function(me) {
					me.initContent = "我要投诉**团长**";
					var siteAdviceForm = me.getElement('form');
					if (!siteAdviceForm) {
						return;
					}
					/*var cancelButton = me.getElement('[name=cancel]');
					 cancelButton.addEvent("click", function() {
					 me.hide();
					 });*/
					var siteAdviceContent = $(siteAdviceForm['content']);
					siteAdviceContent.set("html", me.initContent);
					siteAdviceContent.addClass('hint_color');
					siteAdviceContent.addEvent("focus", function() {
						if (this.value == me.initContent) {
							this.value = "";
							this.removeClass('hint_color');
						}
					}.bind(siteAdviceContent));
					siteAdviceContent.addEvent("click", function() {
						if (this.value == me.initContent) {
							this.value = "";
							this.removeClass('hint_color');
						}
					}.bind(siteAdviceContent));
					siteAdviceContent.addEvent("blur", function() {
						if (this.value == "") {
							this.value = me.initContent;
							this.addClass('hint_color');
						}
					}.bind(siteAdviceContent));
					var warningInfo = me.getElement('[name=waring_info]');
					new AjaxForm(siteAdviceForm, {
						onRequest: function() {
							var field = siteAdviceForm.elements['content'];
							if (field.value.trim() == "" || field.value.trim() == me.initContent) {
								warningInfo.set('html', '请输入您要投诉的内容');
								warningInfo.setStyle('display', '');
								field.addEvent('focus', function() {
									warningInfo.setStyle('display', 'none');
								});
								return false;
							}
							return true;
						},
						onComplete: function(action) {
							if (!action.error) {
								successMessage("您的投诉已经提交成功，我们会尽快处理并通过站内消息回复。");
								me.hide();
							} else {
								warningInfo.set('html', 'action.message');
								warningInfo.setStyle('display', '');
							}
						}
					});
				}
			});
			mbox.show();
		});
	}, {});
}
function showAdviceDialog() {
	login.popupLogin(function() {
		loader.use("mbox", "form", function() {
			var mbox = new MBox($('siteAdviceDiv').get('html'), {
				title : '欢迎留下您的意见，经采用后有积分奖励哦',
				width: 408,
				className: 'suggestnew',
				onInit: function(me) {
					me.initContent = "我们非常感谢您的用心，我们的点滴进步离不开您的建议反馈，音悦台衷心的谢谢您，请在这里描述您遇到的问题。";
					var siteAdviceForm = me.getElement('form');
					if (!siteAdviceForm) {
						return;
					}
					/*var cancelButton = me.getElement('[name=cancel]');
					 cancelButton.addEvent("click", function() {
					 me.hide();
					 });*/
					var siteAdviceContent = $(siteAdviceForm['content']);
					siteAdviceContent.set("html", me.initContent);
					siteAdviceContent.addClass('hint_color');
					siteAdviceContent.addEvent("focus", function() {
						if (this.value == me.initContent) {
							this.value = "";
							this.removeClass('hint_color');
						}
					}.bind(siteAdviceContent));
					siteAdviceContent.addEvent("click", function() {
						if (this.value == me.initContent) {
							this.value = "";
							this.removeClass('hint_color');
						}
					}.bind(siteAdviceContent));
					siteAdviceContent.addEvent("blur", function() {
						if (this.value == "") {
							this.value = me.initContent;
							this.addClass('hint_color');
						}
					}.bind(siteAdviceContent));
					var warningInfo = me.getElement('[name=waring_info]');
					new AjaxForm(siteAdviceForm, {
						onRequest: function() {
							var field = siteAdviceForm.elements['content'];
							if (field.value.trim() == "" || field.value.trim() == me.initContent) {
								warningInfo.set('html', '请输入您的意见或遇到的问题');
								warningInfo.setStyle('display', '');
								field.addEvent('focus', function() {
									warningInfo.setStyle('display', 'none');
								});
								return false;
							}
							return true;
						},
						onComplete: function(action) {
							if (!action.error) {
								successMessage("您的意见已经提交成功，我们会尽快处理并通过站内消息回复。");
								me.hide();
							} else {
								warningInfo.set('html', 'action.message');
								warningInfo.setStyle('display', '');
							}
						}
					});
				}
			});
			mbox.show();
		});
	}, {});
}
function executeInProgress(fn, end, start) {
	start = start || 0;
	if (start == end) {
		return;
	}
	start = start - 0 + Math.ceil((end - start) / 10);
	fn(start);
	setTimeout(function() {
		executeInProgress(fn, end, start);
	}, 5);
}
function doSearch(keyword) {
	var form = $('hidden_search_form');
	form['key'].value = keyword;
	form.submit();
}
function checkTextareaChar(Element, msgBox, max, showLeftCharCount) {
	Element = typeof Element == 'object' ? Element : $(Element);
	msgBox = typeof msgBox == 'object' ? msgBox : $(msgBox);
	var uuid = 'textarea' + (+new Date());
	window[uuid] = setInterval(function() {
		if (!Element) {
			clearInterval(window[uuid]);
			return;
		}
		if (Element.value.length > max) {
			Element.value = Element.value.substr(0, max)
		}
		if (!showLeftCharCount) {
			msgBox.set('html', Element.value.length);
		} else {
			msgBox.set('html', max - Element.value.length);
		}
	}, 250);
	return uuid;
}
function ajax_title_content_form(fanForm, titleMinLength, titleMaxLength, contentMinLength, contentMaxLength
		) {
	if (!fanForm) {
		return;
	}
	var form = $(fanForm);
	if (!form) {
		return;
	}
	ajaxForm.init(form, {
		onRequest: function() {
			tinyMCE.triggerSave();
			var title = form['title'];
			var content = form['content'];
			var titleLength = title.value.trim().length;
			var contentLength = content.value.trim().length;
			if (titleMinLength > 0 && titleLength < titleMinLength) {
				errorMessage("标题应至少有" + titleMinLength + "个字");
				title.focus();
				return false;
			}
			if (titleMaxLength > 0 && titleLength > titleMaxLength) {
				errorMessage("您的标题有点长哦，请控制在" + titleMaxLength + "字以内吧");
				title.focus();
				return false;
			}
			if (contentMinLength > 0 && contentLength < contentMinLength) {
				errorMessage("内容应至少有" + contentMinLength + "个字");
				return false;
			}
			if (contentMaxLength > 0 && contentLength > contentMaxLength) {
				errorMessage("您的内容有点长哦，请控制在" + contentMaxLength + "字以内吧");
				return false;
			}
			successMessage("正在发布主题，请稍候...");
			return true;
		},
		onComplete: function(action) {
			if (!action.error) {
				setTimeout(function () {
					successMessage("发表成功,正在更新页面内容，请稍候...");
				}, 2000);
				reloadDocument(2000);
			} else {
				setTimeout(function () {
					errorMessage(action.message);
				}, 2000);
			}
		}
	});
}
function checkFlash() {
	var hasFlash = 0;
	try {
		new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
		hasFlash = 1;
	} catch (e) {
		if (navigator.plugins && navigator.plugins.length > 0 && navigator.plugins["Shockwave Flash"]) {
			hasFlash = 1;
		}
	}
	return hasFlash;
}
function loadFlash(url, boxId, id, width, height, flashvars, write, options) {
	id = id || 'flashplayer';
	width = width || '100%';
	height = height || '100%';
	flashvars = flashvars || '';
	var wmd = 'opaque';
	if (options) {
		wmd = options['wmode'] || 'opaque';
	}
	var flashCode;
	if (Browser.Engine.trident) {
		flashCode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ' +
		            'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" ' +
		            'width="' + width + '" height="' + height + '" id="' + id + '" name="' + id + '">' +
		            '<param name="allowScriptAccess" value="always" />' +
		            '<param name="allowFullScreen" value="true" />' +
		            '<param name="movie" value="' + url + '" />' +
		            '<param name="loop" value="true" />' +
		            '<param name="menu" value="false" />' +
		            '<param name="wmode" value=' + wmd + ' />' +
		            '<param name="quality" value="high" />' +
		            '<param name="bgcolor" value="#000000" />' +
		            '<param name="flashvars" value="' + flashvars + '" />' +
		            '</object>';
	} else {
		flashCode = '<embed width="' + width + '" height="' + height + '" flashvars="' + flashvars +
		            '" bgcolor="#000000" allowfullscreen="true" allowscriptaccess="always" wmode="' + wmd + '" id="' + id + '" name="' +
		            id +
		            '" src="' + url + '" />';
	}
	if (!checkFlash()) {
		flashCode = '您的浏览器不支持Flash';
	}
	if (write) {
		document.write(flashCode);
	} else {
		window.addEvent('domready', function() {
			$(boxId).set('html', flashCode);
		});
	}
}
function initRichTextArea(textAreaId) {
	if (!tinyMCE) {
		alert("should include tinymce.js before site-common.js");
		return;
	}
	tinyMCE.init({
		// General options
		mode:"exact",
		elements:textAreaId,
		theme : "advanced",
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,link,forecolor,backcolor,emotions,image,media,justifyleft,justifycenter,justifyright,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_fonts : '\u5B8B\u4F53=simsun;\u9ED1\u4F53=simhei;\u6977\u4F53=\u6977\u4F53;\u96B6\u4E66=\u96B6\u4E66;\u5E7C\u5706=\u5E7C\u5706;\u4EFF\u5B8B=\u4EFF\u5B8B_GB2312;\u5FAE\u8F6F\u96C5\u9ED1=microsoft yahei;Arial=arial,helvetica,sans-serif;Comic Sans MS=comic sans ms,sans-serif;Georgia=georgia,times new roman,times,serif;Courier New=courier new,courier,monospace;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Verdana=verdana,geneva;',
		theme_advanced_font_sizes : "\u4E00\u53F7=26pt;\u5C0F\u4E00=24pt;\u4E8C\u53F7=22pt;\u5C0F\u4E8C=18pt;\u4E09\u53F7=16pt;\u5C0F\u4E09=15pt;\u56DB\u53F7=14pt;\u5C0F\u56DB=12pt;\u4E94\u53F7=10pt;\u5C0F\u4E94=9pt",
		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",
		language : "zh",
		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",
		// Style formats
		style_formats : [
			{title : 'Bold text', inline : 'b'},
			{title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
			{title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
			{title : 'Example 1', inline : 'span', classes : 'example1'},
			{title : 'Example 2', inline : 'span', classes : 'example2'},
			{title : 'Table styles'},
			{title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
		],

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}
/**
 * 顶部状态栏（含登录处理）
 */
var topbar = {
	links : [
		{
			info:{
				"src":"",
				"className":"topBarAvatar",
				"text":"",
				"link":"#"
			},
			links:[
				{
					"link":"/home/profile/avatar",
					"className":"icon_avatar",
					"text":"修改头像"
				},
				{
					"link":"/home/profile",
					"className":"icon_userInfo",
					"text":"修改个人资料"
				},
				{
					"link":"/home/profile/password",
					"className":"icon_userPassword",
					"text":"修改密码"
				}
			]
		},
		{
			info:{
				"className":"icon_newMsg",
				"text":"",
				"link":"/home/message"
			},
			links:[
				{
					"link":"/home/message",
					"className":"icon_inbox",
					"text":"收件箱"
				},
				{
					"link":"/home/message/notification",
					"className":"icon_information",
					"text":"提醒"
				},
				{
					"link":"/home/message/announcement",
					"className":"icon_notice",
					"text":"公告"
				}
			]
		},
		{
			info:{
				"text":"我的",
				"link":"#"
			},
			links:[
				{
					"link":"/u/",
					"className":"icon_home",
					"text":"<strong>我的展示页</strong>"
				},
				{
					"link":"/home/blog/write",
					"className":"icon_blog",
					"text":"发表日志"
				},
				{
					"link":"/home/album",
					"className":"icon_photoUpload",
					"text":"上传照片"
				},
				{
					"link":"/home/fanclub",
					"className":"icon_group",
					"text":"我的饭团"
				},
				{
					"link":"/home",
					"className":"icon_yinyuetai",
					"text":"<strong>我的音悦台</strong>"
				},
				{
					"link":"/home/mv",
					"className":"icon_mv",
					"text":"我的MV"
				},
				{
					"link":"/home/pl",
					"className":"icon_playlist",
					"text":"我的悦单"
				},
				{
					"link":"/home/friend",
					"className":"icon_friend",
					"text":"我的好友"
				}
			]
		}
	],
	toggleLoginForm: function() {
		var topBarLogin = $('topBarLogin');
		var topBarLoginA = topBarLogin.getElement('a');
		topBarLogin.hasClass('topBarLoginBtn') ? topBarLogin.removeClass('topBarLoginBtn') : topBarLogin.addClass('topBarLoginBtn');
		topBarLoginA.blur();
	},
	init : function() {
		var topBarLogin = $('topBarLogin');
		var topBarLoginA = topBarLogin.getElement('a');
		topBarLoginA.addEvent('click', function() {
			this.toggleLoginForm();
			return false;
		}.bind(this));
		$$('#pop-username-top,#pop-password-top').each(function(item) {
			var val = item.get('value');
			item.addEvents({
				'focus' : function() {
					if (item.get('value') == val) {
						item.set('value', '');
					}
					item.getParent().addClass('focus');
				},
				'blur' : function() {
					if (item.get('value') == val || !item.get('value')) {
						item.getParent().removeClass('focus');
						item.set('value', val);
					}
				}
			});
		});
		$$('#topBarLoginForm input').each(function(item) {
			if (item.hasClass('i_text')) {
				item.addEvents({
					'blur' : function() {
						if (item.get('value') == '') {
							item.set('value', item.get('defaultValue'));
							item.removeClass('focus');
						}
					},
					'focus' : function() {
						if (item.get('value') == item.get('defaultValue')) {
							item.set('value', '');
						}
					}
				});
			}
		});
		if (Browser.Engine.trident4) {
			$('topBarLoginSubmit').addEvents({
				'mouseover':function() {
					this.className = 'hover';
				},
				'mouseout':function() {
					this.className = '';
				}
			});
			topbar.fixIE6($$('#topBarUserPanel>ul>li'));
		}
		login.callbacks.push(function(action) {
			topbar.toggleLoginForm();
			topbar.links[0].info.src = action.headImg;
			topbar.links[0].info.text = action.userName;
			topbar.links[0].info.link = '/home';
			topbar.links[1].info.text = action.messageSessionsInfo.totalUnreadCount;
			if (topbar.links[1].info.text) {
				topbar.links[1].info.src = '/images/core/new_msg.gif';
			}
			topbar.links[2].links[0].link = '/u/' + action.userId;
			if ($('topBarUserPanel')) {
				var ul = $('topBarUserPanel').getElement('ul');
				ul.innerHTML = topbar.makeHtml() + ul.innerHTML;
				topbar.fixIE6($$('#topBarUserPanel>ul>li'));
				$('topBarLogin').setStyle('display', 'none');
				$('topBarReg').setStyle('display', 'none');
				$('topBarLogined').setStyle('display', 'inline');
			}
		});
		ajaxForm.init($('topBarLoginForm'), {
			onRequest: function() {
				return true;
			},
			onComplete: function(action) {
				if (action.error) {
					var login_error = $('login_error');
					login_error.setStyle('display', 'block');
					login_error.getElement('em').set('html', action.message);
					return false;
				}
				login.loginComplete(action);
			}
		});
	},
	makeHtml : function() {
		var links = topbar.links;
		var html = '';
		for (var i = 0 , len = links.length; i < len; i++) {
			var img = '';
			if (links[i].info.className) {
				var src = links[i].info.src || '/images/core/opacity.png';
				img = '<img src=" ' + src + ' " class=" ' + links[i].info.className + ' " alt=" ' + links[i].info.text + ' "/>';
			}
			html += '<li class="topBarUserPanelOption loginedOption">';
			html += '<a href="' + links[i].info.link + '" class="topBarUserPanelOptionA">' + img + '<em>' + links[i].info.text +
			        '</em><img src="/images/core/opacity.png" alt="" class="icon_selectDown"/><!--[if lt IE 9]><span></span><![endif]--></a>';
			html += topbar.makeHtml2(links[i].links);
			html += '</li>';
		}
		return html;
	},
	makeHtml2 : function(links) {
		var html = '<div class="topBarUserSelect"><!--[if lt IE 9]><span class="topBarUserSelectBgT"></span><![endif]--><ul>';
		for (var i = 0 , len = links.length; i < len; i++) {
			html += '<li><a href="' + links[i].link + '"><img src="/images/core/opacity.png" class="' + links[i].className + '" alt=""/> ' +
			        links[i].text + ' </a></li>'
		}
		html += '</ul><!--[if lt IE 9]><span class="topBarUserSelectBgB"></span><![endif]--></div>';
		return html;
	},
	fixIE6 : function(list) {
		if (Browser.Engine.trident4) {
			list.each(function(item) {
				item.removeEvents('mouseenter');
				item.removeEvents('mouseleave');
				item.addEvents({
					"mouseenter":function() {
						item.addClass('hover');
					},
					"mouseleave":function() {
						item.removeClass('hover');
					}
				});
			});
		}
	}
};
window.addEvent('domready', function() {
	if ($('footKeyword')) {
		loader.use('suggest', function() {
			new Suggest($('footKeyword'), {
				maxResults:5
			});
		});
	}
	if ($('headKeyword')) {
		loader.use('suggest', function() {
			new Suggest($('headKeyword'));
		});
	}
	if ($('topBarKeyword')) {
		loader.use('suggest', function() {
			new Suggest($('topBarKeyword'), {
				maxResults:5
			});
		});
	}
	if ($('topBarLogin')) {
		topbar.init();
	}
	login.refreshLoginInfo();
	if ($('topBarProposal')) {
		$('topBarProposal').addEvent('click', function() {
			showAdviceDialog();
			return false;
		});
	}
	/* below this is js hack for IE6 */
	if (Browser.Engine.trident4) {
		$$("#menu li").each(function(item) {
			item.addEvent("mouseenter", function() {
				this.addClass("lihover");
			});
			item.addEvent("mouseleave", function() {
				this.removeClass("lihover");
			});
		});
		$$("#menume_div p").each(function(item) {
			item.addEvent("mouseenter", function() {
				this.addClass("phover");
			});
			item.addEvent("mouseleave", function() {
				this.removeClass("phover");
			});
		});
	}
	/* above is js hack for IE6 */
	if ($("s_value")) {
		$("s_value").addEvent("focus", function() {
			if (this.value == "输入关键词查找MV") {
				this.value = "";
				this.style.color = "#333333";
			}
		});
		$("s_value").addEvent("blur", function() {
			if (this.value == "") {
				this.value = "输入关键词查找MV";
				this.style.color = "#CCCCCC";
			}
		});
	}
	if ($("s_value2")) {
		$("s_value2").addEvent("focus", function() {
			if (this.value == "输入关键词查找MV") {
				this.value = "";
				this.style.color = "#333333";
			}
		});
		$("s_value2").addEvent("blur", function() {
			if (this.value == "") {
				this.value = "输入关键词查找MV";
				this.style.color = "#CCCCCC";
			}
		});
	}
	$$("a.user_head_image_plus").each(function(item) {
		item.fixpng();
	});
	// todo below code was used only in home/album/view.jsp && person/photo.jsp
	$$("[hoverClass]").each(function(item) {
		item.addEvent("mouseenter", function() {
			this.addClass(item.getProperty("hoverClass"));
		});
		item.addEvent("mouseleave", function() {
			this.removeClass(item.getProperty("hoverClass"));
		});
	});
	// above code was used only in home/album/view.jsp && person/photo.jsp
	// playlist image hover play menu
	$$("div.pl_image_box").each(function(item) {
		addPlaylistImageHover(item);
	});
	// video image hover play menu
	$$("div.video_image_box").each(function(item) {
		addVideoImageHover(item);
	});
	// album image hover menu
	$$("div.album_image_box").each(function(item) {
		addAlbumImageHover(item);
	});
	// album image hover menu
	$$("img.photo_small").each(function(item) {
		addPhotoSmallHover(item);
	});
	$$("img.photo_medium").each(function(item) {
		addPhotoMediumHover(item);
	});
	// user info box
	$$("[infoBoxIndex]").each(function(item) {
		var index = item.getProperty("infoBoxIndex");
		var plus = $("plus_" + index);
		if (plus) {
			item.addEvent("mouseenter", function() {
				plus.setStyle("display", "inline");
			});
			item.addEvent("mouseleave", function() {
				plus.setStyle("display", "none");
			});
		}
	});
	if ($("global_search_form")) {
		bindGlobalSearchForm($("global_search_form"));
	}
	if ($("global_search_form_bottom")) {
		bindGlobalSearchForm($("global_search_form_bottom"));
	}
});
function addBookmark(url, title) {
	try {
		window.external.AddFavorite(url, title);
		return false;
	} catch(e) {
		try {
			window.sidebar.addPanel(title, url, "");
			return false;
		} catch(err) {
			//alert('暂不支持此浏览器');
			return false;
		}
	}
}
function setHomepage() {
	try {
		document.body.style.behavior = 'url(#default#homepage)';
		document.body.setHomePage('http://www.yinyuetai.com');
	} catch(e) {
		alert("暂不支持此浏览器");
	}
}
function showQqLikeHint() {
	window.addEvent('domready', function() {
		setTimeout(function() {
			$('qqlikePob').setStyle('display', 'block');
			setTimeout(function() {
				$('qqlikePob').setStyle('display', 'none');
			}, 15000);
		}, 3000);
		$('qqlikePobClose').addEvent('click', function() {
			$('qqlikePob').setStyle('display', 'none');
			var requestUrl = "/set-user-preference";
			var params = "method=setShowQqLikeHint&value=false";
			new Request.JSON({
				url: requestUrl,
				method : 'post',
				data : params,
				onSuccess : function(action) {
					if (action.error) {
						errorMessage(action.message);
					}
				}
			}).send();
			return false;
		})
	});
}
function openWindowCenter(url, width, height) {
	var windowSize = window.getSize();
	var windowWidth = windowSize.x;
	var windowHeight = windowSize.y;
	var offsetX, offsetY;
	if (width >= windowWidth) {
		offsetX = 0;
	} else {
		offsetX = (windowWidth - width) / 2;
	}
	if (height >= windowWidth) {
		offsetY = 0;
	} else {
		offsetY = (windowHeight - height) / 2;
	}
	window.open(url, 'newwindow',
	            'height=' + height + ',width=' + width +
	            ',left=' + offsetX + ',top=' + offsetY +
	            ',toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
}
function openSinaAuthWindow() {
	openWindowCenter('/api/login/sina-auth', 580, 410);
}
function sinaLogined(loginResult) {
	login.loginComplete(loginResult);
}
function sinaLoginFailed(message) {
	loader.use("humanmessage", function() {
		errorMessage(message);
	})
}
function checkComment(commentForm, commentMinLength, commentMaxLength) {
	var field = commentForm['content'];
	var length = field.value.trim().length;
	if (length == 0) {
		$('commentFormHint').set('html', "请输入评论内容");
		field.focus();
		return false;
	}
	if (length < commentMinLength) {
		$('commentFormHint').set('html', "评论应至少有" + commentMinLength + "个字");
		field.focus();
		return false;
	}
	if (length > commentMaxLength) {
		$('commentFormHint').set('html', "您的评论有点长哦，精简一下吧，请控制在" + commentMaxLength + "字以内");
		field.focus();
		return false;
	}
	$('commentFormHint').set('html', "");
	return true;
}
function setMainVideo(videoId, artistName, videoTitle, callback) {
	login.popupLogin(function() {
		var requestUrl = "/mv/set-main-video";
		var params = "videoId=" + videoId;
		new Request.JSON({
			url: requestUrl,
			method : 'post',
			data : params,
			onSuccess : function(result) {
				if (!result.error) {
					successMessage("OK啦，您已经把&nbsp;&nbsp;" + artistName + " - " + videoTitle + " 设为个人主页的主打歌!");
					if (callback) {
						callback();
					}
				} else {
					errorMessage("该曲目已经是您的个人主页主打歌了:)");
				}
			}
		}).send();
	}, null);
}
function addFavoriteVideo(videoId, artistName, videoTitle, callback) {
	login.popupLogin(function() {
		var requestUrl = "/mv/add-favorite";
		var params = "videoId=" + videoId;
		new Request.JSON({
			url: requestUrl,
			method : 'post',
			data : params,
			onSuccess : function(result) {
				if (!result.error) {
					var message = '';
					if (artistName && videoTitle) {
						message = 'OK啦，' + '您已经把&nbsp;&nbsp;' + artistName + " - " + videoTitle + '添加到收藏夹';
					} else {
						message = 'OK啦，已经添加到收藏夹';
					}
					successMessage(message);
					if (callback) {
						callback();
					}
				} else {
					errorMessage("忘了吧，你已经收藏过该曲目了:)");
				}
			}
		}).send();
	}, null);
}
function join_fanclub(artistId) {
	login.popupLogin(function() {
		var requestUrl = "/home/fanclub/join-fanclub";
		var params = "artistId=" + artistId;
		new Request.JSON({
			url: requestUrl,
			method : 'post',
			data : params,
			onSuccess : function(action) {
				if (!action.error) {
					successMessage("成功加入饭团" + action.artist_name);
				} else {
					errorMessage(action.message);
				}
			}
		}).send();
	}, null);
}

