// Global Init
$(function(){
		   
	// input focus
	$("input[type='text'],input[type='password']").each(function(i){
    	$(this).bind("focus",function(){$(this).addClass("focus");});
		$(this).bind("blur",function(){$(this).removeClass("focus")});
	});
	
	//share
	$(".share .simpleBtn").each(function(i){
		var type = $(this).attr("type");
			
		if(type) {
			$(this).click(function(){
			var eType = $(this).attr("eType") || "0";
				id = $(this).attr("eId") || "0";								   
				if(type == "facebook") {
					fb_refresh_url="/facebook/share/"+eType+"/"+id;
					if(fb_login=="0"){
						FB.Connect.requireSession();
					}else{
						window.location = fb_refresh_url;
					}
				} else if(type == "tweet") {
					$.ajax({
						type: "POST",
						url: tweet_get,
						data: "type=" + eType + "&id=" + id,
						dataType: "json",
						success: function(data){
							var logined = data.logined;
							var message = data.message;
							if(logined=="false"){
								window.location =message ;			
							}else{
								var title = "Share message";
								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=\"tmessage\">Message:</label></div><div class=\"enter\"><textarea name=\"tmessage\" rows=\"8\" onkeydown=\"var e = event || e; if((e.keyCode > 46 || e.keyCode == 32)&& this.value.length>140) {return false}\">"+message+"</textarea><div id=\"twHint\">Please limit your tweet to 140 characters.</div></div></li>";
									 content += "</ul>";
								var btn = {" Share " : function(){
											var	message = $("#dialog textarea").val();
											if(message.length>140){
												return false;
											}
											message = encodeURIComponent(message);
											var	pars = "type=" + eType + "&id=" + id + "&message="+ message;
												$.ajax({
													type: "POST",
													url: tweet_send,
													data: pars,
													dataType: "json",
													success: function(data){
														$("#dialog").remove(); 
														$("body").dialog({title: data.title,content: data.content});	
													}
												});
												return false;
											},
											" Cancel " : function(){$("#dialog").remove(); return false}
										};
								$("body").dialog({title: title,content: content,btn: btn});	
							}
						}
					});
					
				} else if(type == "rsvp") {
					$.ajax({
						type: "POST",
						url: event_rsvp,
						data: "event_id=" + id,
						dataType: "json",
						success: function(data){
							$("body").dialog({title: data.title,content: data.content});
						}
					});
					
				}
				return false;
			});	
		}
	});
	
	//invite hint box
	$("<div id=\"inviteHint\"><div class=\"topArrow\"></div><div class=\"content\"><div class=\"info m10 pd20\"></div></div><div class=\"shadow\"></div><div class=\"close\"></div></div>").appendTo("body");
	var inviteHintTimer = window.setInterval(showInvite,10000);
	function showInvite() {
		var wrap = $("#inviteHint"),
			btn = wrap.find(".close"),
			infoBox = wrap.find(".info");
		$.post(getinstantinvite,function(xml){
			var result = $(xml).find("invite");
			if(result.length > 0) {
				var invite = result.eq(0); 
				window.clearInterval(inviteHintTimer);
				infoBox.html("<a target=\"_blank\" class=\"black bold unline\" href=\"/user/" + invite.attr("uId")+ "\"> " + invite.attr("username") + " </a> invited you to come to <a target=\"_blank\"  class=\"room black bold unline\" href=\"/snazl/" + invite.attr("roomID") + "\"> " + invite.attr("roomname") + " </a>!");
				wrap.show();
				wrap.animate({ bottom: "20px"});
				infoBox.find(".room").click(function(){handle(wrap,invite.attr("inviteID"))});
				btn.click(function(){handle(wrap,invite.attr("inviteID"))});
				//window.setInterval(function(){handle(wrap,invite.attr("inviteID"))},10000)
			}
		});	
		var handle = function(wrap,id) {
			$.post(handleinstantinvite,"inviteID="+id);
			wrap.css({ bottom: "-20px"});
			wrap.hide();
			window.setTimeout(function(){showInvite()},1000);
			inviteHintTimer = window.setInterval(showInvite,10000);
		}
		
	}
	
	
	
	// close space
	(function(){
		var obj = $("#spaceTab li[spaceID]");
		var ids = [];
		obj.each(function(i){
			ids.push($(this).attr("spaceID"));	
			var spaceTitle = $(this).find(".title a");
			var strSpaceTitle = spaceTitle.text();
			if(strSpaceTitle.length > 16) strSpaceTitle = strSpaceTitle.substr(0,13) + "...";
			spaceTitle.text(strSpaceTitle);
		});
		
		obj.find(".close").click(function(e){
			var fuc;
			var liObj = $(this).parent();
			var id = liObj.attr("spaceID");
			var p;
			fuc = function(){
				$.ajax({
					type: "POST",
					url: space_leave,
					data: "roomID="+id,
					success: function(str){
						if(str != "true") fuc();
						if(obj.length == 1) {
							window.location = "/user";
							return false;
						}
						if(liObj.hasClass("current")) {
							for(var t=0; t<ids.length; t++) {
								if(id == ids[t]) {
									if(t == ids.length-1) p = ids[0];
									else p = ids[t+1];
									break;
								}
							}
							window.location = "/snazl/"+p;
							return false;			
						}
						else {
							liObj.remove();
							return false;
						}		
					},
					error: function(){
						window.setTimeout(fuc,1000);	
					}
				});
				return false;
			}
			fuc();
			e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;				
			return false;
		});
	})();
	// last chat
	getCurSpace();
	
	function getCurSpace() {
		var obj = $("#spaceTab li[spaceID]");
		for(var i = 0; i < obj.length; i++) {
			if(i == 0) window.setTimeout(function(){getLastChat(obj.eq(0))},1000*0);
			if(i == 1) window.setTimeout(function(){getLastChat(obj.eq(1))},1000*1);
			if(i == 2) window.setTimeout(function(){getLastChat(obj.eq(2))},1000*2);
			if(i == 3) window.setTimeout(function(){getLastChat(obj.eq(3))},1000*3);
		}
	}
	
	var status = "disabled",
		changeTitlerTimer,
		documentTitle = document.title;
	$(window).focus(activePage);
	$(window).blur(function(){status = "disabled"});
	$("html").mousemove(activePage);
	
	function activePage() {
		window.clearInterval(changeTitlerTimer); 
		document.title = documentTitle; 
		status = "active";
	}
	
	function getLastChat(obj) {
		var id = obj.attr("spaceID");
		var messageBox = obj.find("#spaceLastChat");
		$.ajax({
		type: "POST",
		url: chat_getLast,
		data: "roomID="+id,
		success: function(message){
			if(message == "0") return;
			var data = message.split("$&%^#*$&@");
			var name = data[0];
			var message = data[1];
			if(status != "active") {
				window.clearInterval(changeTitlerTimer); 
				changeTitlerTimer = window.setInterval(function(){document.title = document.title == message ? documentTitle : message},1000);
			}
			if(message.length > 46) message = message.substr(0,46)+"...";
			messageBox.find(".bold").text(name+": ");
			messageBox.find(".content").text(message);
			messageBox.fadeIn(1000);
			window.setTimeout(function(){messageBox.fadeOut(1000)},2000);
		}
		});
		
		window.setTimeout(function(){getLastChat(obj)},4000);
	}

	

	

	
	$("#search").find("input[name='keyword']").focus(function(){
		$(this).val("");															  
	});
		
	$("#search form").bind("submit",function(){search(); return false});
	
	function search(){
		var keyword = $("#search").find("input[name='keyword']").val();
		if(keyword == "Search in snazl..." || keyword == "") return;
		var type = $("#search").find(".selected").text().toUpperCase().trim();
		var url;
		switch(type) {
		case "PEOPLE": 
			url = "/search/user/"+keyword; 
			break; 	
		case "MEDIA": 
			url = "/search/media/"+keyword; 
			break; 	
		default: 
			url = "/search/snazls/"+keyword; 
			break; 	
		}
		window.location.href = url;
	}
	
});

//Public 
Array.prototype.remove=function(dx)
	{
	if(isNaN(dx)||dx>this.length){return false;}
	for(var i=0,n=0;i<this.length;i++)
	{
		if(this[i]!=this[dx])
		{
			this[n++]=this[i]
		}
	}
	this.length-=1
}

String.prototype.trim= function() 
{ 
    return this.replace(/(^\s*)|(\s*$)/g, ""); 
}

Array.prototype.distinct = function()  
{  
	var   a   =   {};   
	for(var   i=0;   i<this.length;   i++)  
	{  
	  if(typeof   a[this[i]]   ==   "undefined")  
		  a[this[i]]   =   1;  
	}  
	this.length   =   0;  
	for(var   i   in   a)  
	  this[this.length]   =   i;  
	return   this;   
}

function loginHint() {
	var title = "Log in or sign up!";
	var content = "Please log in or sign up to participate in this SnazL!";
	var btn = {"Log In":function(){$("#dialog").remove();window.location.href="/signup/4";return false},"Return":function(){$("#dialog").remove();return false}};
	$("body").dialog({title:title,content:content,btn:btn});
}

function addToFavorite(id) {
	alert("id"+id);	
}

function rateForMedia(id,rate) {
	alert("id:"+id+" rate:"+rate);	
}

function inviteFriend(email) {
	var emailAddress = "";
	var pass = false;
	if(email.constructor == String){ pass = true; emailAddress = email;}
	var title = "Invite Friends";
	var content = "<div style='padding:0 30px; line-height:50px'><span class='bold mr10'>Email:</span> <input type='text' name='email' value='"+ emailAddress +"' /><span class='hint ml10 red'></span></div>"
	var btn = {
		"Search": searchFriend,
		"Cancel" : function(){$("#dialog").remove(); return false} 
	};
	if(!pass) $("body").dialog({title: title,content: content,btn: btn});
	else searchFriend(email);
	
	function searchFriend(email) {
		var email = pass?email:$("#dialog input[name='email']")[0].value;
		if(!testEmail(email)) {
			$("#dialog .hint").html("Please enter correct email!");
			return;
		}
		$.ajax({
			type: "POST",
			url: friend_finder,
			data: "email="+email,
			success: function(message){
				var result = message.split(",");
				if(result[0] == "true") {
					var userId = result[1];
					var email = result[2];
					content = "<div class='user m20' userId='"+userId+"'><span class='darkYellow'>"+email+"</span> is already a SnazL member</div>";	
					btn = {
						"Add Friend": function() {
							var userId = $("#dialog .user").attr("userId");
							$.post(friend_add,"userID="+userId);
							$("#dialog").remove();
								content = "<div class='m20'>Your invite has been sent.</div>";
								btn = {"Close":function(){$("#dialog").remove()}}
								$("body").dialog({title: title,content: content,btn: btn});
								var closeTimer = window.setTimeout(function(){$("#dialog").remove()},1000);
							},
						"Cancel": function(){$("#dialog").remove()}
					};
				} else {
					var email = result[1];
					content = "<div class='m10 red'>The user you are searching for is not a SnazL member yet. Invite them:</div><dl style='margin-left:100px'><dt class='clear'><div class='left w70'>Email</div><div class='left'><input class='w200' type='text' name='email' value='"+email+"' /></div></dt><dd class='clear'><div class='left w70'>Message:</div><div class='left w200'><textarea name='message' class='w200' /></div></dd></dl>";
					btn = {
						"Send Invite": function(){
							var message =  $("#dialog textarea[name='message']")[0].value;
							var data = "email="+email+"&message="+message;
							$.post(friend_invite,data);
							$("#dialog").remove();
							},
						"Cancel": function(){$("#dialog").remove()}
						};
				}
				$("#dialog").remove();
				$("body").dialog({title: title,content: content,btn: btn});
			}
		})

	}
}

function inviteToSpace() {
	var title = "Invite Friends";
	var content = "<div style='padding:0 30px; line-height:50px'><div class='hint red'></div><span class='bold mr10'>Search:</span> <input type='text' name='content' /><label><input type='radio' name='type' value='email' checked = 'checked' />Email</label> <label><input type='radio' name='type' value='username' />Username</label></div>"
	var btn = {
		"Search": searchFriend,
		"Cancel" : function(){$("#dialog").remove(); return false} 
	};
	$("body").dialog({title: title,content: content,btn: btn});
	
	function searchFriend() {
		var type = $("#dialog input[checked]")[0].value;
		var val = $("#dialog input[name='content']")[0].value;
		if(type == "email")
		if(!testEmail(val)) {
			$("#dialog .hint").html("Please enter correct email!");
			return;
		}
		if(val == "") {
			$("#dialog .hint").html("The username cann't be empty!");
			return;		
		}
	
		$.ajax({
			type: "POST",
			url: friend_finderSpace,
			data: "type="+type+"&value="+val,
			success: function(message){
				var result = message.split(",");
				if(result[0] == "true") {
					var userId = result[1];
					var email = result[2];
					var username = result[3];
					var fname = result[4];
					var lname = result[5];
					var friend = result[6];
					content = "<div class='user m20' userId='"+userId+"'><span class='darkYellow'>"+username+"</span> is already a SnazL member</div>";	
					btn = {
						"Invite Them Here":function(){
							$.post(space_invite,"userID="+userId+"&roomID="+roomID);
							content = "<div class='m20'>Your invite has been sent.</div>";
							btn = {"Close":function(){$("#dialog").remove()}}
							$("body").dialog({title: title,content: content,btn: btn});
							},
						"Add Friend": function() {
							$.post(friend_add,"userID="+userId);
							content = "<div class='m20'>Your invite has been sent.</div>";
							btn = {"Close":function(){$("#dialog").remove()}}
							$("body").dialog({title: title,content: content,btn: btn});
							},
						"Cancel": function(){$("#dialog").remove()}
					};
				} else {
					var email = result[2];
					title = "invite";
					content = "<div class='m10 red'>The person you're looking for has not registered with SnazL yet! Invite them here!</div><dl style='margin-left:100px'><dt class='clear'><div class='left w70'>Email</div><div class='left'><input class='w200' type='text' name='email' value='"+email+"' /></div></dt><dd class='clear'><div class='left w70'>Message:</div><div class='left w200'><textarea name='message' class='w200' /></div></dd></dl>";
					btn = {
						"Send Invite": function(){
							var message =  $("#dialog textarea[name='message']")[0].value;
							var data = "email="+email+"&message="+message+"&roomID="+roomID;
							$.post(space_inviteFriend,data);
							$("#dialog").remove();
							},
						"Cancel": function(){$("#dialog").remove()}
						};
				}
				$("#dialog").remove();
				$("body").dialog({title: title,content: content,btn: btn});
			}
		})

	}
}

function testEmail(str) {
	var emailPattern = /^[a-zA-Z0-9_][\w\-\.]+@[\w\-]+(\.[a-z]+){1,2}$/;
	return emailPattern.test(str);
}

function testUrl(str) {
	var urlPattern = /[a-zA-z]+:\/\/[^\s]*.mp3/;
	return urlPattern.test(str);
}

//top space roller
$(function(){
	// inviteFriend();	
});

// the space scroll
$.fn.roll = function(params){
	var p = params;
	var btnLeft = $("#"+ p.left);
	var btnRight = $("#"+ p.right);
	var targetFrame = $("#"+ p.target);
	var child = p.child;
	var auto = p.auto;
	var itv,ion,ioff;
	
	var turnLeft = function(){
		btnLeft.unbind("click",turnLeft);
		if(auto) autoStop();
		targetFrame.animate( {marginLeft:-128}, 'slow', '', function(){
			targetFrame.find(child+":first").appendTo( targetFrame );
			targetFrame.css("marginLeft",0);
			btnLeft.bind("click",turnLeft);
			if(auto) autoPlay();
		});
		return false;
	};
	
	var turnRight = function(){
		btnRight.unbind("click",turnRight);
		if(auto) autoStop();
		targetFrame.find(child+":last").clone().show().prependTo( targetFrame );
		targetFrame.css("marginLeft",-128);
		targetFrame.animate( {marginLeft:0}, 'slow' ,'', function(){
			targetFrame.find(child+":last").remove();
			btnRight.bind("click",turnRight);
			if(auto) autoPlay();
		});
		return false;
	};
	
	var cc = function() {
		if(($(this+":last").is("div"))) $(this).find("div").remove();
		else {
		$('<div>'+ title + '</div>').appendTo($(this));
		var title = $(this).attr("title");
		}
	};
	
	if(auto) {
		targetFrame.bind("mouseenter",function(e){autoStop(); e.stopPropagation()});
		targetFrame.bind("mouseleave",function(e){autoPlay(); e.stopPropagation()});
	}
	
	targetFrame.find(child).each(function(i){
	$('<div>'+ $(this).attr("title") + '</div>').appendTo($(this)).hide();	
	});

	targetFrame.find(child).mouseover(
		function() {
		var self = $(this);
		ion = window.setTimeout(function () {
			self.find("div").show();
			targetFrame.find(child).not(self).fadeTo(100, 0.5);
    	},250);
		}
	);
	
	targetFrame.find(child).mouseout(
		function() {		
		var self = $(this);
		ioff = window.setTimeout(function () {
		   targetFrame.find(child).fadeTo(100, 1);
		   self.find("div").hide();
		},250)
		window.clearTimeout(ion);
		}
	);
	
	btnRight.click( turnRight ).click(function(){return false;});
	btnLeft.click( turnLeft ).click(function(){return false;});
	
	function autoPlay(){ itv = window.setInterval(turnLeft, 3000)};
	function autoStop(){ window.clearInterval(itv)};
	
	if(auto) autoPlay();
}

// Tabs
$.fn.tabs = function (params) {
	var p = params || {};
	var control = p.control || "li";
	var target = p.target || ".item";
	var playTab = p.playTab || 1;
	var fxFade = p.fxFade || false;
	var fuc = p.fuc || false;
	var fucBool = true;
		
	var ctrlObjs = $(control,this);
	var targetObjs = $(target,this);
	var cur = 0;
	
	fxFade = "no";
	
	//if(fuc) ctrlObjs.click(function(){alert("fun");});
	
	ctrlObjs.each(function(i){
		if (i == playTab-1) {
			targetObjs.eq(i).show();
			if (!$(this).hasClass("current"))	$(this).addClass("current");
		} else { 
			targetObjs.eq(i).hide();
			if ($(this).hasClass("current")) $(this).removeClass("current");
		}
	});
	
	ctrlObjs.each(function(i){
    	$(this).bind("click",function(){
			if(fuc && cur == 0) { if(!fuc()) return false; }
			if ($(this).hasClass("current")) return false;
			$(this).addClass("current");
			targetObjs.each(function(j){
				if(i!=j) {
					ctrlObjs.eq(j).removeClass("current");
					targetObjs.eq(j).hide();
				}
				if(fxFade!="no") targetObjs.eq(i).fadeIn(400);
				else targetObjs.eq(i).show();
				cur = i;
			});
			return false;
		});
	});
	this.change = function(n) {
		
	}
	return this;
}

// the scroll bar of box
$.fn.scrollBar = function(params) {
	if($(this).length > 0) {
		var p = params || {};	
		var dragger = $(p.dragger || ".dragger",this);
		var up = $(p.up || ".topArrow",this);
		var down = $(p.down || ".botArrow",this);
		var content = $(p.content || ".data",this);
		
		var d = 3;
		var arrowHeight = 16;
		var startY,upTimer,downTimer;
	
		dragger.css("top",0+"px");
		content.css("top",0+"px");
		
		var targetHeight = content.height();
		var railHeight = this.height()-arrowHeight*2;
		var scale = targetHeight / railHeight;
		if( targetHeight/this.height() <= 1 ) {
			dragger.hide();
			up.unbind("mousedown");
			down.unbind("mousedown");
			return;
		}else {
			if(dragger.css("display")=="none") dragger.show();
			dragger.height(this.height() / scale);
		}
		dragger.bind("mousedown",function(e){
			var e = window.event?window.event:e;
	
		
			
			var start = e.clientY - this.offsetTop;
			$(document).mousemove(
			function(e) {
				
				var e = window.event?window.event:e;
				var top = e.clientY-start;
				if( top<0) {
					top = 0;
				}
				if(top>railHeight-dragger.height()) {
					top = railHeight-dragger.height();
				}			
				dragger.css("top",top+"px");
				content.css("top",-scale*top+"px");
				window.getSelection?window.getSelection().removeAllRanges():document.selection.empty();
			});	
	
			$(this).mouseout(
				function(){
					$(document).mouseup(
						function() {
							$(document).unbind("mousemove");
					}
					)
				}
			)
		});
		up.unbind();
		down.unbind();
		up.bind("mousedown",function(){
			up.css("cursor","pointer");
			upTimer = window.setInterval(function(){move('up')},30)
		});
		down.bind("mousedown",function(){
			down.css("cursor","pointer");
			downTimer = window.setInterval(function(){move('down')},30)
		});
		up.bind("mouseup",function(){
			up.css("cursor","default");
			clearInterval(upTimer);
		});
		down.bind("mouseup",function(){
			down.css("cursor","default");
			clearInterval(downTimer)
		});
		
		
		var mouse_wheel = function(e){
			 var evt = window.event || e;
			 if(evt.detail > 0 || evt.wheelDelta < 0) {
				move('down');
				if($.browser.mozilla) {e.stopPropagation && (e.preventDefault(), e.stopPropagation()) || (e.cancelBubble = true, e.returnValue = false);}
				return false;
			 } else {
				move('up');
				if($.browser.mozilla) {e.stopPropagation && (e.preventDefault(), e.stopPropagation()) || (e.cancelBubble = true, e.returnValue = false);}
				return false;
			 }
		}
		var mouse_wheel_opera = function(e){
			 var obj = e.srcElement;
			 if(obj == $(this)[0]){
			  mouse_wheel(e);
			 }
		}
		if ($.browser.msie || $.browser.safari) $(this)[0].onmousewheel = mouse_wheel;
		if($.browser.mozilla) $(this)[0].addEventListener("DOMMouseScroll", mouse_wheel, false);
		if($.browser.opera) document.onmousewheel = mouse_wheel_opera;
	
	
	
		
		function move(turn) {
			var currentTop = dragger.css("top");
			currentTop = currentTop.substring(0,currentTop.length-2);
			var dis;
			if(turn == "up") {
				if(currentTop<=0) {clearInterval(upTimer);return;}
				dis = parseInt(currentTop)-d;
			}else if(turn == "down") {
				if(currentTop>=railHeight-dragger.height()) {clearInterval(downTimer);return;}
				dis = d + parseInt(currentTop);
			}
			dragger.css("top",dis+"px");
			content.css("top",-scale*dis+"px");	
		}
	
		
		
	}
}

// dialog of alert & confirm and so on
$.fn.dialog = function(params) {
	var p = params || {};	
	var btn =  p.btn || {" Yes ":function(){$("#dialog").remove();return false;}};
	var title =  p.title || "SnazL.com Dialog Box:";
	var style =  p.width || "dialog";
	var content =  p.content || "Are you sure?";
	var fuc = p.fuc || false;
	
	var self = this;
	var createBtn = function (value , fuc){
		var button = document.createElement("input");
		$(button).attr("type","button");
		$(button).attr("value",value);
		$(button).bind("click",fuc);
		return $(button);
	};
	
	var create = function () {
		var header = "<li class='header'><div class='title'>" + title + "</div><a href='#' class='close'></a></li>";
		var data = "<li class='data'>"+ content +"</li>";
		var footer = document.createElement("li");
		$(footer).addClass("footer");
		for(var key in btn) createBtn(key,btn[key]).appendTo(footer);
		var ul = document.createElement("ul"); 
		$(ul).addClass("content");
		$(ul).html(header+data);
		$(ul).append(footer);
		var boxBg = document.createElement("div");
		$(boxBg).addClass("bg");
		var boxDiv = document.createElement("div");
		$(boxDiv).attr("id","dialog");
		$(boxDiv).append(ul);
		$(boxDiv).append(boxBg);
		return boxDiv;
		}
	self.append(create());
	var winW = document.documentElement.clientWidth || window.innerWidth;
	var winH = document.documentElement.clientHeight || window.innerHeight;
	var mH = getPageScroll();
	$("#dialog .content").css("left",(winW-$("#dialog .content").width())/2);
	$("#dialog .content").css("top",mH+300);
	
	function getPageScroll(){
	  var yScroll;
	  if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	  } else if (document.documentElement && document.documentElement.scrollTop){   // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	  } else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	  }
	
	  return yScroll;
	} 
	
	
	var boxSwitch = function (p) {
		if(p == "open") $("#dialog").show();
		else {
			$("#dialog").remove();
			return false;
		}
	}
	$("#dialog .close").bind("click",boxSwitch);
	$("#dialog .bg").bind("mousedown",function(){$(this).css("cursor","not-allowed")});
	$("#dialog .bg").bind("mouseup",function(){$(this).css("cursor","default")});
	$("#dialog .header")[0].onselectstart = function() {return false;}
	$("#dialog .header").bind("mousedown",function(e){
		var e = window.event?window.event:e;
		this.startX = e.clientX - this.parentNode.offsetLeft;
		this.startY = e.clientY - this.parentNode.offsetTop;
		$("#dialog .header").mousemove(
		function(e) {
			var e = window.event?window.event:e;
			var left = e.clientX-this.startX;
			var top = e.clientY-this.startY;
			$("#dialog .content").css("left",left+"px");
			$("#dialog .content").css("top",top+"px");
		});	

		$(this).mouseup(
		function() {
			$("#dialog .header").unbind("mousemove");
		});
	});
}

// simulate confirm
$.fn.confirm = function(info,obj,fuc) {
	var self = this;
	var title = info.title || "SnazL.com Confirm Box:";
	var content = info.content || "Are you sure?"
	var btn = info.bt || {" Yes! ": function(){$("#dialog").remove(); fuc(self,obj)}," No " : function(){$("#dialog").remove(); return false} };
	$("body").dialog({title: title,content: content,btn: btn});
}


// form submit
$.fn.getForm = function() {
	var result = "";
	$("input[type='text'],input[type='hidden'],input[type='radio'][checked],input[type='password'],select,textarea",this[0]).each(function(i){
		result += $(this).attr("name") + "=" + escape($(this).val()) + "&";
    });
	result = result.substr(0,result.length-1);
	return result;
}

//clear form
$.fn.clearForm = function() {
	$("input[type='text'],input[type='password'],input[type='file'],textarea",this[0]).each(function(i){
		$(this).val("");																		  																			  
	});
}

// message board
$.fn.wall = function(params){
	var container = $(".container",this);
	var p = params || {};		
	var show = p.show || $(".messageList",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";
	
	area.val("Leave a comment 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 loadMessage(){
		var pars = idType+"="+id;
		$.ajax({
			type: "POST",
			url: get,
			data: pars,
			success: function(xml){
				show.empty();
				var obj = $(xml).find("message");
				obj.each(function(i){
					var li;
					var owner = $(this).attr("owner"); 
					var id = $(this).attr("messageID"); 
					var username = $(this).attr("username");
					var uId = $(this).attr("userID");
					var photo = $(this).attr("photo");
					var time = $(this).attr("time");
					var content = $(this).attr("content");
					content = content.replace(/\[/g,"<").replace(/\]/g,">");
					if(owner == "true") li = "<li id=\""+ id +"\"><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\">"+content+"</p></li>";	
					else li = "<li id=\""+ id +"\"><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\">"+content+"</p></li>";	
					show.append(li);
				});
				addEvent();
			}
	    });	
		
	})();
	
	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 +"\"><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 +"\"><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);
		addEvent();
		container.scrollBar();
	}
	
	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;
		});
	}
	
	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();
		$.post(del,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 "";
			}
	}
}

// hide & show content
$.fn.cut = function(length){
	var self = $(this);
	var wholeStr = self.text();
	if(wholeStr.length > length) {
		var cutStr = wholeStr.substr(0,length)+"... ";
		var moreObj = $("<a href=\"#\" class=\"blueBg unline bold\">More</a>").click(function(){self.find(".cut").hide();self.find(".whole").show();return false});
		var lessObj = $("<a href=\"#\" class=\"blueBg unline bold\">Less</a>").click(function(){self.find(".whole").hide();self.find(".cut").show();return false});
		self.html("<div class='whole'></div><div class='cut'></div>");
		self.find(".whole").text(wholeStr).append(lessObj);
		self.find(".cut").text(cutStr).append(moreObj);
		self.find(".whole").hide();
	}
}

$.fn.cutTag = function(){
	var self = $(this);
	var wholeTags = self.find("a");
	if(wholeTags.length > length) {
		var cutTags = wholeTags.slice(0,length);
		var moreObj = $("<a href=\"#\" class=\"blueBg unline bold\">More</a>").click(function(){self.find(".cut").hide();self.find(".whole").show();return false});
		var lessObj = $("<a href=\"#\" class=\"blueBg unline bold\">Less</a>").click(function(){self.find(".whole").hide();self.find(".cut").show();return false});
		self.html("<span class='whole left'></span><span class='cut left'></span>");
		self.find(".whole").html(wholeTags).append(lessObj);
		self.find(".cut").html(cutTags).append(moreObj);
		self.find(".whole").hide();

	}
}


$.fn.message = function(to){	
	var self = $(this);
	
	//init
	if(to) {
		//	
	}
	
	//bind event
	$("#user").click(addTo);
	$("#user .addressee").focus();
	$("#user .addressee").focus(focusTo);
	$("#user .addressee").blur(blurTo);
	$("#user .addressee").keyup(function(e){keyupTo(this,e)});	
	$("#btnSendMessage").click(sendMessage);
	
	function focusTo(){

		$(this).parent().parent().next().show();
		$(this).keydown(function(e){
			if(e.keyCode == 8) {
				if($(this).val()=="") $(this).prev().remove();	
			}
			if(e.keyCode == 40) {
				var current = $("#userList .selected");
				if(!current.next().is("li")) return;
				current.removeClass("selected");
				current.next().addClass("selected");			
			}
			if(e.keyCode == 38) {
				var current = $("#userList .selected");
				if(!current.prev().is("li")) return;
				current.removeClass("selected");
				current.prev().addClass("selected");			
			}
			if(e.keyCode == 13) {
				$(this).blur();
				var current = $("#userList .selected");
				var id = current.attr("userId");
				var username = current.find(".username").text()
				selectUser(id,username);
			}

			});
	}
	
	function blurTo(){
		$(this).parent().parent().next().hide();
		$("#userList").hide();
		$(this).remove()
	}
	
	function addTo(){
		var userWidth = 0,
			totalWidth = $(this).width(),
			obj = $("<input class=\"addressee\" name=\"addressee\" type=\"text\"/>");
		if($(this).find("input").length >= 1) return;
		$(this).find(".username").each(function(i){userWidth += $(this).width()+11});
		obj.css("width",totalWidth-userWidth-8);
		$(this).append(obj);
		$("#user .addressee").focus();
		$("#user .addressee").focus(focusTo);
		$("#user .addressee").blur(blurTo);
		$("#user .addressee").keyup(function(e){keyupTo(this,e)});		
	}
	
	function keyupTo(self,e){
		var val = self.value;
		if(val == "") return;
		if(e.keyCode < 48) return;
		$.post(user_search,"query="+val,function(xml){
			$("#userList").empty();
			var obj = $(xml).find("user");
			if(obj.length == 0) {$("#userList").hide();return}
			var id,name,email;
			obj.each(function(i){
				id = $(this).attr("id");
				username = $(this).attr("username").replace(/\[/g,"<").replace(/\]/g,">");
				email = $(this).attr("email").replace(/\[/g,"<").replace(/\]/g,">");
				$("#userList").append(createUser(id,username,email));
			});
			$("#userList").show();
			$("#userList").children().eq(0).addClass("selected");
			$("#userList li").mouseover(function(){
				$("#userList li").removeClass("selected");
				$(this).addClass("selected");
			});
		});								 
	}
	
	function createAddressee(id,username) {
		return "<a class=\"username\" userId=\""+id+"\" href=\"#\"><span class=\"left\">"+username+"</span><span class=\"close icon\"></span></a>";
	}
	
	function createUser(id,username,email) {
		var obj = $("<li userId=\""+id+"\"><span class=\"username\">"+username+"</span><span class=\"email ml10\">"+email+"</span></li>");
		obj.mousedown(function(){selectUser(id,username)});
		return obj; 	
	}
	
	function selectUser(id,username){
			var user = $("#user").find(".username");
			for(var i=0; i<user.length; i++) {
				if(user.eq(i).attr("userId") == id) { 
					//user.eq(i).focus();
					$("#subject").focus();
					return;	
				}			
			}
			$("#user").append(createAddressee(id,username));
			$("#user a").click(function(){return false});
			$("#user .close").unbind().click(function(){$(this).parent().remove();return false})
			}
			
	function sendMessage(){
		var toID = [],
			messageID = 0,
			subject = $("#messageSubject").val(),
			message = $("#messageContent").text(),
			pars;
		$("#user .username").each(function(){
			toID.push($(this).attr("userId"));								   
		});
		pars = "toID="+toID.toString()+"&messageID="+messageID+"&subject="+subject+"&message="+message;
		$.post(snazlMessage_send,pars,function(str){alert(str)});
	}
}
	


// forgot password
function forgotPassword() {
	var title = "Forgot Password";
	var content = "<span class=\"red\" id=\"passwordHint\" style=\"display:none\"></span><div>Email Address: <input id=\"fPassword\" name=\"fPassword\" type=\"text\" />";
	var btn = {" Next " : getPassword,
				" Cancel " : function(){$("#dialog").remove(); return false}
			};
	$("body").dialog({title: title,content: content,btn: btn});
	$("#dialog .data").find("input").focus(function(){$("#passwordHint").hide();});
	return false;
	
	function getPassword() {
		var email = $("#fPassword").val();
		if(!testEmail(email)) {	
			$("#passwordHint").text("Please enter correct email!");
			$("#passwordHint").show();
			return false;
		}
		$.post(password_forgot,"email="+email,function(str){
			$("#dialog").remove(); 
			var title = "Forgot Password";
			var content = str;
			var btn = {" OK " : function(){$("#dialog").remove(); return false}};
			$("body").dialog({title: title,content: content,btn: btn});
		});
	}

}

// dialog of alert & confirm and so on
$.fn.slider = function(params) {
	var p = params || {};	
	var target =  p.target;
	var direction =  p.direction || "y";
	var step = p.step || 100;
	var speed = p.speed || 2000;
		
	var distance = step;
	if(target.find("li").length <= 1) return;

	if(direction == "y") {
		var timer = window.setInterval(moveY,speed);
	}
	if(direction == "x") {
		var targetW = target.find("li").length * step;
		target.width(targetW);
		var timer = window.setInterval(moveX,speed);
	}

	function moveY(){
		target.animate({marginTop:-distance}, 'slow', '', function(){
			$(this).find("li:first").appendTo($(this));
			$(this).css("marginTop",-distance+step);
		});
	}
	
	function moveX(){
		target.animate({marginLeft:-distance}, 'slow', '', function(){
			$(this).find("li:first").appendTo($(this));
			$(this).css("marginLeft",-distance+step);
		});
	}
}

function addMediaToSnazl(medias) {
	var title = "Add media to SnazL";
	var content = "<div id=\"wrapSnazlet\"><div class=\"tab\"><label><input sType=\"cur\" type=\"radio\" name=\"sType\" checked=\"checked\"/>Current SnazLs</label><label><input sType=\"madesnazl\" type=\"radio\" name=\"sType\"/>SnazLs Created</label><label><input sType=\"managesnazl\" type=\"radio\" name=\"sType\"/>SnazLs Moderated</label><label><input sType=\"favsnazl\" type=\"radio\" name=\"sType\"/>Wow SnazLs</label><label><input sType=\"joinedsnazl\" type=\"radio\" name=\"sType\"/>Subscriptions</label></div><ul class=\"wrap\" style=\"height:150px; overflow-y:scroll; border:1px solid gray\">Loading...</ul></div>";
	var btn = {"Add to SnazL":function(){}};
	$("body").dialog({title: title,content: content,btn: btn});	
	var wrap = $("#dialog .wrap"),
		tabItem = $("#dialog .tab input"),
		type = "cur";
	var pars = "type="+type;
	loadSnazls(type);
	tabItem.focus(function(e){
		type = $(this).attr("sType");
		this.checked = true;
		loadSnazls(type);
	})
	
	function loadSnazls(type) {
		$.ajax({
			type: "POST",
			url: get_snazl_type,
			data: "type="+type,
			dataType: "json",
			success: function(data){
				var num = 0;
				wrap.empty();
				for(var key in data) {
					num++;
					var li = $("<li snazlId=\""+key+"\" style=\"float:left; width:243px; margin:2px; padding:4px;  background:#e1e9ef; overflow:hidden\">"+data[key].snazl_name+"</li>");
					li.hover(function(e){$(this).css({background:"#b2d8f4",cursor:"pointer"})},function(e){$(this).css({background:"#e1e9ef",cursor:"default"})});
					li.appendTo(wrap);
				}
				if(num<=0) {
					wrap.html("no snazl.");
					return;
				}
				wrap.find("li").click(function(e){
					var snazlId = $(this).attr("snazlId");
					$.ajax({
						type: "POST",
						url: snazl_add_media,
						data: "mediaIDs="+ medias +"&spaceIDs="+ snazlId,
						dataType: "json",
						success: function(data){
							$("#dialog").remove();
							var title = data.title;
							var content = data.content;
							$("body").dialog({title: title,content: content});
						}
					});						
					
				});

			}
		})
	}
	
	
	
}