$("#dofollow").live("click", function() {
	var w = trim($(this).text());
	var func = 'follow';
	var userid = $(this).parent().children("#userid").text();
	if (userid == "") {
		alert("請先登入或註冊");
		window.location.href = "login.php";
		return;
	}
	if (w == '編輯個人資料') {
		window.location.href = "editprofile.php";
		return;
	}
	if (w == '取消追蹤')
		func = 'defollow';
	var surl = 'commfunc.php';
	var friendid = $("#friendid").text();
	$.post(surl, {
		func : func,
		friendid : friendid
	}, function(response) {
		var rs = (func == 'follow') ? '取消追蹤' : '加入追蹤';
		alert(response);
		$("#dofollow").text(rs);
	});

})

$("#addtofavorite").live("click", function() {
	var func = 'addtofavorite';
	var surl = 'commfunc.php';
	var t = $(this).text();
	var anchor = $(this);
	if (t == '取消最愛')
		func = 'removefavorite';
	var uid = $(this).parent().children("#uid").text();
	var userid = $(this).parent().children("#userid").text();
	if (userid == "") {
		alert("請先登入或註冊");
		window.location.href = "login.php";
		return;
	}
	$.post(surl, {
		func : func,
		userid : userid,
		uid : uid
	}, function(response) {
		alert(response);
		// if (response == "OK")
		if (func == 'removefavorite')
			window.location.reload();
		else {
			// alert(anchor.text());
			anchor.text('取消最愛');
		}
	});

})

$(".checkav").live("click", function() {
	var u1 = trim($("#userid").val()).toLowerCase();
	if (u1.length < 4 || u1.length > 16 || u1.match(/\W/)) {
		alert("帳號格式有錯，請重新輸入");
		document.form1.userid.value = "";
		document.form1.userid.focus();
	} else {
		var url = "commfunc.php";
		$.post(url, {
			func : "checkav",
			userid : u1
		}, function(msg) {
			if (!msg.match(/OK/)) {
				alert("這個帳號已經有人使用了，請重新選擇。");
				document.form1.userid.value = "";
				document.form1.userid.focus();
			} else {
				alert("這個帳號可以使用。");
			}
		});

	}
})

$(".doregister")
		.live(
				"click",
				function() {
					var u1 = trim($("#userid").val()).toLowerCase();
					var p1 = trim($("#pass1").val());
					var p2 = trim($("#pass2").val());
					var intro = $("#intro").text();
					var medianame = $("#medianame").val();
					var subtype = $("#subtype").val();
					var agree = $("#agreeeula").is(':checked');
					if (!agree) {
						alert("請閱讀並勾選同意 tome 服務使用條款");
						$("#agreeeula").focus();
						return;
					}
					// alert(medianame+intro);
					if (p1 != p2) {
						alert("您輸入的密碼不相符，請重新輸入");
						document.form1.pass1.value = "";
						document.form1.pass2.value = "";
						document.form1.pass1.focus();
					} else if (u1.match(/\W/) || u1.length < 4
							|| u1.length > 16) {
						alert("您可能使用了不合法的特殊字元，或者長度不相符，請重新輸入");
						document.form1.userid.value = "";
						document.form1.userid.focus();
					} else if (p1.match(/\W/) || p1.length < 4
							|| p1.length > 16 || p2.length < 4
							|| p2.length > 16) {
						alert("您可能使用了不合法的特殊字元，或者長度不相符，請重新輸入");
						document.form1.pass1.value = "";
						document.form1.pass2.value = "";
						document.form1.pass1.focus();
					} else {
						var url = "commfunc.php";
						$
								.post(
										url,
										{
											userid : u1,
											userpass : p1,
											func : "doregister",
											intro : intro
										},
										function(msg) {
											if (!msg.match(/OK/)) {
												alert("註冊失敗，請重新再試一次！");
												document.form1.reset();
												document.form1.userid.focus();
											} else {
												if (confirm("註冊成功，請按確定登入。")) {
													var url = "commfunc.php";
													$
															.post(
																	url,
																	{
																		func : "login",
																		userid : u1,
																		userpass : p1
																	},
																	function(
																			msg) {
																		if (msg != "OK") {
																			alert("登入失敗，請重新再試一次！");
																			window.location.href = "login.php";
																		} else {
																			var sid = $
																					.cookie('PHPSESSID');
																			window.location.href = "myapp://loginok/"
																					+ u1
																					+ "/"
																					+ sid;
																			sleep(500);
																			window.location.href = "sitelist.php?type=mine";
																		}
																	})

												}

											}
										});
					}
				})

// 去除字串左邊的空白虛格
function ltrim(instr) {
	return instr.replace(/^[\s]*/gi, "");
}

// 去除字串右邊的空白虛格
function rtrim(instr) {
	return instr.replace(/[\s]*$/gi, "");
}

// 去除字串前後的空白虛格
function trim(instr) {
	instr = ltrim(instr);
	instr = rtrim(instr);
	return instr;
}

function sleep(milliseconds) {
	var start = new Date().getTime();
	for ( var i = 0; i < 1e7; i++) {
		if ((new Date().getTime() - start) > milliseconds) {
			break;
		}
	}
}

function dologout() {
	if (confirm("您確定要登出嗎？")) {
		var url = "commfunc.php";
		$.post(url, {
			func : "logout"
		}, function(msg) {
			var sid = $.cookie('PHPSESSID');
			window.location.href = "myapp://logoutok/" + sid;
			sleep(500);
			window.location.href = "sitelist.php?type=all";
		})
	}
	return (false);
}

$("#del_but").live(
		'click',
		function() {
			if (confirm("您確定要刪除這個網頁嗎？")) {
				var url = "commfunc.php";
				var uid = $(this).parent().parent().children().children("#uid")
						.text();
				var userid = $(this).parent().parent().children().children(
						"#userid").text();
				var admin = $(this).parent().parent().children().children(
						"#admin").text();
				$.post(url, {
					func : "deleteurl",
					userid : userid,
					uid : uid,
					admin : admin
				}, function(msg) {
					alert(msg);
					window.location.reload();
				})
			}

		})

$("#addcomm").live("click", function() {
	var surl = "commfunc.php";
	var func = "addcomm";
	var uid = $(this).parent().children("#uid").text();
	var userid = $(this).parent().children("#userid").text();
	var nickname = $(this).parent().children("#nickname").val();
	var msg = $(this).parent().children("#msg").val();
	
	var captcha = $(this).parent().children("#captcha-form").val();
	if (trim(nickname) == "") {
		alert("請輸入稱呼");
		$(this).parent().children("#nickname").focus();
		return;
	}

	$.post(surl, {
		func : func,
		userid : nickname,
		uid : uid,
		msg : msg,
		captcha : captcha
	}, function(response) {
		
		if (response == "回應已送出") 
			alert(response);
		else 
			alert("無法送出回應，請再試一次。");
			window.location.reload();
		
			
			
	});

})

$("#showhide").live("click", function() {
	// var userid =
	// $(this).parent().children("#commbox").children("#userid").text();
	var h = $("#commbox").css("display");
	if (h == "none") {
		// if (userid == "") {
		// alert("請先登入");
		// window.location = "login.php";
		// return;
		// }

		$("#commbox").css("display", "block");
		$(this).css("display", "none");
		$("#commbox").children("#nickname").focus();
	} else {
		$("#commbox").css("display", "none");

	}
})

$("#showhide1").live("click", function() {

	$("#commbox").css("display", "none");
	$("#showhide").css("display", "block");

})

$(".dologin").live("click", function() {
	var userid = trim(document.form1.userid.value);
	var userpass = trim(document.form1.userpass.value);
	var url = "commfunc.php";
	$.post(url, {
		func : "login",
		userid : userid,
		userpass : userpass
	}, function(msg) {
		if (msg != "OK") {
			alert("登入失敗，請重新再試一次！");
			document.form1.userid.value = "";
			document.form1.userpass.value = "";
			document.form1.userid.focus();
		} else {
			var sid = $.cookie('PHPSESSID');
			window.location.href = "myapp://loginok/" + userid + "/" + sid;
			sleep(500);
			window.location.href = "sitelist.php?type=mine";
		}
	})
})

$(".dologin2").live("click", function() {
	var userid = trim(document.form1.userid.value);
	var userpass = trim(document.form1.userpass.value);
	var url = "commfunc.php";
	$.post(url, {
		func : "login",
		userid : userid,
		userpass : userpass
	}, function(msg) {
		if (msg != "OK") {
			alert("登入失敗，請重新再試一次！");
			document.form1.userid.value = "";
			document.form1.userpass.value = "";
			document.form1.userid.focus();
		} else {
			var surl = trim(document.form1.surl.value);
			var stitle = trim(document.form1.stitle.value);
			$.post(url, {
				func : "addindex",
				url : surl,
				title : stitle
			}, function(msg) {
				alert(msg);
				window.close();
			});

		}
	})
})

function submitenter(myfield, e, who) {
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;

	if (keycode == 13) {
		// myfield.form.submit();
		$(who).click();
		return false;
	} else
		return true;
}
/**
 * Cookie plugin
 * 
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de) Dual licensed under the MIT and
 * GPL licenses: http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 * 
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain:
 *          'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to
 *       use the same path and domain used when the cookie was set.
 * 
 * @param String
 *            name The name of the cookie.
 * @param String
 *            value The value of the cookie.
 * @param Object
 *            options An object literal containing key/value pairs to provide
 *            optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date
 *         from now on in days or a Date object. If a negative value is
 *         specified (e.g. a date in the past), the cookie will be deleted. If
 *         set to null or omitted, the cookie will be a session cookie and will
 *         not be retained when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default:
 *         path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie
 *         (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be
 *         set and the cookie transmission will require a secure protocol (like
 *         HTTPS).
 * @type undefined
 * 
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 * 
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 * 
 * @param String
 *            name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 * 
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires
				&& (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime()
						+ (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires
			// attribute,
			// max-age is not
			// supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [ name, '=', encodeURIComponent(value), expires,
				path, domain, secure ].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for ( var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie
							.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};


