var docRoot = "";
//var docRoot = "/_dev";
/*
$(document).ready(function(){
	//tb_init('a.profileMessageThickbox');
	//tb_init('a.uploadPhotoLink');
	
	// Album Sortable list
	$("#placeholderSortable").sortable({
  	placeholder: "album_sortable_placeholder",
    revert: true,
    update: showSerialize
  });
});
*/
function redirect(gotoUrl){
	window.location = gotoUrl;
}
function showBannerLogin(){
	$('#LoginButton').hide();
	$('#BannerLogin').slideDown("slow");
}
function hideBannerLogin(){
	$('#BannerLogin').slideUp("slow", function(){
		$('#LoginButton').show();
	});
}

function checkHeaderPost(maxChar){
	var temp = $('#Header_post').val();
	if(parseInt(temp.length) > parseInt(maxChar)){
		$('#Header_post').val(temp.substring(0,temp.length-1));
		$('#postNumber').html("&nbsp;0&nbsp;");
	}
	else{
		var numberRemain = parseInt(maxChar)-parseInt(temp.length)
		$('#postNumber').html("&nbsp;"+numberRemain+"&nbsp;");
	}
}

function postWYDoing(eleId, para, phrase){
	$('#Conversation_post').html('<img src="'+docRoot+'/images/loading.gif" border="0" width="20" height="20" />');
	
	var wyDoing = $('#'+eleId).val();
	if(wyDoing != phrase){
		para = para+"&val="+wyDoing;
		var response = $.ajax({
			type: "POST",
	  	url: docRoot+"/profile/proc_profile.php",
	  	data: para,
	  	async: true,
	  	success: function(msg){
	  		$('#Conversation_post').html('<input class="post" type="submit" value="Post" name="post" onclick="postWYDoing(\'Header_post\', \'submit=updateProfileWYDoing\', \'What are you doing?\')" />');
	  	}
		}).responseText;
	}
}

function showLogin(){
	if($('#SignupForm').css('display') != "none"){
		//$('.signupForm').css({backgroundColor:'#FFFFCC'});
		$('.signupForm').fadeTo("slow", 0.33, function(){
			$('.signupForm').fadeTo("slow", 1.00);	
		});
	}
	$('#SignupForm').slideDown(1000);
}

function showHiddenBox(div){
	if($('#'+div).css('display') != "none"){
		//$('.signupForm').css({backgroundColor:'#FFFFCC'});
		$('#'+div).fadeTo("slow", 0.33, function(){
			$('#'+div).fadeTo("slow", 1.00);	
		});
	}
	$('#'+div).show(1000);
}
function closeHiddenBox(div){
	$('#'+div).hide(1000);
}
/*
function joinEvent(eleId, masterId){	
	$('#JoinEvent_'+eleId).load('joinEvent.php?id='+eleId+'&mid='+masterId);
}
function unjoinEvent(eleId, masterId){
	$('#JoinEvent_'+eleId).load('joinEvent.php?id='+eleId+'&mid='+masterId+'&act=unjoin');
}*/
function joinEvent(cid, masterId, eleId){	
	//alert(cid+":"+masterId+":"+eleId);
	var response = $.ajax({
		type: "POST",
  	url: 'joinEvent.php',
  	data: 'id='+cid+'&mid='+masterId,
  	async: true,
  	success: function(msg){
  		if(msg != 0){
  			//$('#'+eleId).append(msg);
  			window.location = docRoot+"/calendar/detail.php?id="+masterId;
  		}
  		else{
  			dialog_main_feedback();
  		}
  	}
	}).responseText;
	//$('#JoinEvent_'+eleId).load('joinEvent.php?id='+eleId+'&mid='+masterId);
}
function unjoinEvent(cid, masterId, eleId){	
	//alert(cid+":"+masterId+":"+eleId);
	var response = $.ajax({
		type: "POST",
  	url: 'joinEvent.php',
  	data: 'id='+cid+'&mid='+masterId+'&act=unjoin',
  	async: true,
  	success: function(msg){
  		//alert(msg);
  		if(msg != 0){
  			//$('#'+eleId+'_'+msg).remove();
  			window.location = docRoot+"/calendar/detail.php?id="+masterId;
  		}
  		else{
  			dialog_main_feedback();
  		}
  	}
	}).responseText;
	//$('#JoinEvent_'+eleId).load('joinEvent.php?id='+eleId+'&mid='+masterId);
}

function toggle(eleId){
	$('#'+eleId).toggle();
}

/*########################################
	########## General Functions ###########
	########################################*/

// Country field ID, State Field ID
function checkCountry(CountryFieldID,StateFieldID,stateOption){
	//alert($('#'+CountryFieldID).val()+"HERE");
	if($('#'+CountryFieldID).val() != "US"){
		$('#'+StateFieldID).hide();
		if(stateOption.length > 0)
			$('#'+stateOption).val("0");
	}
	else
		$('#'+StateFieldID).show();
}

function scrollTo(eleId) {
	var targetOffset = $('#'+eleId).offset().top;
	$('html,body').animate({scrollTop: targetOffset}, 500);
}

function ajaxLoad(ele,page,para){
	//alert(ele+' '+page+' '+para);
	$('#'+ele).load(page+'?'+para);
}

function profile_ajaxLoadWithForm(formId,ele,page,callback_ele,callback_page){
	//alert(formId+":"+callback_ele+":"+callback_page);
	var str = $("#"+formId).serialize();
	//alert(str);
	$('#'+ele).load(page+'?'+str, function(){
		//alert(callback_page);
		//$('#'+callback_ele).load(callback_page);	
	});
}

function ajaxLoad_profilePic(ele,page,para){
	showLoading('Profile_upload_response');
	var response = $.ajax({
		type: "POST",
  	url: page,
  	data: para,
  	async: true,
  	success: function(msg){
  		//$('#Profile_pic').load('changeProfilePic.php');	
			$('#tab_profile_pic').load('editProfile.php?action=tabProfilePic&fb='+escape(msg),function(){
				//tb_init('a.profileMessageThickbox');
			});
  	}
	}).responseText;
	/*
	$('#'+ele).load(page+'?'+para,function(){
		$('#Profile').load('changeProfilePic.php?'+para);	
		$('#tab_profile_pic').load('editProfile.php?action=tabProfilePic');
	});*/
}

function ajaxLoad_emotionPic(ele,page,para){
	var response = $.ajax({
		type: "POST",
  	url: page,
  	data: para,
  	async: true,
  	success: function(msg){
			$('#tab_profile_emotion_pic').load('editProfile.php?action=tabEmotionPic&fb='+escape(msg),function(){
				tb_init('a.profileMessageThickbox');
				tb_init('a.uploadPhotoLink');
			});
  	}
	}).responseText;
}

function showLoading(ele){
	$('#'+ele).show();
	$('#'+ele).html('<img src="'+docRoot+'/images/loading.gif" border="0" width="32" height="32" />');
}
function hideLoading(ele){
	$('#'+ele).html('');
}

// This function is for the form field 
// to show the init text
function showInitTextField(eleId, phrase){
	if($('#'+eleId).val() == ""){
		document.getElementById(eleId).value=phrase;
		document.getElementById(eleId).style.color='#999999';
	}
}
// This function is for the form field 
// to hide the init text	
function hideInitTextField(eleId, phrase){
	if($('#'+eleId).val() == phrase){
		document.getElementById(eleId).value='';
		document.getElementById(eleId).style.color='#000000';
	}
}	
// search for url variable
// For example: 
// para = "val1=abc&val2=efg"
// var temp = searchUrlValue(para, 'val2')
// temp will show efg
function searchUrlValue(para, urlIndex){
	var variable = para.split("&");
	for(var i=0; i<variable.length; i++){
		var temp = variable[i].split("=");
		if(temp[0] == urlIndex){
			return temp[1];
		}
	}
}

// general tooltip
// ele = the element that tragger the tooltip. for example, you can put onmouseover="tooltip(this,...)"
// tooltip = the id of the hidden tooltip
// offset_top and offset_left is just the pixel the you want the tooltip locate.
function tooltip(ele,tooltip, offset_top, offset_left){
	var pos = $(ele).position();
	var posY = parseInt(pos.top-offset_top);
	var posX = parseInt(pos.left+offset_left);
	$('#'+tooltip).css('top',posY);
	$('#'+tooltip).css('left',posX);
	
	$('#'+tooltip).show();
	
	$(ele).mouseout(function(){
		$('#'+tooltip).hide();
	});
}

/*########################################*/

/*########################################*/
/*validation*/
function validate_general(arrayVal){
	//alert(arrayVal.length);
	$('#Feedback').hide();
	$('#Feedback').text('');
	var flag=true;
	var feedback="";
	var i=0;
	for (i=0;i<arrayVal.length;i++){
		var fieldVal=$('#'+arrayVal[i]).val();
		//trim white space
		fieldVal = fieldVal.replace(/^\s+|\s+$/g,"");
		if(fieldVal.length==0){
			feedback += "<div class='feedbackContent'>"+arrayVal[i]+" is empty</div>";
			flag=false;
		}
	}
	if(flag){
		return true;
	}
	else{
		$('#Feedback').show();
		$('#Feedback').append("<div class='feedbackTitle'>The following fields are invalid</div>")
		$('#Feedback').append(feedback);
	}
	
	return false;
}

function validate_inbox_compose(to_field,subject,message){
	$('#Feedback').hide();
	$('#Feedback').text('');
	var flag=true;
	var feedback="";
	
	var to=$('#'+to_field).text();
	//trim white space
	to = to.replace(/^\s+|\s+$/g,"");
	
	var s=$('#'+subject).val();
	//trim white space
	s= s.replace(/^\s+|\s+$/g,"");
	
	var m=$('#'+message).val();
	//trim white space
	m = m.replace(/^\s+|\s+$/g,"");
	
	if(to.length==0){
		feedback += "<div class='feedbackContent'>"+to_field+" is empty</div>";
		flag=false;
	}
	if(s.length==0){
		feedback += "<div class='feedbackContent'>"+subject+" is empty</div>";
		flag=false;
	}
	if(m.length==0){
		feedback += "<div class='feedbackContent'>"+message+" is empty</div>";
		flag=false;
	}
	
	if(flag){
		return true;
	}
	else{
		$('#Feedback').show();
		$('#Feedback').append("<div class='feedbackTitle'>The following fields are invalid</div>")
		$('#Feedback').append(feedback);
	}
	
	return false;
}
/*########################################*/

/*########################################*/
/*Setting Function*/
function changeMyAccount(formId,loc){
	// if there is ref location
	if(loc.length > 0){
		addition = "?ref_loc="+loc;
	}
	else{
		addition="";
	}

	var str = $('#'+formId).serialize();
	
	if(formId=="nameForm")
		var act = "changeName";
	else if(formId=="emailForm")
		var act = "changeEmail";
	else if(formId=="passwordForm")
		var act = "changePassword";
		
	$.ajax({
		type: "POST",
		url: docRoot+"/setting/proc.php",
		data: str+"&action="+act,
		success: function(msg){
			//alert( "Data Saved: " + msg );
			// If error
			if(msg){
				$('#myAccountFeedback').html('<span class="err">'+msg+'</span>');
			}
			else{
				if(formId=="passwordForm")
					window.location = docRoot+"/account/logout.php"+addition;
				else if(formId=="emailForm"){
					dialog_main_feedback("We are going to send you an email within a few minutes. Please check your email and follow the instruction to complete the change email process.");
				}
				else
					window.location = docRoot+"/setting/myAccount.php"+addition;
			}
		}
	});
}

/*########################################*/

/*########################################*/
/*Profile Function*/

function checkSearchPeople(eleId, phrase){
	if($('#'+eleId).val() == "" || $('#'+eleId).val() == phrase){
		document.getElementById(eleId).value=phrase;
		return false;
	}
	else
		return true;
}

function ajaxLoad_profileMessage(ele,page,para){
	var friend_id = searchUrlValue(para,'to');
	//var tempValue=new Date();

	var message = $('#ProfileMessage').val();
	var emotionList = $('#EmotionFace').val();
	var emotion = $('#emotionList_'+emotionList).val();
	
	if(message.length > 0){
		/*$('div.Profile_date_temp').show();
		//$('#Profile_message').prepend(message);
		$.get(page+"?"+para+"&message="+message+"&emotion="+emotion,
			function(data){
				$('#Profile_message').prepend(data);
				$('#ProfileMessage').val("");
				tb_init('a.profileMessageThickbox');
			}
		);
		*/
		
		$('#'+ele).html('<div style="height: 500px;text-align:center;"><img src="'+docRoot+'/images/loading.gif" border="0" width="32" height="32" /></div>');
		var response = $.ajax({
			type: "POST",
	  	url: page,
	  	data: para+"&message="+message+"&emotion="+emotion,
	  	async: true,
	  	success: function(msg){
	  		//alert(msg);
	  		$('#ProfileMessage').val("");
	  		if(friend_id!=undefined && friend_id.length > 0)
	  			$('#'+ele).load(docRoot+'/profile/activity/?action=profileMessage&id='+friend_id+'&m=viewFriend&nav=messages&fb='+escape(msg),function(){
	  				//tb_init('a.profileMessageThickbox');	
	  			});
	  		else
					$('#'+ele).load(docRoot+'/profile/activity/?action=profileMessage&nav=messages&fb='+escape(msg),function(){
						//tb_init('a.profileMessageThickbox');
					});
	  	}
		}).responseText;
	}
}

function ajaxLoad_deleteProfileMessage(ele,page,para,fid){
	var tempValue=new Date();
	
	$('#'+ele).html('<div style="height: 500px;text-align:center"><img src="/images/loading.gif" border="0" width="32" height="32" /></div>');
	var response = $.ajax({
		type: "POST",
	 	url: page,
	 	data: para,
	 	async: true,
	 	success: function(msg){
	 		$('#ProfileMessage').val("");
			$('#'+ele).load(docRoot+'/profile/?id='+fid+'&m=viewFriend&action=profileMessage&fb='+escape(msg)+'&t='+escape(tempValue),function(){
				tb_init('a.profileMessageThickbox');
			});
	 	}
	}).responseText;
}

function showProfileMessageControl(ele){
	$('#'+ele).show();
}
function hideProfileMessageControl(ele){
	$('#'+ele).hide();
}

// Profile Photo Upload result
function showProfilePicResult(ele, result) {
	//$('#'+ele).html(result);
	$('#tab_profile_pic').load('editProfile.php?action=tabProfilePic&fb='+escape(result), function(){
		//tb_init('a.profileMessageThickbox');
	});
}
// School Photo Upload result
function showSchoolPicResult(act, sid, mode, result) {
	/*alert(act);
	alert(sid);
	alert(result);*/
	$('#School_upload_photo').val('');
	$('#School_upload_response').html('');
	if(act=="edit" || mode=='refresh'){
		window.location = docRoot+"/schools/detail.php?id="+sid;
	}
	else{
		$('#tab_school_photo').load(docRoot+"/schools/tab_photo.php?id="+sid);
	}
	$('#dialog_school_uploadPhoto').dialog('close');
}

// Calendar Photo Upload result
function showCalendarPicResult(cid, result) {
	/*alert(act);
	alert(sid);
	alert(result);*/
	$('#Calendar_upload_photo').val('');
	$('#Calendar_upload_response').html('');
	//alert(result);
	// if success
	if(result == 1){
		window.location = docRoot+"/calendar/detail.php?id="+cid;
		$('#dialog_calendar_addPhoto').dialog('close');
	}
	else{
		$('#dialog_calendar_addPhoto').dialog('close');
		dialog_main_feedback(result);
	}
	
}

function showEmotionPicResult(ele, result) {
	//$('#'+ele).html(result);
	$('#tab_profile_emotion_pic').load('editProfile.php?action=tabEmotionPic&fb='+escape(result), function(){
		tb_init('a.profileMessageThickbox');
		tb_init('a.thickbox');
	});
}

function changeEmotionFace(sizeOfArray){
	//var emotionVal = $('#EmotionFace').val()-1;
	var emotionVal = $('#EmotionFace').val();
	//alert(emotionVal);
	var i=0;
	for (i=0;i<=sizeOfArray;i++){
		if(emotionVal == i)
			document.getElementById('EmotionFaceImage_'+i).style.display="block";
		else
			document.getElementById('EmotionFaceImage_'+i).style.display="none";
	}
	//$('#EmotionFaceImage').text('<img src="{$UPLOAD_PHOTO_LINK}/{$EMOTION_FACE['+emotionVal+'].file_name}_ic{$EMOTION_FACE['+emotionVal+'].extension}" border="0" />');
}

// Calendar Event
function showEventHiddenBox(div){
	if($('#'+div).css('display') == "none"){
		$('#'+div).slideDown(1000);
	}
}
function closeEventHiddenBox(div){
	$('#'+div).slideUp(1000);
}

// Profile Feed
function replyFeed(feedId){
	var reply = $('#textarea_'+feedId).val();
	if(reply.length > 0){
		$.ajax({
			type: "POST",
		 	url: docRoot+"/profile/proc_feed.php",
		 	data: 'id='+feedId+'&reply='+reply,
		 	success: function(msg){
		 		//alert( "Data Saved: " + msg );
		 		// If error
		 		if(msg == '0'){
					//$('#KT_Feedback').html('<span class="err">There is an error. Please try again.</span>');
					dialog_main_feedback();
				}
				else{
					//alert(msg);
					//append the reply into DOM
					$("#Reply_"+feedId).append(msg);
					$("#textarea_"+feedId).val("");
				}
			}
	 });
	}
}

/*########################################*/


/* Album Functions */
/*
function showSerialize(){
    var temp = $('#placeholderSortable').sortable('serialize');
    // This tempTimestamp is important for IE by forcing it IE to update content
    var tempTimestamp = parseInt(new Date().getTime().toString().substring(0, 10));
    $('#Sortable_message').load(docRoot+'/albums/proc.php?submit=UpdateOrder&'+temp+'&t='+tempTimestamp);
}*/

function addAlbumComment(){
	var str = $('#addCommentForm').serialize();
	//alert(str);
	var comment = $('#addComment_textarea').val();
	if(comment){
		$.ajax({
			type: "POST",
		 	url: docRoot+"/albums/addComment.php",
		 	data: str,
		 	success: function(msg){
		 		//alert( "Data Saved: " + msg );
		 		// If error
		 		if(msg == '0'){
					$('#addCommentFeedback').html('<span class="err">There is an error. Please try again.</span>');
				}
				else{
					//append the comment into DOM
					$("#Album_comment").append("<div id='Album_tempFeedback' class='ajaxFeedback'>Comment has been added</div>");
					$("#Album_comment").append(msg);
					$("#addComment_textarea").val("");
					$("#addCommentFeedback").val("");
				}
			}
	 });
	}
}

function album_delete(tid){
	$.ajax({
		type: "POST",
	 	url: docRoot+"/albums/removeTag.php",
	 	data: 'id='+tid,
	 	success: function(msg){
	 		//alert( "Data Saved: " + msg );
	 		// If error
	 		if(msg == '0'){
				dialog_main_feedback();
			}
			else{
				$('[id=Photo_tag_inside_'+tid+']').remove();
			}
		}
	});
}

/*#####END ALBUM FUNCTIONS ###############*/

/* Video Functions */
function loadVideo(){
	$('#VideoBox').html('<div style="width: 400px;text-align:center;"><img src="'+docRoot+'/images/loading.gif" border="0" width="32" height="32" /></div>');
	var video = $('#VideoUrl').val();
	if(video){
		try{
			var temp = video.split('v=');
			temp = temp[1].split('&');
			temp = temp[0].replace('#','');
			//alert(temp);
			var videoId = temp;
			// check the video id
			//$('#VideoThumbnail').val(val.thumbnail);
			$('#VideoLinkID').val(videoId);
			var videoObj =  '<object width="425" height="344">';
			videoObj += 	'<param name="movie" value="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1&autoplay=1"></param>';
			videoObj += 	'<param name="allowFullScreen" value="true"></param>';
			videoObj += 	'<param name="allowscriptaccess" value="always"></param>';
			videoObj += 	'<embed src="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>';
			videoObj += '</object>';
			$('#VideoBox').html(videoObj);
			$('#Preview_video').show();
			/*
			$.getJSON(docRoot+"/classes/checkYouTube.php",{ vid: videoId }, function(val){
				if(val.feedback=="fail"){
					$('#VideoTitle').val("");
					$('#VideoDescription').val("");
					$('#VideoLinkID').val("");
					$('#VideoBox').html("Can not find this YouTube Video. Please make sure the link is correct and try again.");
				}
				else{
					$('#VideoTitle').val(val.title);
					var desc = val.description;
					desc = desc.replace(/<br\/>/g,"\n\r");
					$('#VideoDescription').val(desc);
					$('#VideoThumbnail').val(val.thumbnail);
					$('#VideoLinkID').val(videoId);
					var videoObj =  '<object width="425" height="344">';
				    videoObj += 	'<param name="movie" value="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1&autoplay=1"></param>';
						videoObj += 	'<param name="allowFullScreen" value="true"></param>';
						videoObj += 	'<param name="allowscriptaccess" value="always"></param>';
						videoObj += 	'<embed src="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>';
						videoObj += '</object>';
					$('#VideoBox').html(videoObj);
				}
			});
			*/
		}
		catch(err){
			$('#VideoBox').html("Can not find this YouTube Video. Please make sure the link is correct and try again.");
			return false;
		}
	}
	else{
		$('#VideoBox').html("Can not find this YouTube Video. Please make sure the link is correct and try again.");
		return false;
	}
}

function addVideoComment(){
	var str = $('#addCommentForm').serialize();
	var comment = $('#addComment_textarea').val();
	if(comment){
		$.ajax({
			type: "POST",
		 	url: docRoot+"/videos/addComment.php",
		 	data: str,
		 	success: function(msg){
		 		//alert( "Data Saved: " + msg );
		 		// If error
		 		if(msg == '0'){
					$('#addCommentFeedback').html('<span class="err">There is an error. Please try again.</span>');
				}
				else{
					//append the comment into DOM
					$("#Video_comment").append("<div id='Video_tempFeedback' class='ajaxFeedback'>Comment has been added</div>");
					$("#Video_comment").append(msg);
					$("#addComment_textarea").val("");
					$("#addCommentFeedback").val("");
				}
			}
	 });
	}
}
/*#####END VIDEO FUNCTIONS ###############*/

/*######## SCHOOL FUNCTIONS ###############*/
function addSchoolComment(){
	var str = $('#addCommentForm').serialize();
	//alert(str);
	
	var comment = $('#addComment_textarea').val();
	if(comment){
		$.ajax({
			type: "POST",
		 	url: docRoot+"/schools/addComment.php",
		 	data: str,
		 	success: function(msg){
		 		//alert( "Data Saved: " + msg );
		 		// If error
		 		if(msg == '0'){
					$('#addCommentFeedback').html('<span class="err">There is an error. Please try again.</span>');
				}
				else{
					//append the comment into DOM
					//alert($('#School_review_form').html());
					$('#School_review_form').hide();
					$("#School_comment_section").show();
					$("#School_comment").append("<div id='School_tempFeedback' class='ajaxFeedback'>Comment has been added</div>");
					$("#School_comment").append(msg);
					$("#addComment_textarea").val("");
					$("#addComment_anonymous").attr('checked', false);
					$("#current_rating").css('width','0');
					$("#addCommentFeedback").val("");
				}
			}
	 });
	}
}

/*#####END SCHOOL FUNCTIONS ###############*/

/*######## INBOX FUNCTIONS ###############*/
function inbox_mark_unread(master_inbox_id){
	//alert(inbox_id);
	var response = $.ajax({
		type: "POST",
	 	url: docRoot+'/inbox/proc_compose.php',
	 	data: 'submit=Mark As Unread&master_inbox_id='+master_inbox_id,
	 	async: true,
	 	success: function(msg){
	 		//alert(msg);
	 		if(msg=="true"){
	 			window.location=docRoot+"/inbox/index.php";
	 		}
	 	}
	}).responseText;
}

function inbox_selectToFriend(userId,fullname,pic){
	if($('#friend_'+userId).text()==""){
		// Append to the dialog
		$('#SelectedFriend').append('<span id="friend_'+userId+'" style="padding:3px; float:left;"><table cellspacing="0" cellpadding="0" border="0"><tr><td><img src="'+pic+'" border="0" title="'+fullname+'" /></td></tr><tr><td><span class="link" onclick="inbox_deleteToFriend(\''+userId+'\')">Delete</span></td></tr></table></span>');
		//Append to the compose main page
		$('#To_field').append('<span id="to_field_friend_'+userId+'" style="padding:3px; float:left;"><table cellspacing="0" cellpadding="0" border="0"><tr><td><img src="'+pic+'" border="0" title="'+fullname+'" /></td></tr><tr><td><span class="link" onclick="inbox_deleteToFriend(\''+userId+'\')">Delete</span></td></tr></table><input type="hidden" name="selectedFriend[]" value="'+userId+'" /></span>');
	}
	else{
		alert(fullname+" is alreay in the list.");
	}
}
function inbox_deleteToFriend(eleId) {
	$('#friend_'+eleId).remove();
	$('#to_field_friend_'+eleId).remove();
}
function inbox_search_frield(eleId){
	showLoading('dialog_inbox_to_field_content');
	var val = $('#'+eleId).val();
	$('#dialog_inbox_to_field_content').load(docRoot+'/inbox/dialog_to_field.php?search='+val);
}
/*######## END INBOX FUNCTIONS ###########*/

/*######## FORUM FUNCTIONS ###############*/

/*datalist*/
function datalist_forum_image(pathUrl){
	showLoading('dialog_forum_image_user_photo_inside');
	$('#dialog_forum_image_user_photo').load(pathUrl);
}

/*Reply to*/
function forum_showReplyTo(reply_id){
	//alert(reply_id);
	$.ajax({
		type: "POST",
		url: docRoot+"/forum/viewReplyTo.php",
		data: "id="+reply_id,
		success: function(msg){
			//alert( "Data Saved: " + msg );
			//append the reply to list into DOM
			$('[id=reply_'+reply_id+']').append(msg);
		}
	});
}

/* Email Notification */
function forumEmailNotification(fid,act){
	//alert(fid+":"+act);
	$('#forum_email_loading').show();
	$('#getEmail').hide();
	$('#stopEmail').hide();
	if(act=="stopEmail"){
		$.ajax({
			type: "POST",
			url: docRoot+"/forum/emailNotification.php",
			data: "id="+fid+"&act="+act,
			success: function(msg){
				if(msg==0){
					alert('There is an error. Please try again later');
				}
				else{
					//$('#forumEmailNotification').html('<span class="link" id="forumEmailNotification" onclick="forumEmailNotification(\'getEmail\')">Get Email Notification From This Post</span>');
					$('#forum_email_loading').hide();
					$('#getEmail').show();
					$('#stopEmail').hide();
				}
			}
		});
	}
	else{
		$.ajax({
			type: "POST",
			url: docRoot+"/forum/emailNotification.php",
			data: "id="+fid+"&act="+act,
			success: function(msg){
				if(msg==0){
					alert('There is an error. Please try again later');
				}
				else{
					//$('#forumEmailNotification').html('<span class="link" id="forumEmailNotification" onclick="forumEmailNotification(\'stopEmail\')">Stop Email Notification From This Post</span>');
					$('#forum_email_loading').hide();
					$('#getEmail').hide();
					$('#stopEmail').show();
				}
			}
		});
	}
}

/*Posting Form*/
function addTag(openTag, closeTag){		
	var ta = document.Form1.post;
	var str = ta.value;

	// Code for IE
	if (document.selection){
		ta.focus();
		var sel = document.selection.createRange();
		var start = findStartPositionForIE(ta);
		var countText = sel.text.length;
		if(openTag == 'none')
    	sel.text = sel.text;
    else
			sel.text = openTag + sel.text + closeTag;
	}
	// Code for Mozilla Firefox
  else{
		var len = ta.value.length;
	  var start = ta.selectionStart;
		var end = ta.selectionEnd;
		
    var sel = ta.value.substring(start, end);
    var countText = sel.length;
    if(openTag == 'none')
    	var rep = sel;
    else
			var rep = openTag + sel + closeTag;
    ta.value =  ta.value.substring(0,start) + rep + ta.value.substring(end,len);
	}
	
	//Set the curor back into the tag.
	//if(countText < 1)
	var fullPosLength = start+openTag.length+sel.length+closeTag.length;
	if(sel.length > 0)
		setCaretPosition(fullPosLength);
	else
		setCaretPosition(start+openTag.length);
	ta.focus();
}

function addTagWithEqual(openTag, closeTag){
	if(openTag == '[size]'){
		newTag = editSelectedTextSize();
		
		if(newTag == null)
			addTag('none','none');
		else{
			addTag(newTag, closeTag);
		}
	}
}

function findStartPositionForIE(ele){
	var range = document.selection.createRange().duplicate();
	var pos;			
	var stored_range = range.duplicate();
	stored_range.moveToElementText(ele);
	stored_range.setEndPoint( 'EndToEnd', range );
	pos = stored_range.text.length - range.text.length;
	return pos;
}
	
function setCaretPosition(caretPos) {
	var ta = document.Form1.post;
  if(ta != null) {
  	if(ta.createTextRange) {
    	var range = ta.createTextRange();
      range.move('character', caretPos);
      range.select();
    }
    else {
    	if(ta.selectionStart) {
      	ta.focus();
        ta.setSelectionRange(caretPos, caretPos);
      }
      else
        ta.focus();
    }
  }
}

function smilies(face){
	var ta = document.Form1.post;

	// Code for IE
	if (document.selection){
		ta.focus();
		var start = findStartPositionForIE(ta);
		var sel = document.selection.createRange();
		sel.text = face;
	}
	// Code for Mozilla Firefox
  else{
  	var start = ta.selectionStart;
		var len = ta.value.length;
	  var start = ta.selectionStart;
		var end = ta.selectionEnd;
		
		var rep = face;
    ta.value =  ta.value.substring(0,start) + rep + ta.value.substring(end,len);
	}
	setCaretPosition(start+face.length);
	ta.focus();
}

	function editSelectedTextSize() {
		fontVal = document.Form1.fontSize.value;
		if(fontVal != 'fontNormal'){
			document.Form1.fontSize.value = "fontNormal";
			return '[size='+fontVal+']';
		}
		else
			return null;
	}
	/*
	function editSelectedTextColor() {
		fontVal = document.Form1.fontColor.value;
		if(fontVal != '#000000'){
			document.Form1.fontColor.value = "#000000";
			return '[color='+fontVal+']';
		}
		else
			return null;
	}*/
	
	function showOrHideToolbox(start, end){
		if(start != end)
			document.getElementById('Toolbox').style.display="none";
	}
	
	function showInstruction(val){
		document.getElementById('buttonInstruction').innerHTML = val;
	}
	function emptyInstruction(){
		document.getElementById('buttonInstruction').innerHTML = "";
	}
	
//##############################

var selectButton = "";
function showToolbox(ele){
	var toolbox = document.getElementById('Toolbox');
	if(toolbox.style.display == "none")
		toolbox.style.display = "block";
	else{
		if(selectButton == ele)
			toolbox.style.display = "none";
	}
	if(selectButton != ele)
		selectButton = ele;
	
	var posx=findPosX(document.getElementById('Editor'));
	var posy=findPosY(document.getElementById('Editor'));
	toolbox.style.top=posy+62;
	if(ele=='image'){
		toolbox.style.left=posx+102;
		var string='<br/><br/><table cellspacing="0" align="center" width="90%" class="toolbox"><tr><td>Please type in the url for the image.</td></tr><tr><td><input id="TextImage" type="text" name="url" /></td></tr><tr><td><input type="submit" value="Submit" onclick="setText(\'image\');return false;" />&nbsp;&nbsp;<input type="submit" value="Cancel" onclick="cancelToolbox(); return false;" /></td></tr></table>';
	}
	else if(ele=='url'){
		toolbox.style.left=posx+155;
		var string='<br/><br/><table cellspacing="0" align="center" width="90%" class="toolbox"><tr><td>Please type in the url.</td></tr><tr><td><input id="TextUrl" type="text" name="url" /></td></tr><tr><td><input type="submit" value="Submit" onclick="setText(\'url\');return false;	" />&nbsp;&nbsp;<input type="submit" value="Cancel" onclick="cancelToolbox(); return false;" /></td></tr></table>';
	}
	toolbox.innerHTML=string;
	
}	
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
  
  function setText(typeVal){
  	var ta = document.Form1.post;
  	if (document.selection) {
			var range = document.selection.createRange().duplicate();
			if (range.parentElement() == ta){
				var pos;
				
				var stored_range = range.duplicate();
				stored_range.moveToElementText( ta );
				stored_range.setEndPoint( 'EndToEnd', range );
				pos = stored_range.text.length - range.text.length;
				
				var selectionStart = pos;
				var selectionEnd = pos + range.text.length;
				
				var firstPart = ta.value.substring(0,selectionStart);
				var lastPart = ta.value.substring(selectionEnd,ta.value.length);
			}
		}
		else if (ta.selectionStart){
			var firstPart = ta.value.substring(0,ta.selectionStart);
			var lastPart = ta.value.substring(ta.selectionEnd,ta.value.length);
		}
		else if (ta.selectionStart == '0'){
			var firstPart = '';
			var lastPart = ta.value.substring(ta.selectionEnd,ta.value.length);
		}
  	if(typeVal=="image"){
			var textVal = document.getElementById('TextImage').value;
			addString = "[img]"+textVal+"[/img]"
			ta.value = firstPart+addString+lastPart;
  	}
  	else if(typeVal=="url"){
  		var firstPart = ta.value.substring(0,ta.selectionStart);
			var lastPart = ta.value.substring(ta.selectionEnd,ta.value.length);
			var textVal = document.getElementById('TextUrl').value;
			addString = "[url]"+textVal+"[/url]"
			ta.value = firstPart+addString+lastPart;
  	}
  }
  
  function selectForumImage(picUrl){
  	$('#TextImage').val(picUrl);
  }
  
  function cancelToolbox(){
  	document.getElementById('Toolbox').style.display="none";
  }
/*############# END FORUM FUNCTIONS ################*////
