//global vars
var lastChatID = 0; 
var lastPaintID = 0;
var lastMediaListID = 0; 
var lastEntered = 0;
var lastLeft = 0;
var timer = 60;
var loadImg = new Image();
loadImg.src = "../images/loading.gif";

$(function(){
		   

		   
	//init
	$("#member > .container").scrollBar();
	$("#friend > .container").scrollBar();
	$("#spaceMember").scrollBar();
	$("#rightTop").tabs({control:".tab li"});
	$("#rightBot").tabs({control:".tab li"});
	$("#uploadFile").tabs({control:"ul.tab li",target:".subItem",fxFade:"no"});
	$("#video .graBoxTab").tabs({control:"ul.graTab li",target:".graItem",fxFade:"no"});
	$("#audio .graBoxTab").tabs({control:"ul.graTab li",target:".graItem",fxFade:"no"});
	$("#image .graBoxTab").tabs({control:"ul.graTab li",target:".graItem",fxFade:"no"});	
	$("#snazlVideo").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlVideo2").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlImage").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlImage2").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlAudio").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlAudio2").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#myAlbum").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	$("#myAlbum1").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	
	$("#addMedia").tabs({control:".nav li",target:".item",fxFade:"no"});
	$("#addVideo").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	$("#addImage").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	$("#addAudio").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	$("#leftAddMedia").click(function(){addMedia(); return false});

	$("#addMedia_c").tabs({control:".nav li",target:".item",fxFade:"no"});
	$("#addVideo_c").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	$("#addImage_c").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	$("#addAudio_c").tabs({control:".subNav li",target:".subItem",fxFade:"no"});
	$("#snazlVideo_c").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlVideo2_c").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlImage_c").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlImage2_c").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlAudio_c").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	$("#snazlAudio2_c").tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no"});
	
	$("#btnCopyEmbed").bind("click",copy);
	$("#btnCopyUrl").bind("click",copyUrl);
	
	$("#details").cut(120);
	$("#leftBot .description").each(function(i){$(this).cut(40)});
	$("#leftBot .creator").each(function(i){
		var fullName = $(this).text();
		if(fullName.length > 10) fullName = fullName.substr(0,10) + "...";
		$(this).text(fullName);
	});
	
	var backObj = $("<input type=\"button\" value=\"<< Back\" class=\"back\"/>").click(function(){
		var wrap = $(this).parent().parent();
		showStep(wrap,".first");
		return false;
	});
	$("#addMedia .second").prepend(backObj);
	$("#addMedia_c .second").prepend(backObj);
	
	$("#mediaSort").sortable({ placeholder: "hover", revert: true });
	$("#btnEditPlaylist").click(editPlaylist);
	$("#savePlaylist").click(function(){
		var mediaList = getMediaList();	
		if(mediaList == "") {
			alert("There must be at least one item in the playlist!");
			return;
		}	
		var pars = "medias="+mediaList+"&roomID="+roomID;
		$.post(space_editPlaylist,pars,function(){
			$("#editPlaylist").hide();
			$("body").dialog({
			title: "Changes upadated successfully",
			content: "The changes you made to the SnazL's playlist were updated successfully.",
			btn: {" OK ":function(){$("#dialog").remove();}}
			});
		});
	});
	$("#btnEditPlaylistNo").click(function(){
		var title = "You can't do that yet.";
		var content = "You must be a moderator of this SnazL to edit its playlist.";
		var btn = {" OK " : function(){$("#dialog").remove(); return false}};
		$("body").dialog({title: title,content: content,btn: btn});			
		//window.setTimeout(function(){$("#dialog").remove();},2000);
		return false;
	});
	$("#btnAddMediaNo").click(function(){
		var title = "SnazL Alert";
		var content = "You must subscribe to the SnazL to add media!";
		var btn = {" OK " : function(){$("#dialog").remove(); return false}};
		$("body").dialog({title: title,content: content,btn: btn});			
		//window.setTimeout(function(){$("#dialog").remove();},2000);
		return false;
	});
	
	
	
	
	delPlaylist();
	
	$("#switchAddMedia").toggle(
		  function () {
			$("#addMedia_c").show();
			$("#mediaSort").animate({ height: "275px"});
			$("#editPlaylist .content").animate({ top: "6%"});;
			$("#switchAddMedia").css("background-position","60px -950px");
		  },
		  function () {
			$("#addMedia_c").hide();
			$("#mediaSort").animate({ height: "400px"});
			$("#editPlaylist .content").animate({ top: "6%"});;
			$("#switchAddMedia").css("background-position","60px -1002px");
		  }
	); 
	
	//submit the thumb
	$(".submitThumb").click(function uploadThumb(){
		 var wrap = $(this).parent().parent();
		 var thumbWrap = wrap.parent().parent().parent().parent().parent().find(".thumb");
		 var obj = wrap.find(".btnAudioThumb");
		 if(obj[0].value.length == 0)  return false;
		 $.ajaxFileUpload({
			url:audioSnap_upload,
			secureuri:false,
			fileElementId:obj,
			dataType: 'json',
			success: function (data){	
				var wrap = $("#audioThumb .thumb");
				wrap.empty();
				if(data.status != "fail") {
					var imageurl = data.imageurl;
					var thumb = data.th_imageurl;
					var snap_id = data.snap_id;
					var obj = $("<img imageurl=\""+ imageurl +"\" snap_id=\""+ snap_id +"\" src=\"" +thumb+ "\" />");
					thumbWrap.html(obj);
				}
				else {
					var title1 = data.errortype;
					var content1 = data.errormessage;
					var btn1 = {" OK " : function(){$("#dialog").remove(); return false}};
					$("body").dialog({title: title1,content: content1,btn: btn1});				
				}
			}
			});
		 return false;
	});		
	
	$("#btnSnazlVideoTitle").bind("click",function(){return showSnazlMedia($("#videoKeyword"),"title","video")});
	$("#btnSnazlImageTitle").bind("click",function(){return showSnazlMedia($("#imageKeyword"),"title","photo")});
	$("#btnUploadImage").bind("click",function(){uploadImage($("#uploadImage"),"imageupload","photoPath","no");return false});
	$("#btnUploadImage_c").bind("click",function(){uploadImage($("#uploadImage_c"),"imageupload","photoPath_c","yes");return false});
	
	//bind form event
	$("#myAlbum .subNav li").click(function(){var data = $(this).attr("albumId"); listMedia(data,"album"); return false});
	$("#btnMyAlbum").click(function(){var data = $("#myAlbum .subNav li").eq(0).attr("albumId"); listMedia(data,"album"); return false});
	$("#myAlbum1 .subNav li").click(function(){var data = $(this).attr("albumId"); listMedia(data,"album","all",$("#myAlbum1"),"yes"); return false});
	$("#btnMyAlbum1").click(function(){var data = $("#myAlbum1 .subNav li").eq(0).attr("albumId"); listMedia(data,"album","all",$("#myAlbum1"),"yes"); return false});	
	
	$("#formAllVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","all",$("#addVideo .all"),"no"); return false})
	$("#formAllVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","all",$("#addVideo .all"),"no"); return false})
	$("#formSnazlVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","snazl",$("#addVideo .snazl"),"no"); return false})
	$("#formSnazlVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","snazl",$("#addVideo .snazl"),"no"); return false})
	$("#formYoutubeVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","youtube",$("#addVideo .youtube"),"no"); return false})
	$("#formYoutubeVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","youtube",$("#addVideo .youtube"),"no"); return false})
	$("#formPhotobucketVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","photobucket",$("#addVideo .photobucket"),"no"); return false})
	$("#formPhotobucketVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","photobucket",$("#addVideo .photobucket"),"no"); return false})
	$("#formMetacafeVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","metacafe",$("#addVideo .metacafe"),"no"); return false})
	$("#formMetacafeVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","metacafe",$("#addVideo .metacafe"),"no"); return false})
	$("#formMyVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","mine",$("#addVideo .snazl"),"no"); return false})
	$("#formFavVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","fav",$("#addVideo .snazl"),"no"); return false})
	$("#formRatedVideoSearch").submit(function(){var data = this.query.value; listMedia(data,"video","rate",$("#addVideo .snazl"),"no"); return false})
	$("#formMyVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","mine",$("#addVideo .snazl"),"no"); return false})
	$("#formFavVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","fav",$("#addVideo .snazl"),"no"); return false})
	$("#formRatedVideoSearch2").submit(function(){var data = this.query.value; listMedia(data,"video","rate",$("#addVideo .snazl"),"no"); return false})
	
	$("#formAllImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","all",$("#addImage .all"),"no"); return false});
	$("#formAllImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","all",$("#addImage .all"),"no"); return false});
	$("#formGoogleImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","google",$("#addImage .google"),"no"); return false});
	$("#formGoogleImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","google",$("#addImage .google"),"no"); return false});
	$("#formFlickrImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","flickr",$("#addImage .flickr"),"no"); return false});
	$("#formFlickrImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","flickr",$("#addImage .flickr"),"no"); return false});
	$("#formPhotobucketImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","photobucket",$("#addImage .photobucket"),"no"); return false});
	$("#formPhotobucketImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","photobucket",$("#addImage .photobucket"),"no"); return false});
	$("#formSnazlImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","snazl",$("#addImage .snazl"),"no"); return false});
	$("#formSnazlImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","snazl",$("#addImage .snazl"),"no"); return false});
	$("#formMyImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","mine",$("#addImage .snazl"),"no"); return false})
	$("#formFavImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","fav",$("#addImage .snazl"),"no"); return false})
	$("#formRatedImageSearch").submit(function(){var data = this.query.value; listMedia(data,"imageurl","rate",$("#addImage .snazl"),"no"); return false})
	$("#formMyImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","mine",$("#addImage .snazl"),"no"); return false})
	$("#formFavImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","fav",$("#addImage .snazl"),"no"); return false})
	$("#formRatedImageSearch2").submit(function(){var data = this.query.value; listMedia(data,"imageurl","rate",$("#addImage .snazl"),"no"); return false})	
	
	
	$("#formAllAudioURL").submit(function(){var data = this.url.value; addAudioByURL($("#addAudio .url"),data); return false});
	$("#audioFile").change(function(){audioUpload($("#formUploadAudio"))});
	$("#formSnazlAudioSearch").submit(function(){var data = this.query.value; listMedia(data,"audio","snazl",$("#addAudio .snazl"),"no"); return false});
	$("#formSnazlAudioSearch2").submit(function(){var data = this.query.value; listMedia(data,"audio","snazl",$("#addAudio .snazl"),"no"); return false});
	$("#formAllVideoURL").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo .all"),data);return false});
	$("#formYoutubeVideoURL").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo .youtube"),data);return false});
	$("#formPhotobucketVideoURL").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo .photobucket"),data);return false});
	$("#formMetacafeVideoURL").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo .metacafe"),data);return false});
	$("#formMyAudioSearch").submit(function(){var data = this.query.value; listMedia(data,"audio","mine",$("#addAudio .snazl"),"no"); return false})
	$("#formFavAudioSearch").submit(function(){var data = this.query.value; listMedia(data,"audio","fav",$("#addAudio .snazl"),"no"); return false})
	$("#formRatedAudioSearch").submit(function(){var data = this.query.value; listMedia(data,"audio","rate",$("#addAudio .snazl"),"no"); return false})
	$("#formMyAudioSearch2").submit(function(){var data = this.query.value; listMedia(data,"audio","mine",$("#addAudio .snazl"),"no"); return false})
	$("#formFavAudioSearch2").submit(function(){var data = this.query.value; listMedia(data,"audio","fav",$("#addAudio .snazl"),"no"); return false})
	$("#formRatedAudioSearch2").submit(function(){var data = this.query.value; listMedia(data,"audio","rate",$("#addAudio .snazl"),"no"); return false})
	
	
	$("#formAllImageURL").submit(function(){var data = $(this).getForm(); addMediaByURL("imageurl",$("#addImage .all"),data);return false});





	//bind form event (edit playlist)
	$("#formAllVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","all",$("#addVideo_c .all"),"yes"); return false})
	$("#formAllVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","all",$("#addVideo_c .all"),"yes"); return false})
	$("#formSnazlVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","snazl",$("#addVideo_c .snazl"),"yes"); return false})
	$("#formSnazlVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","snazl",$("#addVideo_c .snazl"),"yes"); return false})
	$("#formYoutubeVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","youtube",$("#addVideo_c .youtube"),"yes"); return false})
	$("#formYoutubeVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","youtube",$("#addVideo_c .youtube"),"yes"); return false})
	$("#formPhotobucketVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","photobucket",$("#addVideo_c .photobucket"),"yes"); return false})
	$("#formPhotobucketVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","photobucket",$("#addVideo_c .photobucket"),"yes"); return false})
	$("#formMetacafeVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","metacafe",$("#addVideo_c .metacafe"),"yes"); return false})
	$("#formMetacafeVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","metacafe",$("#addVideo_c .metacafe"),"yes"); return false})
	$("#formMyVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","mine",$("#addVideo_c .snazl"),"yes"); return false})
	$("#formFavVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","fav",$("#addVideo_c .snazl"),"yes"); return false})
	$("#formRatedVideoSearch_c").submit(function(){var data = this.query.value; listMedia(data,"video","rate",$("#addVideo_c .snazl"),"yes"); return false})
	$("#formMyVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","mine",$("#addVideo_c .snazl"),"yes"); return false})
	$("#formFavVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","fav",$("#addVideo_c .snazl"),"yes"); return false})
	$("#formRatedVideoSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"video","rate",$("#addVideo_c .snazl"),"yes"); return false})
	
	$("#formAllImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","all",$("#addImage_c .all"),"yes"); return false});
	$("#formAllImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","all",$("#addImage_c .all"),"yes"); return false});
	$("#formGoogleImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","google",$("#addImage_c .google"),"yes"); return false});
	$("#formGoogleImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","google",$("#addImage_c .google"),"yes"); return false});
	$("#formFlickrImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","flickr",$("#addImage_c .flickr"),"yes"); return false});
	$("#formFlickrImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","flickr",$("#addImage_c .flickr"),"yes"); return false});
	$("#formPhotobucketImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","photobucket",$("#addImage_c .photobucket"),"yes"); return false});
	$("#formPhotobucketImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","photobucket",$("#addImage_c .photobucket"),"yes"); return false});
	$("#formSnazlImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","snazl",$("#addImage_c .snazl"),"yes"); return false});
	$("#formSnazlImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","snazl",$("#addImage_c .snazl"),"yes"); return false});
	$("#formMyImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","mine",$("#addImage_c .snazl"),"yes"); return false})
	$("#formFavImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","fav",$("#addImage_c .snazl"),"yes"); return false})
	$("#formRatedImageSearch_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","rate",$("#addImage_c .snazl"),"yes"); return false})
	$("#formMyImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","mine",$("#addImage_c .snazl"),"yes"); return false})
	$("#formFavImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","fav",$("#addImage_c .snazl"),"yes"); return false})
	$("#formRatedImageSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"imageurl","rate",$("#addImage_c .snazl"),"yes"); return false})	
	
	
	$("#formAllAudioURL_c").submit(function(){var data = this.url.value; addAudioByURL($("#addAudio_c .url"),data); return false});
	$("#audioFile_c").change(function(){audioUpload($("#formUploadAudio_c"))});
	$("#formSnazlAudioSearch_c").submit(function(){var data = this.query.value; listMedia(data,"audio","snazl",$("#addAudio_c .snazl"),"yes"); return false});
	$("#formSnazlAudioSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"audio","snazl",$("#addAudio_c .snazl"),"yes"); return false});
	$("#formAllVideoURL_c").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo_c .all"),data);return false});
	$("#formYoutubeVideoURL_c").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo_c .youtube"),data);return false});
	$("#formPhotobucketVideoURL_c").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo_c .photobucket"),data);return false});
	$("#formMetacafeVideoURL_c").submit(function(){var data = $(this).getForm(); addMediaByURL("video",$("#addVideo_c .metacafe"),data);return false});
	$("#formMyAudioSearch_c").submit(function(){var data = this.query.value; listMedia(data,"audio","mine",$("#addAudio_c .snazl"),"yes"); return false})
	$("#formFavAudioSearch_c").submit(function(){var data = this.query.value; listMedia(data,"audio","fav",$("#addAudio_c .snazl"),"yes"); return false})
	$("#formRatedAudioSearch_c").submit(function(){var data = this.query.value; listMedia(data,"audio","rate",$("#addAudio_c .snazl"),"yes"); return false})
	$("#formMyAudioSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"audio","mine",$("#addAudio_c .snazl"),"yes"); return false})
	$("#formFavAudioSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"audio","fav",$("#addAudio_c .snazl"),"yes"); return false})
	$("#formRatedAudioSearch2_c").submit(function(){var data = this.query.value; listMedia(data,"audio","rate",$("#addAudio_c .snazl"),"yes"); return false})
	
	
	$("#formAllImageURL_c").submit(function(){var data = $(this).getForm(); addMediaByURL("imageurl",$("#addImage_c .all"),data);return false});


	$("#leftBot .spaceItem").each(function(i){
		var wrap = $(this).find(".thumb");
		var obj = wrap.find("ul");
		wrap.slider({target:obj,direction:"x",step:100,speed:2000});
	});	

	
	onlineTimer = window.setTimeout(getOnlines,60000);
	numTimer();

	//bind event	
	$("#addFavorite").bind("click",addFavorite);
	$("#inviteFriend").bind("click",inviteToSpace);
	$("#joinSpace").bind("click",joinSpace);
	$("#updateUser").bind("click",function(){
		window.clearTimeout(onlineTimer);
		getOnlines();
		return false;
	});
	
	operateUser();
	
	//my friends status
	updateFriendStatus();
	offFriendInvite();
});

/* window.onload = function(){spaceTimer = window.setTimeout(spaceListener,2000);} */

function getOnlines() {
	var container = $("#member").find(".userList");
	container.html("<img style=\"margin-left:120px;margin-top:130px\" src=\"../images/loading.gif\" width=\"16\" height=\"16\" />");
	$.ajax({
	    type: "POST",
	    url: onlines_get,
	    data: "roomID="+roomID,
	    success: handleOnline
	});	
	
	function handleOnline(xml) {
		var users = $(xml).find("user");
		var userStr = "";
		users.each(function(i){
			var userId = $(this).attr("id");
			var identity = $(this).attr("status");		
			var friend = $(this).attr("friend");		
			var photo = $(this).attr("photo");
			var username = $(this).attr("username");	
			var location = $(this).attr("location");
			var iconStr;
			switch(identity) {
				case "creator": iconStr = "<span class=\"isCreator icon\" title=\"creator\"></span>";break;
				case "admin": iconStr = "<span class=\"isAdmin icon\" title=\"admin\"></span>";break;
				case "member": iconStr = "<span class=\"isMember icon\" title=\"member\"></span>";break;
				case "blocked": iconStr = "<span class=\"isBlock icon\" title=\"blocked user\"></span>";break;
				default: iconStr = "";break;
			}
			userStr += "<li userId=\""+userId+"\" identity=\""+identity+"\" friend=\""+friend+"\">";
            userStr +=      "<div class=\"head\"><a href=\"/user/"+userId+"\" title=\"to "+username+"'s profile\"><img src=\""+photo+"\" width=\"25\" height=\"25\"/></a></div>";
            userStr +=      "<div class=\"username\"><a href=\"/user/"+userId+">\" title=\"to "+username+"'s profile\">"+username+"</a></div>";
            userStr +=      "<div class=\"address\">"+location+"</div>";
            userStr +=      "<div class=\"identity\">"+iconStr+"</div>";
            userStr += "</li>";
		});
		container.html(userStr);
		$("#member > .container").scrollBar();
		operateUser();
		timer = 60;
		onlineTimer = window.setTimeout(getOnlines,60000);
	}
}

//who's here funciton
function operateUser(){
	
	// select user
	var current = 0,currentId,currentUser,currentObj,currentType;
	var users = $("#member .userList").find("li");
	users.each(function(i) {
		$(this).click(function(){
			users.eq(current).removeClass("hover");
			$(this).addClass("hover");
			current = i;
			currentId = users.eq(current).attr("userId");
			currentUser = users.eq(current).find(".username").text();
			currentObj = users.eq(current);
			currentType = users.eq(current).attr("identity");
			
			if(currentObj.attr("friend") != "yes") $("#addFriend").removeClass("disabled");
			else $("#addFriend").addClass("disabled");
			
			if(currentObj.attr("identity") != "block") $("#blockUser").removeClass("disabled");
			else $("#blockUser").addClass("disabled");
			
		});
	});
		
	// add event for tools
	$("#addFriend").unbind().bind("click",function(){addFriend($(this),currentObj,currentId,currentUser);return false});	
	$("#blockUser").unbind().bind("click",function(){blockUser($(this),currentObj,currentUser,roomID,currentId);return false});		

};


function disabled(){
	var title = "Operate Fail";
	var content = "You didn't select a user or The operation is not allowed!";
	var btn = {" OK " : function(){$("#dialog").remove(); return false}};
	$("body").dialog({title: title,content: content,btn: btn});			
	window.setTimeout(function(){$("#dialog").remove();},2000);
	return false;
}

function addFriend(self,currentObj,currentId,currentUser){
	if(!currentId || currentId == 0 || uID == currentId || currentObj.attr("friend") == "yes") {
		disabled();
		return;
	}
	var title = "Add Friend:";
	var content = "Your friend request (<span class='red'>"+currentUser+"</span>) 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="+currentId);
	currentObj.attr("addFriend","yes");
	self.addClass("disabled");
}

function blockUser(self,currentObj,currentUser,roomID,currentId){
	if(!currentId || currentId == 0 || currentObj.attr("identity") == "block" || uID == currentId) {
		disabled();
		return;
	}
	var title = "Block User";
	var content = "You have blocked " + currentUser;
	var btn = {" OK " : function(){$("#dialog").remove(); return false}};
	$("body").dialog({title: title,content: content,btn: btn});
	window.setTimeout(function(){$("#dialog").remove();},2000);
	currentObj.find(".identity").html("<span class=\"isBlock icon\" title=\"Blocked\"></span>");
	$.post(user_block,"roomID="+roomID+"&userID="+currentId);
	currentObj.attr("identity","block");
	self.addClass("disabled");
}

function numTimer() {
	$("#updateUser u").text(timer);
	timer--;
	window.setTimeout(numTimer,1000);
}

function setNumTimer(s) {

}

function showHind(str) {
	$("#spaceHint").empty();
	$("#spaceHint").text(str);
	$("#spaceHint").fadeIn();
	window.setTimeout(function(){$("#spaceHint").fadeOut()},2000);
}

function joinSpace() {
	showHind("Your request has been sent to the owner of this snazl!");
	$.post(space_join,"roomID="+roomID);
}
function addFavorite() {
	showHind("Your friends know you've WOWed this SnazL!");
	$.post(add_favorite,"id="+roomID+"&type=rooms");
}

function spaceListener() {
	var data = "roomID="+roomID+"&lastChatID="+lastChatID+"&lastPaintID="+lastPaintID+"&lastMediaListID="+lastMediaListID+"&lastEntered="+lastEntered+"&lastLeft="+lastLeft;
	$.ajax({
	    type: "POST",
	    url: space_update,
	    data: data,
	    success: handleListener
	});	
}

function handleListener(xml) {
	//var oSerializer = new XMLSerializer();
	//var oXmlDoc = oSerializer.serializeToString(xml);
	//alert(oXmlDoc);
	
	var spaceInfo = $(xml).find("space");
	var newLastChatID = spaceInfo.attr("lastChatID");
	var newLastPaintID = spaceInfo.attr("lastPaintID");
	var newLastMediaListID = spaceInfo.attr("lastMediaListID");
	var newLastEntered = spaceInfo.attr("lastEntered");
	var newLastLeft = spaceInfo.attr("lastLeft");

	/*			
	getFla("chatBoard").handleChatContent(xmlToString(spaceInfo.find("chatroom")[0]));
	try {
		getFla("paints").handlePaintData(xmlToString(spaceInfo.find("paint")[0]));
	} catch(e) { // do nothing
	}
	*/
	if(lastMediaListID != newLastMediaListID) getFla("mediaPlayer").hanldePlayList(xmlToString(spaceInfo.find("medias")[0]));
	if(lastEntered != newLastEntered) handleEnter($(spaceInfo).find("entered"));
	if(lastLeft != newLastLeft) handleLeft($(spaceInfo).find("left"));

	lastChatID = newLastChatID; 
	lastPaintID = newLastPaintID;
	lastMediaListID = newLastMediaListID;
	lastEntered = newLastEntered;
	lastLeft = newLastLeft;
	
	spaceTimer = window.setTimeout(spaceListener,1000);
}

function getFla(name) {
	if ($.browser.msie) {
	   return document.getElementById(name);
	}else{
	   return document[name];
	}
}

function handleEnter(data){
	
}

function handleLeft(data){
	
}

function xmlToString(xml) {
	var str;
	if($.browser.msie) str = xml.xml; 
	else str = (new XMLSerializer()).serializeToString(xml);
	return str;
}

function zring_createXml(str){
	if(window.ActiveXObject){
		var xmlDom=new ActiveXObject("Microsoft.XMLDOM");
		xmlDom.loadXML(str);
		return xmlDom;
	}else return new DOMParser().parseFromString(str, "text/xml");
}

function listMedia(data,type,subType,where,topPlaylist) {
	
	if(type == "album") {
		var pars = "albumID=" + data;
		var wrap = $("#myAlbum .subItem:visible");
		if(topPlaylist == "yes") wrap = where.find(".subItem:visible");
		wrap.find(".mediaBrowse").html("<div style=\"text-align:center\"><img style=\"margin-top:100px\" src=\"images/loading.gif\" width=\"16\" height=\"16\" /></div>");	 

		$.post(album_getmedia,pars,function(xml){
																
			var container = wrap.find(".mediaBrowse"),
				medias = $(xml).find("media");
				container.empty();
				if(medias.length < 1) {
					container.html("<div style=\"padding-top:90px;text-align:center\">No media in this album.</div>");
					return false;
				}
				medias.each(function(i){
				var title,
					allTitle = $(this).attr("title") || "",
					thumb = $(this).attr("thumb") || "",
					source = $(this).attr("source") || "",
					url = $(this).attr("url") || "",
					keywords = $(this).attr("keywords") || "",
					mType = $(this).attr("type") || "",
					id = $(this).attr("id"),
					description = $(this).attr("description") || "";
				if(allTitle.length > 18) title = allTitle.substr(0,15) + "...";
				else title = allTitle;
				if(keywords != "")
					var	media = $("<li><div class=\"detailBox\"><div class=\"detail\"><div class=\"arrow\"></div><div class=\"content\"><h3 class='f14px'>"+ allTitle +"</h3><strong>Tags: </strong>"+ keywords + "<br /><strong>description: </strong>" + description +"</div></div></div><a href=\"#\"><div class=\"thumb\"><img src=\""+ thumb +"\" width=\"120\" height=\"90\"/></div><h3 class=\"ml10\"><span class=\""+mType+"\"></span><strong class=\"left\">"+ title +"</strong></h3><div class=\"form gray\">"+ source +"</div></a></li>");
				else 
					var	media = $("<li><div class=\"detailBox\"><div class=\"detail\"><div class=\"arrow\"></div><div class=\"content\"><h3 class='f14px'>"+ allTitle +"</h3>description: </strong>" + description +"</div></div></div><a href=\"#\"><div class=\"thumb\"><img src=\""+ thumb +"\" width=\"120\" height=\"90\"/></div><h3 class=\"ml10\"><span class=\""+mType+"\"></span><strong class=\"left\">"+ title +"</strong></h3><div class=\"form gray\">"+ source +"</div></a></li>");
				media.mouseover(function(){
					if(description == "" && title == allTitle) return;	 
					$(this).find(".detail").show();						 
				});
				media.mouseout(function(){
					$(this).find(".detail").hide();						 
				});						
				media.click(function(){
					var objMedia = $("<li mediaId=\""+ id +"\"><div class=\"thumb\"><img title=\""+ allTitle +"\" src=\""+ thumb +"\" /></div><h3><strong>"+ title +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>");
					$(this).remove();
					addToPlaylist(id,topPlaylist,objMedia);	
				});
				container.append(media);
				});
											 
								 
		});
		
		
		
		
		return false;
		
	}	
	
	
	
	var url,
		query = data,
		obj = where.find(".second");

	data = "query=" + query + "&type="+subType;
	
	//change the second form tab
	if(subType) {
		var formType;
		switch(type) {
			case "video": formType = $("#editPlaylist:hidden").length > 0 ? $("#snazlVideo2") : $("#snazlVideo2_c"); break;
			case "imageurl": formType = $("#editPlaylist:hidden").length > 0 ? $("#snazlImage2") : $("snazlImage2_c"); break;
			case "audio": formType = $("#editPlaylist:hidden").length > 0 ? $("#snazlAudio2") : $("#snazlAudio2_c"); break;
			default: formType =  $("#editPlaylist:hidden").length > 0 ? $("#snazlVideo2") : $("#snazlVideo2_c"); break;
		}
		
		if(subType == "mine") formType.tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no",playTab:2});
		if(subType == "fav") formType.tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no",playTab:3});
		if(subType == "rate") formType.tabs({control:".thirdNav li",target:".snazlItem",fxFade:"no",playTab:4});
	}
	
	showStep(where,".second");
	obj.find(".mediaBrowse").html("<div style=\"text-align:center\"><img style=\"margin-top:100px\" src=\"images/loading.gif\" width=\"16\" height=\"16\" /></div>");
	obj.find("input[name='query']").val(query);

	if(type == "video") {
		url = video_search;
		if(subType == "mine" || subType == "fav" || subType == "rate") {
			url = personalMedia_search;
			data += "&mediaType=video&userID="+cookId;
		}
		$.post(url,data,function(xml){
			var container = obj.find(".mediaBrowse"),
				medias = $(xml).find("video");
				container.empty();
				if(medias.length < 1) {
					var noResultHint;
					switch(subType) {
						case "snazl": noResultHint = "We don't have a video matching your request in our database yet. You can add it to the SnazL database by <a href=\"/uploadmedia\" target=\"_blank\" class=\"blue bold unline\">uploading it</a>."; break;
						case "mine": noResultHint = "You have not added any video to SnazL yet."; break;
						case "fav": noResultHint = "You have not favorited any video yet."; break;
						case "rate": noResultHint = "You have not rated any video yet."; break;
						default: noResultHint = "No videos were found matching \""+ query +"\". You can add the video directly using its url."; break;
					}
					container.html("<div style=\"padding-top:90px;text-align:center\">"+noResultHint+"</div>");
					return false;
				}
				medias.each(function(i){
				var title,
					allTitle = $(this).attr("title"),
					thumb = $(this).attr("thumb"),
					source = $(this).attr("source"),
					url = $(this).attr("url"),
					keywords = $(this).attr("keywords"),
					description = $(this).attr("description"),
					ori = $(this).attr("ori_owner");
				if(description == window.undefined)	 description = "";
				if(allTitle.length > 18) title = allTitle.substr(0,15) + "...";
				else title = allTitle;
				if(keywords != window.undefined)
					var	media = $("<li><div class=\"detailBox\"><div class=\"detail\"><div class=\"arrow\"></div><div class=\"content\"><h3 class='f14px'>"+ allTitle +"</h3><strong>Tags: </strong>"+ keywords + "<br /><strong>description: </strong>" + description +"</div></div></div><a href=\"#\"><div class=\"thumb\"><img src=\""+ thumb +"\" width=\"120\" height=\"90\"/></div><h3><strong>"+ title +"</strong></h3><div class=\"form gray\">"+ source +"</div></a></li>");
				else 
					var	media = $("<li><div class=\"detailBox\"><div class=\"detail\"><div class=\"arrow\"></div><div class=\"content\"><h3 class='f14px'>"+ allTitle +"</h3>description: </strong>" + description +"</div></div></div><a href=\"#\"><div class=\"thumb\"><img src=\""+ thumb +"\" width=\"120\" height=\"90\"/></div><h3><strong>"+ title +"</strong></h3><div class=\"form gray\">"+ source +"</div></a></li>");
				media.mouseover(function(){
					if(description == "" && title == allTitle) return;	 
					$(this).find(".detail").show();						 
				});
				media.mouseout(function(){
					$(this).find(".detail").hide();						 
				});						
				if(subType == "snazl" || subType == "mine" || subType == "fav" || subType == "rate") {
					var id = $(this).attr("id");
					media.click(function(){
						var objMedia = $("<li mediaId=\""+ id +"\"><div class=\"thumb\"><img title=\""+ allTitle +"\" src=\""+ thumb +"\" /></div><h3><strong>"+ title +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>");
						$(this).remove();
						addToPlaylist(id,topPlaylist,objMedia);	
					});
				}
				else media.click(function(){addMediaInfo(type,where,thumb,allTitle,ori,keywords,description,url,".second",topPlaylist);$(this).remove();return false});
				container.append(media);
				});
		});
	}
	
	if(type == "imageurl") {
		url = image_search;
		if(subType == "mine" || subType == "fav" || subType == "rate") {
			url = personalMedia_search;
			data += "&mediaType=imageurl&userID="+cookId;
		}		
		$.post(url,data,function(xml){
			var container = obj.find(".mediaBrowse"),
				medias = $(xml).find("image");
				container.empty();

				if(medias.length < 1) {
					var noResultHint;
					switch(subType) {
						case "snazl": noResultHint = "We don't have an image matching your request in our database yet. You can add it to the SnazL database by <a href=\"/uploadmedia\" target=\"_blank\" class=\"blue bold unline\">uploading it</a>."; break;
						case "mine": noResultHint = "You have not added any image to SnazL yet."; break;
						case "fav": noResultHint = "You have not favorited any image yet."; break;
						case "rate": noResultHint = "You have not rated any image yet."; break;
						default: noResultHint = "No images were found matching \""+ query +"\". You can add the image using its url."; break;
					}
					container.html("<div style=\"padding-top:90px;text-align:center\">"+noResultHint+"</div>");
					return false;
				}	
				
				medias.each(function(i){
				var title,
					allTitle = $(this).attr("title") || "",
					thumb = $(this).attr("thumb") || "",
					source = $(this).attr("source") || "",
					url = $(this).attr("url") || "",
					keywords = $(this).attr("keywords") || "",
					description = $(this).attr("description") || "",
					ori = $(this).attr("ori_owner");
					
					if(allTitle.length > 23) title = allTitle.substr(0,20) + "...";
					else title = allTitle;
					
				var media = $("<li><a href=\"#\" title=\""+ description +"\"><div class=\"thumb\"><img title=\""+ allTitle +"\" src=\""+ thumb +"\" width=\"120\" height=\"90\"/></div><h3><strong>"+ title +"</strong></h3><div class=\"form gray\">"+ source +"</div></a></li>");
				if(subType == "snazl" || subType == "mine" || subType == "fav" || subType == "rate")  {
					var id = $(this).attr("id");
					media.click(function(){
						var objMedia = $("<li mediaId=\""+ id +"\"><div class=\"thumb\"><img title=\""+ allTitle +"\" src=\""+ thumb +"\" /></div><h3><strong>"+ title +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>");
						$(this).remove();
						addToPlaylist(id,topPlaylist,objMedia);	
					});
				}
				else media.click(function(){addMediaInfo(type,where,thumb,allTitle,ori,keywords,description,url,".second",topPlaylist);$(this).remove();return false});
				container.append(media);
				});
		});
	}
	
	if(type == "audio") {
		url = audio_search;
		if(subType == "mine" || subType == "fav" || subType == "rate") {
			url = personalMedia_search;
			data += "&mediaType=audio&userID="+cookId;
		}
		$.post(url,data,function(xml){
			var container = obj.find(".mediaBrowse"),
				medias = $(xml).find("audio");
				container.empty();

				if(medias.length < 1) {
					var noResultHint;
					switch(subType) {
						case "snazl": noResultHint = "We don't have an audio matching your request in our database yet. You can add it to the SnazL database by <a href=\"/uploadmedia\" target=\"_blank\" class=\"blue bold unline\">uploading it</a>."; break;
						case "mine": noResultHint = "You have not added any audio to SnazL yet."; break;
						case "fav": noResultHint = "You have not favorited any audio yet."; break;
						case "rate": noResultHint = "You have not rated any audio yet."; break;
						default: noResultHint = "No audio were found matching \""+ query +"\". You can add the audio using its url."; break;
					}
					container.html("<div style=\"padding-top:90px;text-align:center\">"+noResultHint+"</div>");
					return false;
				}

				medias.each(function(i){
				var title,
					allTitle = $(this).attr("title"),
					thumb = $(this).attr("thumb"),
					source = $(this).attr("source"),
					url = $(this).attr("url"),
					keywords = $(this).attr("keywords"),
					description = $(this).attr("description");
				if(description == window.undefined)	 description = "";
				if(allTitle.length > 18) title = allTitle.substr(0,15) + "...";
				else title = allTitle;
				if(keywords != window.undefined)
					var	media = $("<li><div class=\"detailBox\"><div class=\"detail\"><div class=\"arrow\"></div><div class=\"content\"><h3 class='f14px'>"+ allTitle +"</h3><strong>Tags: </strong>"+ keywords + "<br /><strong>description: </strong>" + description +"</div></div></div><a href=\"#\"><div class=\"thumb\"><img src=\""+ thumb +"\" width=\"120\" height=\"90\"/></div><h3><strong>"+ title +"</strong></h3><div class=\"form gray\">"+ source +"</div></a></li>");
				else 
					var	media = $("<li><div class=\"detailBox\"><div class=\"detail\"><div class=\"arrow\"></div><div class=\"content\"><h3 class='f14px'>"+ allTitle +"</h3>description: </strong>" + description +"</div></div></div><a href=\"#\"><div class=\"thumb\"><img src=\""+ thumb +"\" width=\"120\" height=\"90\"/></div><h3><strong>"+ title +"</strong></h3><div class=\"form gray\">"+ source +"</div></a></li>");
				media.mouseover(function(){
					if(description == "" && title == allTitle) return;	 
					$(this).find(".detail").show();						 
				});
				media.mouseout(function(){
					$(this).find(".detail").hide();						 
				});						
				if(subType == "snazl" || subType == "mine" || subType == "fav" || subType == "rate") {
					var id = $(this).attr("id");
					media.click(function(){
						var objMedia = $("<li mediaId=\""+ id +"\"><div class=\"thumb\"><img title=\""+ allTitle +"\" src=\""+ thumb +"\" /></div><h3><strong>"+ title +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>");
						$(this).remove();
						addToPlaylist(id,topPlaylist,objMedia);	
					});
				}
				else media.click(function(){addMediaInfo(type,where,thumb,allTitle,keywords,description,url,".second",topPlaylist);$(this).remove();return false});
				container.append(media);
				});
		});
	}
	
}


function addMediaInfo(type,where,thumb,title,ori,tags,description,url,to,topPlaylist) {
	tags = (tags == window.undefined)?"":tags;
	title = (title == window.undefined)?"":title;
	description = (description == window.undefined)?"":description;
	var container = where.find(".third"),
		mType,
		form = container.find("form");
	showStep(where,".third");
	container.find(".thumb img").attr("src",thumb);
	container.find("input[name='title']").val(title);
	container.find("input[name='tags']").val(tags);
	container.find("textarea[name='description']").val(description);
	if(ori) container.find("input[name='oriOwner']").val(ori);
	if(ori&&ori!="")  container.find("input[name='oriOwner']").attr("disabled","disabled");
	container.find(".back").click(function(){showStep(where,".second");return false});
	form.unbind().submit(function(){
		$("body").append("<div id=\"loading\"><div class=\"wrap bold\"><img src=\"/images/loading.gif\" /><br />Adding...</div><div class=\"bg\"></div></div>");
		if(where.find("input[name='title']").val() == "") {
			$("body").dialog({content: "Title cannot be empty.!"});
			return false;
		}
		var data = $(this).getForm();
		if(url==thumb) data += "&type="+type+"&url="+url;
		else data += "&type="+type+"&url="+url+"&thumb="+thumb;
		if(type == "audio") {
			var thumbWrap = $(this).parent().parent().find(".thumb");
			thumb = thumbWrap.find("img").attr("src");
			data += "&snap_id=" + thumbWrap.find("img").attr("snap_id");
		}			
		$.post(media_add,data,function(xml){
			$("#loading").remove();
			var media = $(xml).find("media");
			var id = media.attr("id");
			var name = media.attr("name") || "";
			var allName = name;
			if(name.length > 15) name = name.substr(0,12) + "...";
			if(media.length < 1) {
				alert("Adding failed, Please try again!");
				showStep(where,".second");
				return false;
			}
			if($("#mediaSort").find("li").length < 1) $("#mediaSort").empty();
			if(title=="") title = name;
			if(title.length > 15) title = title.substr(0,12) + "...";
			if(type=="video") mType = "Video";
			if(type=="imageurl") mType = "Image";
			if(type=="audio") mType = "Audio";			
			var objMedia = $("<li mediaId=\""+ id +"\" title=\"" +allName+ "\"><div class=\"thumb\"><img src=\""+ thumb +"\" /></div><h3><span class=\"is"+mType+"\"></span><strong>"+ title +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>");
			delPlaylist();
			//$("#addMedia .hintSuccess").fadeIn(2000); 
			//$("#addMedia .hintSuccess").fadeOut(4000);
			addToPlaylist(id,topPlaylist,objMedia);
			showStep(where,to);
						
		})
		return false;
	});
	return false;
}


function delPlaylist() {
	$("#mediaSort .delete").each(function(i){
		$(this).unbind().click(function(){
			var obj = $(this).parent().parent();
			$("#mediaSort").confirm({title:"Delete Item",content:"Are you sure you want to delete this item from your SnazL playlist?",btn:{" Delete! ": function(){$("#dialog").remove(); fuc(self,obj)}," Cancel " : function(){$("#dialog").remove(); return false} }},obj,del);
			return false;
		});
	});
}

function del(where,obj) {
	obj.remove();
	if(where.find("li").length < 1) 
	$(".btnNext").css("display","none");
}

function getMediaList() {
	var list = "";
	$("#mediaSort li").each(function(i){
		 list += $(this).attr("mediaId")+",";
	});
	list = list.substr(0,list.length-1);
	return list;
}

function addToPlaylist(id,topPlaylist,objMedia) {
	$("body").dialog({
	title: "Item added to this SnazL",
	content: "Are you sure you want to add this item to this SnazL? Everyone in this SnazL will see it.",
	btn: {" OK ":function(){$("#dialog").remove(); doAdd()},
		  "Cancel":function(){$("#dialog").remove(); return false}
		}
	});	
	
	
	function doAdd() {
		var pars = "roomID="+roomID+"&mediaID="+id;
		$.post(addMediaToPlaylist,pars,function(str){
			 if(topPlaylist != "yes") {
				$("body").dialog({
				title: "Item added to this SnazL",
				content: "The new media added might require a few moments to download before it can be played properly!",
				btn: {"Add more":function(){$("#dialog").remove(); return false},
					  "Done":function(){$("#dialog").remove(); $("#upload").hide(); return false}
					}
				});		
			 } else {
				$("#mediaSort").append(objMedia);
				$("#mediaSort").sortable({ placeholder: "hover", revert: true });
				delPlaylist();
			 }
		});	
	}
}

function showStep(where,showObj) {
	where.find(".first").hide();
	where.find(".second").hide();
	where.find(".third").hide();
	where.find(showObj).show();
}

function audioUpload(where) {
	var obj = where.find("input[name='audioFile']");
	if(obj.val() == "") return;
	
	where.submit();
	obj.next().after("<div style=\"height:20px; margin-right:30px; background:url('images/loading.gif') center no-repeat; line-height:20px; font-weight:bold; text-align:center\"><span style=\"padding-left:85px\">Uploading...</span></div>");
	return false;
}

function addAudioByURL(where,data) {
	if(!testUrl(data)) {
		$("body").dialog({content: "Please enter a correct URL!"});
		return;
	}
	var data = "url=" + data,
		obj = where.find(".byURL"),
		boxHtml = obj.html();
	obj.html("<div style=\"height:20px; margin-right:30px; background:url('images/loading.gif') center no-repeat; line-height:20px; font-weight:bold; text-align:center\"><span style=\"padding-left:85px\">Uploading...</span></div>");
	$.post(audio_url,data,function(xml){
		var obj = $(xml).find("audio");
		if(obj.length < 1) {
			showStep(where,".first");
			return;
		}
		var url = obj.attr("url");
		addMediaInfo("audio",$("#addAudio .url"),"images/audio.gif","","","","",url,".third");
		obj.html(boxHtml);
		obj.find("input[name='url']").val("");
	});
}


function uploadAudioResponse(info,data,name) {
	var topPlaylist = "no";
	var wrapper = $("#addAudio");
	var btnEnter = $("#audioFile");
	if($("#editPlaylist:visible").length > 0)  {
		topPlaylist = "yes";
		wrapper = $("#addAudio_c");
		btnEnter = $("#audioFile_c");
	}
	var hintObj = btnEnter.next();
	hintObj.next().remove();
	if(info == "false") alert(data);
	else if(info == "true") {
		hintObj.after("<div style=\"height:20px; background:url('images/loading.gif') center no-repeat; line-height:20px; font-weight:bold; text-align:center\"><span style=\"padding-left:85px; color:green\">Checking...</span></div>");
		$.post(audio_check,"url="+data,function(info,name){
			if(info == "false") {
				hintObj.next().remove();
				hintObj.after("<div style=\"height:20px; margin-right:30px; line-height:20px; font-weight:bold; text-align:center\"><span style=\"padding-left:85px; color:green\">Wrong format</span></div>");
				alert("Sorry, the file that you're trying to upload is of the wrong format.");
			} else {
				addMediaInfo("audio",wrapper.find(".upload"),"images/audio.gif",name,"","","",data,".first",topPlaylist);
				btnEnter.val();
			}
			hintObj.next().remove();
		});
	}
	else alert("Upload failed!");
}


function addMediaByURL(type,where,data) {
	var url,
		obj = where.find(".byURL"),
		boxHtml = obj.html();
	if(type == "video") url = videoUrl_decode;
	if(type == "image" || type == "imageurl" ) url = imageUrl_decode;
	obj.html("<img style=\"margin:20px;margin-left:135px\" src=\"images/loading.gif\" width=\"16\" height=\"16\" />");
	$.post(url,data,function(xml){
		var media = $(xml).find(type=="imageurl"?"image":type);
		media.each(function(i){
			var url = $(this).attr("url"),
				thumb = $(this).attr("thumb"),
				title = $(this).attr("title"),
				keyword = $(this).attr("keyword"),
				description = $(this).attr("description"),
				owner = $(this).attr("ori_owner") || "";
			addMediaInfo(type,where,thumb,title,owner,keyword,description,url,".first");
			obj.html(boxHtml);
			obj.find("input[name='url']").val("");
		});
	})
}

function uploadImage(where,type,id,topPlaylist) {
	 var pars = where.getForm();
	 var mediaUrl; 
	 $.ajaxFileUpload({
		url:file_upload,
		type: 'POST',
		data: pars,
		secureuri:false,
		fileElementId:id,
		dataType: 'json',
		success: function (data)
		{	
			if(data.status != "false") {
				mediaUrl = data.data;
				pars += "&url="+mediaUrl+ "&type=" + type;
				unloadImageInfo(where,pars,topPlaylist);
			}
			else 
			{	
				alert(data.data);
			}
		},
		error:function (e)
        {
          alert("The image that you are trying to upload is larger than our 2 mb file size limit, you can reduce its size by reducing its resolution and/or pixels through photo editing software such as photoshop.");
        }

	 })
}

function unloadImageInfo(where,pars,topPlaylist) {
	$.post(media_add,pars,function(xml){
		var media = $(xml).find("media");
		var title,
			allTitle = media.attr("name"),
			thumb = media.attr("url"),
			id = media.attr("id");
		if(allTitle.length > 18) title = allTitle.substr(0,15) + "...";
		else title = allTitle;
		var objMedia = $("<li mediaId=\""+ id +"\"><div class=\"thumb\"><img title=\""+ allTitle +"\" src=\""+ thumb +"\" /></div><h3><strong>"+ title +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>");
		addToPlaylist(id,topPlaylist,objMedia);			
	});
}


function addMedia() {
	//show upload dialog
	$("#upload").show();
	
	//position of upload dialog
	var winW = document.documentElement.clientWidth || window.innerWidth;
	var winH = document.documentElement.clientHeight || window.innerHeight;
	$("#upload .content").css("left",(winW-$("#upload .content").width())/2);
	$("#upload .content").css("top",(winH-$("#upload .content").height())/2);
	
	//bind event
	$("#upload .close").click(function(){$("#upload").hide();return false});
	$("#btnAddYoutubeVideo").unbind().bind("click",function(){uploadMedia($("#addvideo"),"youtube");return false});
	$("#btnAddAudio").unbind().bind("click",function(){uploadMedia($("#addAudio"),"audio");return false});
//	$("#btnUploadImage").unbind().bind("click",function(){uploadImg($("#addImage"),"uploadPhoto");return false});
	$("#btnAddImage").unbind().bind("click",function(){uploadMedia($("#addImageUrl"),"urlPhoto");return false});
}

function editPlaylist() {
	//show upload dialog
	$("#editPlaylist").show();
	handleManageMedias();
	
	//position of upload dialog
	var winW = document.documentElement.clientWidth || window.innerWidth;
	var winH = document.documentElement.clientHeight || window.innerHeight;
	//$("#editPlaylist .content").css("left",(winW-$("#editPlaylist .content").width())/2);
	//$("#editPlaylist .content").css("top",(winH-$("#editPlaylist .content").height())/2);
	
	//bind event
	$("#editPlaylist .close").click(function(){$("#editPlaylist").hide();return false});

}


function sendSnapPath(filePath) {
	getFla("paints").handleSnapPath(filePath);
}

function handleManageMedias() {
	var data = "roomID="+roomID+"&type=medias";
	$.ajax({
	    type: "POST",
	    url: space_getInfo,
	    data: data,
	    success: function(xml){
			var result = handleMedias(xml);
			if( result.constructor == String) {
				if(result == "") {
					$("#mediaSort").text("You have not added any media to the playlist yet.");
					return false;
				}
				$("#mediaSort").empty();
				$("#mediaSort").append(result);
				delPlaylist();
			}else{
				$("body").dialog({
				title: result.title,
				content: result.content});
			}
		}
		});
}

function handleMedias(xml) {
	if ($(xml).find("error").length != 0) {
		var xmlError = $(xml).find("error");
		var error = {
		title: xmlError.attr("title"),
		content: xmlError.attr("content")
		};
		return error;
	}

	var medias = [];
	var strLi = "";
	$(xml).find("media").each(function(i){
		var media = {};
		media.id = $(this).attr("id");
		wholeName = media.name = $(this).attr("name");
		media.imgUrl = $(this).attr("url");
		media.type = $(this).attr("type");
		medias[i] = media;
    });
	for(var key in medias) {
		if(key.length <= 2) {;
		var id = medias[key].id;
		var name = medias[key].name;
		var imgUrl = medias[key].imgUrl;
		var type = medias[key].type;
		strLi += createMediaElement(id,imgUrl,name,type);
		}
	}
	return strLi;
}

function createMediaElement(id,imgUrl,name,type) {
	if(type=="video") type = "Video";
	if(type=="image") type = "Image";
	if(type=="audio") type = "Audio";
	var whoelName = name;
	if(name.length > 15) name = name.slice(0,12)+"...";
	if(type!=undefined) return "<li  title=\""+ whoelName +"\"  mediaId=\""+ id +"\"><div class=\"thumb\"><img src=\""+ imgUrl +"\" /></div><h3><span class=\"is"+type+"\"></span><strong>"+ name +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>";
	else return "<li  title=\""+ whoelName +"\"  mediaId=\""+ id +"\"><div class=\"thumb\"><img src=\""+ imgUrl +"\" /></div><h3><strong>"+ name +"</strong></h3><div class='tools'><a href='#' class='delete'></a></div></li>";
}

function updateFriendStatus() {
	var wrap = $("#friend .userList");
	$.post(friend_get,function(xml){
		var onlineFriends = $(xml).find("user[status='online']");
		onlineFriends.each(function(i){
			var strRoom = "",
				onlineId = $(this).attr("userID"),
			    onlineObj = wrap.find("li[friendId='"+ onlineId +"']"),
				detailWrap = onlineObj.find(".detailContent dl");
			var rooms = $(this).find("room");
			if(rooms.length != 0) {
				rooms.each(function(i){
					strRoom += 	"<dd><a href=\"/snazl/"+ $(this).attr("id") +"\" target=\"_blank\">" +$(this).attr("name")+ "</a></dd>";
				});
			} else {
				strRoom += 	"<div> &nbsp; </div>";	
			}
			detailWrap.find("dd").remove();
			detailWrap.find("div").remove();
			$(strRoom).appendTo(detailWrap);	
			onlineObj.removeClass("offline");
			onlineObj.clone().prependTo(wrap).find(".invite").unbind().click(function(){
				if($(this).hasClass("disabled")) return false;
				var title = "Invitation Sent:";
				var content = "Your invitation has been sent!";
				var buttons = {" OK " : function(){$("#dialog").remove(); return false}};
				$("body").dialog({title: title,content: content,btn: buttons});
				window.setTimeout(function(){$("#dialog").remove();},2000);
				var pars = "toID="+onlineId+"&roomID="+roomID;
				$.post(sendinstantinvite,pars);
				$(this).addClass("disabled");			
				return false;
			});;
			onlineObj.remove();
		});
	});		
	window.setTimeout(updateFriendStatus,120000);
}

function offFriendInvite() {
	$("#friend .userList li").each(function(i){
		var self = $(this);
		var btn = self.find(".offInvite");
		btn.click(function(){
			var id = self.attr("friendId");	
			var username = self.find(".username a").text();
			var title = "Invite to SnazL";
			var content = "<dl style='margin-left:100px'><dt class='clear'><div class='left w70'>Username:</div><div class='left'><input class='w200' type='text' name='email' value='"+username+"' /></div></dt><dd class='clear'><div class='left w70'>Message:</div><div class='left w200'><textarea name='message' class='w200' /></div></dd></dl>";
			var btn = {
				"Send": function(){
					var message =  $("#dialog textarea[name='message']")[0].value;
					var pars = "toID="+id+"&roomID="+roomID+"&message="+message;
					$.ajax({
						type: "POST",
						url: invitefriendfromspace,
						data: pars,
						dataType: "json",
						success: function(data){
							$("#dialog").remove();
							$("body").dialog({
								title: data.title,
								content: data.content,
								btn:{" OK ":function(){$("#dialog").remove();}}
							});	
						}
					});					
				},
				"Cancel" : function(){$("#dialog").remove(); return false} 
			};
			$("body").dialog({title: title,content: content,btn: btn});
			
		});
		
	});
}

function getfullpageview(url) {
	window.open(url);
	// window.location.href = url;
}

function hideWow() {
	$("#addFavorite").hide();
	showHind("Your friends know you've WOWed this SnazL!");
}

function copy() {
$("#embedCode2").focus();
$("#embedCode").select();
if ($.browser.mozilla) {alert("It's not allowed to copy in firefox");return false}
var code=$("#embedCode")[0].createTextRange();
var yes = code.execCommand('Copy');
if(yes) alert('You have copied the embed code!')
}

function copyUrl() {
$("#url").focus();
$("#url").select();
if ($.browser.mozilla) {alert("It's not allowed to copy in firefox");return false}
var code=$("#url")[0].createTextRange();
code.execCommand('Copy');
alert('You have copied the URL!')
}