//global vars
var message = "";
		
$(function(){
	$("#myFan > .container").scrollBar();
	$("#myFriend").scrollBar({dragger:".dragger",up:".topArrow",down:".botArrow",content:".data"});
	$("#mySpace").tabs({control:".tab li"});
	$("#joinSpace").tabs({control:".tab li"});
	$("#myMedia").tabs({control:".tab li"});
	$("#wall").tabs({control:".tab li",playTab:3});
	$("#favoriteMedia").tabs({control:".tab li"});
	$("#wall").wall();
	$("#myMedia .description").each(function(i){$(this).cut(30)});
	$("#mySpace .description").each(function(i){$(this).cut(80)});
	$("#joinSpace .description").each(function(i){$(this).cut(80)});
	$("#favoriteMedia .description").each(function(i){$(this).cut(80)});
	
	//$("#bodyer .tag").each(function(i){$(this).cutTag(3)});
	
	//bind event
	$("#btnChangePw").bind("click",changePassword);
	$("#removeFriend").click(removeMyFriend);
	//$("#myFriend .add").click(addFriend);
	$("#addFriend").click(addOwnerFriend);
	$("#inviteFriend").bind("click",inviteFriend);
	
	$("#profile .spaceItem").each(function(i){
		var wrap = $(this).find(".thumb");
		var obj = wrap.find("ul");
		wrap.slider({target:obj,direction:"x",step:100,speed:2000});
	});	
	
	$("#wall .item").each(function(){
		var showNum = 10;
		var curNum = showNum;
		var lis = $(this).find("li");
		var more = $(this).find(".moreNotis");
		for(var key in lis)
			if(key >= showNum) lis.eq(key).hide();
		more.click(function(e){
			var toNum = curNum+showNum;
			for(;curNum<toNum; curNum++) {
				if(curNum<lis.length)		
				lis.eq(curNum).show();
				else return false;
			}
			return false;
		});	
	
	});
});

function removeFriend(){
	var obj = $(this).parent().parent();
	var userId  = obj.attr("userId");
	var btn = {" Yes " : doRemoveFriend,
				" No " : function(){$("#dialog").remove(); return false}
			};
	$("body").dialog({btn: btn});
	function doRemoveFriend() {
		$("#dialog").remove(); 
		obj.remove();
		$.post(friend_remove,"userID="+userId);
		return false;
	}
}

function removeMyFriend() {
	var title = "Remove From My Friends",
		content = "Are you sure you want to remove \""+u_name+"\" from your friends?",
		btn = {" Yes " : doRemoveFriend,
				" No " : function(){$("#dialog").remove(); return false}
			};
	$("body").dialog({title:title,content:content,btn: btn});
	function doRemoveFriend() {
		$("#dialog").remove(); 
		$.post(friend_remove,"userID="+id,function(){
			$("body").dialog({title:"Removed From My Friends",content:u_name+" has been successfully removed from your friends",btn: {" OK ":function(){
				window.location = "/users/"+u_name;
			}}});
		});
		return false;
	}	
}

function addFriend() {
	var obj = $(this).parent().parent();
	var userId  = obj.attr("userId");
	var username = obj.find(".username").text();
	var title = "Add Friend:";
	var content = "Your friend request (<span class='red'>"+username+"</span>) have been sent!";
	var btn = {" OK " : function(){$("#dialog").remove(); return false}};
	$("body").dialog({title: title,content: content,btn: btn});
	window.setTimeout(function(){$("#dialog").remove();},2000);
	$.post(friend_add,"userID="+userId);
}

function addOwnerFriend() {
	var title = "Add Friend:";
	var content = "Your friend request has been sent!";
	var btn = {" OK " : function(){$("#dialog").remove(); return false}};
	$("body").dialog({title: title,content: content,btn: btn});
	window.setTimeout(function(){$("#dialog").remove();},2000);	
	$.post(friend_add,"userID="+id);
}

function getSelectedText(obj){
	var selectedText;
	if(window.getSelection) selectedText=getTextFieldSelection(obj);
	else selectedText=document.selection.createRange().text;
	return selectedText;
			
	function getTextFieldSelection(o){
		if(o.selectionStart != undefined && o.selectionEnd != undefined)
			return o.value.substring(o.selectionStart,o.selectionEnd);
		else return "";
	}
}

function changePassword() {
	var title = "Change Password";
	var content = "<span class=\"red\" id=\"passwordHint\" style=\"display:none\"></span><ul class=\"formSection lh3\">";
         content +=    "<li><div class=\"name\" style=\"width:150px\"><label for=\"oldPassword\">Old Password:</label></div><div class=\"enter\"><input type=\"password\" name=\"oldPassword\" id=\"oldPassword\" /></div></li>";
         content +=    "<li><div class=\"name\" style=\"width:150px\"><label for=\"newPassword\">New Password:</label></div><div class=\"enter\"><input type=\"password\" name=\"newPassword\" id=\"newPassword\" /></div></li>";
         content +=    "<li><div class=\"name\" style=\"width:150px\"><label for=\"confirmPassword\">Confirm New Password:</label></div><div class=\"enter\"><input type=\"password\" name=\"confirmPassword\" id=\"confirmPassword\" /></div></li>";
		 content += "</ul>";
	var btn = {" Save " : savePassword,
				" Cancel " : function(){$("#dialog").remove(); return false}
			};
	$("body").dialog({title: title,content: content,btn: btn});
	$("#dialog").find("input[type='password']").click(function(){$(this).val("");$("#passwordHint").hide();});
	
	function savePassword(){
		if($("#oldPassword").val() == "") {
			$("#passwordHint").text("The password can not be empty!");
			$("#passwordHint").show();
			return false;
		}
		if($("#newPassword").val() == "") {
			$("#passwordHint").text("The new password can not be empty!");
			$("#passwordHint").show();
			return false;
		}
		if($("#oldPassword").val() == $("#newPassword").val()) {
			$("#passwordHint").text("You didn't set a new password!");
			$("#passwordHint").show();		
			return false;
		}
		if($("#confirmPassword").val() != $("#newPassword").val()) {
			$("#passwordHint").text("the new password you entered did not match the confirmation that you've entered!");
			$("#passwordHint").show();
			return false;
		}
		var pars = "oldPassword="+$("#oldPassword").val()+"&newPassword="+$("#newPassword").val();
		$.post(password_change,pars,function(str){
			$("#dialog").remove(); 
			var title = "Change Password";
			var content = str;
			var btn = {" OK " : function(){$("#dialog").remove(); return false}};
			$("body").dialog({title: title,content: content,btn: btn});
		});
		return false;
	}
}

$.fn.wall = function(params){
	var container = $(this);
	var p = params || {};		
	var show = p.show || $(".wall ul",this);
	var area = p.area || $("#messageBox");
	var btn = p.btn || $("#btnSendMessage");
	var tools = p.tools || $(".tools",this);
	var get = p.get || wallMessage_get;
	var postMessage = p.post || wallMessage_post;
	var del = p.del || wallMessage_delete;
	var idType = p.type || "userID";
	var allNoti = $(".all ul");
	area.val("Leave a message here").css("color","#aaa");
	area.focus(function(){$(this).val("").css("color","#000"); area.unbind()});
		
	tools.find(".bold").click(function(){addUBB(area,"b");return false});
	tools.find(".italic").click(function(){addUBB(area,"i");return false});
	tools.find(".underline").click(function(){addUBB(area,"u");return false});
	
	btn.bind("click",sendMessage);

	
	function sendMessage() {
		var privacy = 0;
		message = area.val();
		if($("#privateMessage").length!=0 && $("#privateMessage")[0].checked) privacy = 2;
		var pars = idType+"="+id+"&message="+message+"&privacy="+privacy;
		$.ajax({
			type: "POST",
			url: postMessage,
			data: pars,
			success: function(xml){
				handleMessage(xml);
			}
	    });	
		return false;
	}
	
	function handleMessage(xml) {
		var obj = $(xml).find("user");
		var li;
		var owner = obj.attr("owner"); 
		var id = obj.attr("messageID"); 
		var username = obj.attr("username");
		var uId = obj.attr("userID");
		var photo = obj.attr("photo");
		var time = obj.attr("time");
		message = message.replace(/\[/g,"<").replace(/\]/g,">");

		if(owner == "true") li = "<li id=\""+ id +"\" class=\"wallItem\"><div class=\"operate\"><a href=\"#\" class=\"delete\">Delete</a> | <a href=\"#\" class=\"quote\">Quote</a></div><div class=\"photo\"><img src=\""+ photo +"\"/></div><div class=\"userInfo\"><span class=\"username bold\"><a href=\"/user/"+uId+"\">"+username+"</a></span><span class=\"time\"> ("+time+")</span></div><p class=\"pContent\">"+message+"</p></li>";	
		else li = "<li id=\""+ id +"\" class=\"wallItem\"><div class=\"operate\"><a href=\"#\" class=\"quote\">Quote</a></div><div class=\"photo\"><img src=\""+ photo +"\"/></div><div class=\"userInfo\"><span class=\"username bold\"><a href=\"/user/"+uId+"\">"+username+"</a></span><span class=\"time\"> ("+time+")</span></div><p class=\"pContent\">"+message+"</p></li>";	
		show.prepend(li);
		allNoti.prepend(li);
		addEvent();
		
	}
	
	function addEvent() {
		var btnDel = show.find(".delete");
		var btnQuote = show.find(".quote");
		btnDel.unbind().bind("click",function(){
			container.confirm({content:"Are sure remove the message!"},$(this),delMessage);
			return false;
		});
		btnQuote.unbind().bind("click",function(){
			var liObj = $(this).parents("li[id]");
			var username = liObj.find(".username").text();
			var message = liObj.find(".pContent").text();
			var str = "[q][i]The message send by [/i][b]"+username+"[/b]:[br]"+message+"[/q]";
			area.val("");
			area.val(str);
			return false;
		});
		var allbtnDel = allNoti.find(".delete");
		var allbtnQuote = allNoti.find(".quote");
		allbtnDel.unbind().bind("click",function(){
			container.confirm({content:"Are sure remove the message!"},$(this),delMessage);
			return false;
		});
		allbtnQuote.unbind().bind("click",function(){
			var liObj = $(this).parents("li[id]");
			var username = liObj.find(".username").text();
			var message = liObj.find(".pContent").text();
			var str = "[q][i]The message send by [/i][b]"+username+"[/b]:[br]"+message+"[/q]";
			area.val("");
			area.val(str);
			return false;
		});
		
	}
	
	function delMessage(where,obj) {
		var liObj = obj.parents("li[id]");
		var mId = liObj.attr("id");
		var pars = idType+"="+id+"&messageID="+mId;
		liObj.remove();
		container.scrollBar();
		var allLiObj = allNoti.find("li[id=\""+mId+"\"]");
		allLiObj.remove();
		var wallLiObj = show.find("li[id=\""+mId+"\"]");
		wallLiObj.remove();
		$.post(wallMessage_delete,pars);
		
	}
	
	function addUBB(obj,code) {
		var str = getSelectedText(area[0]);
		str = "["+code+"]"+str+"[/"+code+"]";
		var o = obj[0];
		var ubbLength = o.value.length;
		o.focus();
		if(typeof document.selection !="undefined")
		{
			document.selection.createRange().text = str; 
		}
		else
		{	
			o.value=o.value.substr(0,o.selectionStart)+str+o.value.substr(o.selectionEnd,ubbLength);
		}
	}
		
	function getSelectedText(obj){
		var selectedText;
		if(window.getSelection) selectedText=getTextFieldSelection(obj);
		else selectedText=document.selection.createRange().text;
		return selectedText;
				
			function getTextFieldSelection(o){
				if(o.selectionStart != undefined && o.selectionEnd != undefined)
					return o.value.substring(o.selectionStart,o.selectionEnd);
				else return "";
			}
	}
}
