/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */



var server = '';



var posSticky;
var gift = false;
var favoptions = { dataType: 'xml',
					beforeSubmit: function(formData, jqForm, options) {
						if($('#usCurrent').val() == null) {
							var url = "main/login?type=blip&height=170&width=320";
							var t = '<a id="blipLogin" href="#">Đăng nhập</a>&nbsp;|&nbsp;<a id="blipRegister" href="#">Đăng ký</a>';//null;//this.title || this.name || null;
							tb_show(t,url,"Blipping");
							return false;
						}
						
					},
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
												
												//add in playlist 1
												updatePlaylist(1)
											  }
					 };

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
					   							var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
												//minus in playlist 1
												updatePlaylist(0);
												if($('#showfavorites').html()) {
													temp = fav.split('-');
													notice_id = temp[1];
													$('#notice-' + notice_id).remove();
													
												}
											  }
					 };

					 

function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

						 
					 
$(document).ready(function(){
	var pagePublic = $('#public').html();
	var pagePersonal = $('#all').html();
	if(pagePublic || pagePersonal){
		setInterval("getNewNotice()", 10000);
	}
	var usCurr = $('#usCurrent').val();
	if(usCurr && $('#usCurrent').val() != '') {
		setInterval("checkNotify()", 60000);
	}
	
	$('.notiOff').click(
		function() {
			$('#closebutton').click();
		}
	);
	//notification
	/*
	if($('#notifyContent') && $('#notify') && $('#closebutton')) {
		$('#notifyContent').notificationmsg({period: 100000});
	    $('#notify').click(onClick);
	    $('#closebutton').click(function(){ $('#notifyContent').notificationmsg('hide'); });
    }  */
    if ($.browser.version != '6.0') startNotify();     
            
	$('.control-panel-wrapper2').hide("slow");
	//when click favor/disfavor at footer
	
	$('#fav').click(
		function() {
			var fav_footer = $('#fav_footer').val();
			var temp = fav_footer.split('-');
			var status = temp[0];
			var id = temp[1];
			var id_submit = '#' + status + '-submit-' + id;
			$(id_submit).submit();
			if(status == 'favor') {
				status = 'disfavor';
			} else {
				status = 'favor';
			}
			
			fav_footer = status + '-' + id;
			$('#fav_footer').val(fav_footer); 
			
			
		}
	);
	
	// count character on keyup
	function counter(event){
		var maxLength = 140;
		var currentLength = $("#notice_data-text").val().length;
		var remaining = maxLength - currentLength;
		var counter = $("#notice_text-count");
		counter.text(remaining);

		if (remaining <= 0) {
			$("#form_notice").addClass("warning");
		} else {
			$("#form_notice").removeClass("warning");
		}
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}
	function submitonreturnFavor(event) {
		//$("form[id^=favor]").submit();
		//event.preventDefault();
		//event.stopPropagation();
		//return false;
	}
	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		$("#notice_data-text").bind("keydown", submitonreturn);

		// run once in case there's something in there
		counter();

		// set the focus
		$("#notice_data-text").focus();
	}

	// XXX: refactor this code

	

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };

	

	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
											   updateFavorite(1);
											   //cal send mail
											   var temp = form_unsubscribe_id.split("-");
											   var other_id = temp[1];
											   send_to_subscribe('subscribe',other_id);
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
												 updateFavorite(0);
											   }
					  };

	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);

	var PostNotice = { dataType: 'xml',
					   beforeSubmit: function() { 
					   	if($('#usCurrent').val() == null) {
									var url = "main/login?type=blip&height=170&width=320";
									var t = '<a id="blipLogin" href="#">Đăng nhập</a>&nbsp;|&nbsp;<a id="blipRegister" href="#">Đăng ký</a>';//null;//this.title || this.name || null;
									tb_show(t,url,"Blipping");
									//return false;
						}
						if ($("#notice_data-text").get(0).value.length == 0 || $("#notice_data-text").get(0).value.length > 140) {
																				$("#form_notice").addClass("warning");
																				$("#blip-alert").removeAttr('style');
																				$("#blip-alert").html('Bạn đã gõ quá 140 ký tự. Vui lòng sửa lại!');
																				return false;
																		   }
																		  
																		   $("#notice_action-submit").attr("disabled", "disabled");
																		   $("#notice_action-submit").addClass("disabled");
																		   $('#blipbox').hide();
																		   $('#searchbox').show();
																		   $('#statusResults').hide();
																		  
																		   return true;
												 						 },
					   success: function(xml) {	
					   	
					   						   	if($('#usCurrent').val()==null) {
												   		window.location = server +'?auto=1';	
												   	} else {
					   								
					   								closeSearchForm();
					   								//var temp = $(xml).find("input[id=minh]");
					   								//alert(temp.val());
					   								
					   								var newNotice = $("li", xml).get(0);
					   								
					   								var newNoticeId = $(newNotice).attr("id");
					   								
					   								var temp = newNoticeId.split('-');
					   								if(pagePublic) {
														if(temp[1] != '') {
															$('#publicLatest').val(temp[1]);
														}
													} else if (pagePersonal) {
														if(temp[1] != '') {
															$('#personalLatest').val(temp[1]);
														}
													}
													//alert($('#notices_primary .notices li[class*=sticky]').html());
													if(($('body').attr('id')=='public')&&($('#notices_primary .notices li[class*=sticky]').html())){
					   									$("#notices_primary .notices li:nth(0)").after(document._importNode($("li", xml).get(0), true));
													}else {
														$("#notices_primary .notices").prepend(document._importNode($("li", xml).get(0), true));
													}
													$("#notice_data-text").val("");
													counter();
													$("#notices_primary .notice:first").css({display:"none"});
													$("#notices_primary .notice:first").fadeIn(2500);
													
													$("form.form_favor").ajaxForm(favoptions);
													$("form.form_disfavor").ajaxForm(disoptions);
													$("form.form_favor").each(addAjaxHidden);
													$("form.form_disfavor").each(addAjaxHidden);
													
													
											
													$("#notice_action-submit").removeAttr("disabled");
													$("#notice_action-submit").removeClass("disabled");
													//send to reply
													
													send_to_reply('reply');
													//send to reblip
													
													if(reblip_id != null) {
														send_to_reblip("reblip",reblip_id);
														
													}
													var url = $("#s_url").val();
													var title = $("#s_title").val();
													var artist = $("#s_artist").val();
													var reblip_id = $('#notice_in-reply-to').val();
													
													//MemberBlipSame(url);
													//playList.unshift();
													if(($('body').attr('id')=='public')&&($('#notices_primary .notices li[class*=sticky]').html())){
														playList.splice(1,0,new Array(artist,title,url));
													} else {
														playList.unshift(new Array(artist,title,url));
													}
													
													/*tmpplaylist = playList[0];
													playList[0] = playList[1];
													playList[1] = tmpplaylist;*/
													//increase notice
													if($('#pageUser').html() == $('#usCurrent').val() ) {
														var countProfileNotice = $('#countProfileNotice').html();
														countProfileNotice -= 0;
														countProfileNotice++;
														$('#countProfileNotice').html(countProfileNotice);
													}
														
													//getStatusPlayer('playblip');
													NoticeHover();
													NoticeReply();
													NoticeGift();
													//getNewNotice();
													if(gift == false) {
														getStatusPlayer('playblip','');
													} else {
														getStatusPlayer('','');
														gift = false;
														
													}
													//getNewNotice();
													//Props();
												   	}
													
					   		}
					   };
	
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);
	
    NoticeHover();
    NoticeReply();
    NoticeGift();
    Props();
    
});

function close() {
	$('#blipbox').hide();
	$('#searchbox').show();
	$('#form_mp3').show();
	$('#direct_music').val()
	if($('#notice_in-reply-to').val() == '' && $('#direct_music').val() =="") {
		$('#statusResults').show();
		$('#searchResults').show();
	}
	//$('#memberBlipSame').hide();
	//closeSearchForm();
}
function closeMemberBlipSame() {
	$('#memberBlipSame').hide();
	if($('#searchResults').html()!='') {
		$('#statusResults').show();
		$('#searchResults').show();
	}
}
function NoticeHover() {
    $("#content .notice").hover(
        function () {
            $(this).addClass('over');
        },
        function () {
            $(this).removeClass('over');
        }
    );
    $('.notices li.notice').removeClass('alter');
 	$('.notices li.notice:even').addClass('alter');
}

function MemberBlipSame(url) {
	$.ajax({
		   type: "POST",
		   url: server + "/memberblipsame",
		   data: 'url=' + url,
		   success: function(msg){
		   	if(msg != "") {
		   		$('#memberBlipSame').show("slow");
		   		$('#memberBlipSame').html(msg);
		   	}
		   }
		 });
	 
	return false;
	
}


function hideAlert() {
	$('.control-panel-wrapper2').slideUp("slow");
}

function Props() {
		
		$('#content .notice').each(function() {
			var notice = $(this);
			$('.notice_props', $(this)).click(function() {
				if($('#usCurrent').val() == null) {
					var url = "main/login?type=blip&height=170&width=320";
					var t = '<a id="blipLogin" href="#">Đăng nhập</a>&nbsp;|&nbsp;<a id="blipRegister" href="#">Đăng ký</a>';//null;//this.title || this.name || null;
					tb_show(t,url,"Blipping");
					return false;
					
				}
				
				var id = $('.notice_id', notice).text();
				 
				if($('li[id=notice-' + id + '] dl[class=notice_props] a').attr('class') == 'active') {
					return false;
				}
				
				var nickname = ($('.author .nickname', notice).length > 0) ? $('.author .nickname', notice) : $('.author .nickname');
                
                var pageUser = $('#pageUser').html();
                $.ajax({
						   type: "POST",
						   url: server + "/"+nickname.html()+"/addprops",
						   data: 'id=' + id + '&pageUser=' + pageUser,
						   success: function(msg){
						   	if(msg != '') {
						   		if(msg == 'error') {
						   			//alert('Ban khong the tang props cho chinh ban');
						   		} else {
							   		var temp = msg.split(":");
							   		
							   		if(temp[0] == 'error') {
							   			$('#yougivprops').html('<font color="#FF0000">Bạn không thể tặng quá 3 sao cho một thành viên trong 1 ngày!</font>');
								   		$('.control-panel-wrapper2').slideDown("slow",function() { 
								   			setTimeout("hideAlert();",2000);
								   		});
							   		} else {
							   			$('li[id=notice-' + id + '] dl[class=notice_props] a').addClass('active');
										$('li[id=notice-' + id + '] dl[class=notice_props] a').attr('title','Bạn đã tặng sao cho bài hát này');
										$('li[id=notice-' + id + '] dl[class=notice_props] a').removeAttr('href');
								   		$('#showprops').html(temp[0]);
								   		$('#props_receive').html(temp[1]);
								   		$('#yougivprops').html('Bạn đã tặng một sao cho ' + nickname.html());
								   		$('.control-panel-wrapper2').slideDown("slow",function() { 
								   			setTimeout("hideAlert();",2000);
								   		});							   		
								   		send_to_props('props',nickname.html(),id);
							   		}
						   		}
						   	} else {
						   		//alert('Ban khong the tang ' + nickname.html() + ' 1 props');
						   	}
						   	
						   	//alert(msg);
						   }
						 });
                
                return false;
            });
        });
    
}

function NoticeReply() {
		
	
	if ($('#notice_data-text').length > 0) {
		
        $('#content .notice').each(function() {
            var notice = $(this);
            $('.notice_reply', $(this)).click(function() {
                //var nickname = ($('.author .nickname', notice).length > 0) ? $('.author .nickname', notice) : $('.author .nickname');
                //NoticeReplySet(nickname.text(), $('.notice_id', notice).text());
                //Update by ITFS
                randomText();
               if($('#usCurrent').val() == null) {
			
					var url = "main/login?type=blip&height=170&width=320";
					var t = '<a id="blipLogin" href="#">Đăng nhập</a>&nbsp;|&nbsp;<a id="blipRegister" href="#">Đăng ký</a>';//null;//this.title || this.name || null;
					tb_show(t,url,"Blipping");
					return false;
				}
               
                var content = $('.ct-content',notice).val();
                //content = content.replace(/<a href="/,'');
				//content = content.replace(/" class="extlink">--&gt;&nbsp;liên kết<\/a>/,'');              
			    content += ' ';
              
                var title = $('.ct-title',notice).text();
                var artist = $('.ct-artist',notice).text();
                var url = $('.ct-url',notice).val();
                $('#blipbox').show();
				$('#searchResults').hide();
				$('#searchbox').hide();
                $("#frm-artist").text(artist);
                $("#frm-title").text(title);
                $("#s_title").val(title);
                $("#s_artist").val(artist);
                $("#s_url").val(url);
                //alert($('.notice_id', notice).text());
              	 NoticeReplySet2(content, $('.notice_id', notice).text());
                return false;
            });
        });
    }
}

function NoticeGift() {
		
	
	if ($('#notice_data-text').length > 0) {
		
        $('#content .notice').each(function() {
            var notice = $(this);
            $('.notice_gift', $(this)).click(function() {
            	gift = true;
            	if($('#showstream').html()) {
            		var nickname = $('#pageUser').html();
            	} else {
            		var nickname = ($('.author .nickname', notice).length > 0) ? $('.author .nickname', notice) : $('.author .nickname');
            		nickname = nickname.text();
                }
                //NoticeReplySet(nickname.text(), $('.notice_id', notice).text());
                //Update by ITFS
                randomText();
               if($('#usCurrent').val() == null) {
			
					var url = "main/login?type=blip&height=170&width=320";
					var t = '<a id="blipLogin" href="#">Đăng nhập</a>&nbsp;|&nbsp;<a id="blipRegister" href="#">Đăng ký</a>';//null;//this.title || this.name || null;
					tb_show(t,url,"Blipping");
					return false;
				}
               
                var content = '@' + nickname;
                content += ' ';
                var title = $('.ct-title',notice).text();
                var artist = $('.ct-artist',notice).text();
                var url = $('.ct-url',notice).val();
                $('#blipbox').show();
				$('#searchResults').hide();
				$('#searchbox').hide();
                $("#frm-artist").text(artist);
                $("#frm-title").text(title);
                $("#s_title").val(title);
                $("#s_artist").val(artist);
                $("#s_url").val(url);
                //gift = true;
                NoticeReplySet2(content, $('.notice_id_gift', notice).text());
                return false;
            });
        });
    }
}

/**
* Update by ITFS
* Show content Notice
**/

function NoticeReplySet2(content,id) {
	
	//if (content.length > 0) {
		replyto = content;
		//if ($("#notice_data-text").length) {
			
			$("#notice_data-text").val(replyto);
			$("#form_notice input#notice_in-reply-to").val(id);
			$("#notice_data-text").focus();
			return false;
		//}
	//}
	//return true;
}

function NoticeReplySet(nick,id) {
	rgx_username = /^[0-9a-zA-Z\-_.]*$/;
	if (nick.match(rgx_username)) {
		replyto = "@" + nick + " ";
		if ($("#notice_data-text").length) {
			$("#notice_data-text").val(replyto);
			$("#form_notice input#notice_in-reply-to").val(id);
			$("#notice_data-text").focus();
			return false;
		}
	}
	return true;
}

function send_to_reply(action) {
	
	$.ajax({
		   type: "POST",
		   url: server + "/sendmail",
		   data: 'act=' + action,
		   success: function(msg){}
		 });
}
function send_to_subscribe(action,other_id) {
	$.ajax({
		   type: "POST",
		   url: server + "/sendmail",
		   data: 'act=' + action + '&other_id=' + other_id,
		   success: function(msg){}
		 });
}
function send_to_props(action,nickname,id) {
	$.ajax({
		   type: "POST",
		   url: server + "/sendmail",
		   data: 'act=' + action + '&nick=' + nickname + '&id=' + id,
		   success: function(msg){}
		 });
}
function send_to_reblip(action,id) {
	$.ajax({
		   type: "POST",
		   url: server + "/sendmail",
		   data: 'act=' + action + '&notice_id=' + id,
		   success: function(msg){}
		 });
}

function sendComment() {
	//infor send
	var currentTime = new Date()
	var dateTime = currentTime.getDate() + "/" + currentTime.getMonth() + "/" + currentTime.getFullYear() + " " + currentTime.getHours() + ":" + currentTime.getMinutes();
	var addcomment = $('#addcomment').val();
	if(addcomment == "") {
		$('#addcomment').focus();
		return false;
	}
	var avatar = $('#usCurrentAvatar').val();
	var img = '<img src=' + avatar + ' width = "45" height="45" >';
	var user = $('#usCurrent').val();
	var foruser = $('#pageUser').html();
	var sizeComment = 9;
	var listComment = $('.comments').children();
	var data = "<li class='comment clearfix'><span class='vcard author'>"+img+" <a href='' class='url'><span class='nickname fn'>" + user + ": </span></a></span><span class='itfs-entry-content'>" + addcomment + "</span>";
		data += '<div class="entry-content"><dl class="timestamp"><dt>Published</dt><dd><abbr style="color:#676869">' + dateTime + '</abbr></dd></dl></div></li>';
	var readmore = "";
	if(listComment.length <= sizeComment) {
		sizeComment = listComment.length;
	}
	
	//readmore = "<a href='" + server + "/" +user+"/comment'>Xem tất cả(<span id='allcomment'>" + numComment + "</span>)</a>";
	for(i = 0; i < sizeComment;i++) {
		data += "<li class='comment clearfix'>"+$(listComment[i]).html()+"</li>";
	}
	allcomment =$('.totalComment').text();
	allcomment = allcomment.replace(/\(/,'');
	allcomment = parseInt(allcomment.replace(/\)/,'')) + 1;
	$('.totalComment').text('('+allcomment+')');
	
	$('.comments').html(data);
	$('#addcomment').val("");
	
	
	//update data
	
		 
	var newcomment = $.ajax({
		   type: "POST",
		   url: server + "/index.php?action=comment&type=add&nickname=" + foruser ,
		   data: 'content='+ addcomment,
		   async: false
		 }).responseText;
	showPageComment(addcomment,newcomment,user,foruser,img);	   
	return false;
	
}

function showPageComment(addcomment,idComment,user,foruser,img) {
	
	var page_comment = $('#page_comment').val();
	
	if(page_comment == 1) {
		var contents = $('#show_page_comment').children();
		
		var data = "<div><b>" + user + ":</b>" + addcomment + "</div>";
		var size = 20;
		if(contents.length <= size) {
			size = contents.length;
		} else {
			if($('.nav_next').html()== '') {
				var pageNext = $('#pageNext').val();
				pager ='<a href="' + server + '/'+foruser+'/comment?pager='+pageNext+'">Before</a>';
				$('.nav_next').html(pager);
			}
		}
		//alert($(contents[0]).html());
		
		var currentTime = new Date()
		var dateTime = currentTime.getDate() + "/" + currentTime.getMonth() + "/" + currentTime.getFullYear() + " " + currentTime.getHours() + ":" + currentTime.getMinutes();
		var avatarCurrent = $("#usCurrentAvatar").val();
		var data = "<li class=\"hentry notice clearfix alter\">";
		data += "<div class='entry-title'><span class=\"vcard author\"><a href=\""+server+"/"+user+"\">";// + user + ":</b>" + addcomment + "</div>";
		data += "<img class=\"avatar photo\" src=\"" + avatarCurrent + "\"/>";
		data += "<span class=\"nickname fn\">" + user + "</span></a></span><span class=\"entry-content\">" + addcomment + "</span></div>";
		data += "<div class=\"entry-content\"><dl class=\"timestamp\"><dt>Published</dt><dd><abbr style='color:#676869'>" + dateTime + "</abbr></dd></dl></div>";
		data += '<div class="notice-options"><dl class="notice_delete"><dt>Delete this comment</dt><dd><a href="' + server + '/commentdelete/' + idComment + '">Delete</a></dd></dl></div></li>';
		for(i = 0; i <= size-1;i++) {
			if(i % 2 == 0) {
			data += "<li class=\"hentry notice clearfix\">" + $(contents[i]).html() + "</li>";
			} else {
			data += "<li class=\"hentry notice clearfix alter\">" + $(contents[i]).html() + "</li>";
			}
		}
		$('#show_page_comment').html(data);
	}
}

function startNotify() {
	if($('#notifyContent') && $('#notify') && $('#closebutton')) {
		$('#notifyContent').notificationmsg({period: 100000});
	    $('#notify').click(onClick);
	    $('#closebutton').click(function(){ $('#notifyContent').notificationmsg('hide'); });
    } 
}
function getNotify() {
	var data = $.ajax({
		   type: "POST",
		   url: server + "/index.php?action=getNotify" ,
		   async: false
		 }).responseText;
	return data;
}
function checkNotify() {
	var s = $.ajax({
		   type: "POST",
		   url: server + "/index.php?action=getNotify&act=check" ,
		   async: false
		 }).responseText;
		 //setNotifyStatus(s);
		 if(s == 'on') {
		 	$('#notify').html('Notify on');
		 	$('#notify').attr('class','notiOn');
		 }
}

function getNewNotice() {
		
		var pagePublic = $('#public').html();
		var pagePersonal = $('#all').html();
		var listNotice = $('.notices').children();
		
		var size = 20;
		var data = "";
		var latestId;// = $(listNotice[0]).attr("id");
		var user = $('#usCurrent').val();
		if(pagePublic || pagePersonal) {
			//get data new for public
			
			if(pagePublic) {
				latestId = $('#publicLatest').val();
				var str = getNewPublic(latestId);
				if(str != "") {
					if(latestId == "") latestId = 0;
					pager ='<a href="' + server + '/?page='+$('#pageNext').val()+'">Before</a>';
				} else {
					return false;
				}
			} else if(pagePersonal) {
				latestId = $('#personalLatest').val();
				var str = getNewPersonal(latestId);
				if(str != "") {
					if(latestId == "") latestId = 0;
					pager ='<a href="' + server + '/' + user + '/all?page='+$('#pageNext').val()+'">Before</a>';
				} else {
				 	return false;
				}
			}
			
			var pos = str.indexOf("-");
			var numrow = str.substr(0,pos); 
			var temp = str.substr(pos + 1);
			var pos2 = temp.indexOf("-");
			var tempLatest = temp.substr(0,pos2);
			if(pagePublic) {
				$('#publicLatest').val(tempLatest);
			} else if (pagePersonal) {
				$('#personalLatest').val(tempLatest);
			}
			data += temp.substr(pos2 + 1);
			
			numrow -= 0;
			lengthPage = numrow + listNotice.length;
			if(lengthPage <= size) {
				size = lengthPage;
			} else {
				if($('.nav_next').html()== '') {
					$('.nav_next').html(pager);
				}
			}
			var tempId = data.split('special');
			var specialId = tempId[0].replace(/<li id="/,'');
			for(i = 0; i < size;i++) {
				var attrId = $(listNotice[i]).attr("id")
				if (attrId.match("special")=="special") {
					playList.splice(0,1);
					//continue;
				} else {
						if(attrId) {
						if (i%2==0) {
							data += '<li id="'+attrId+'" class="hentry notice clearfix">';	
						} else {
							data += '<li id="'+attrId+'" class="hentry notice clearfix">';
						}
						
						data += $(listNotice[i]).html() + "</li>";
					}
				}
			}
			
			$('.notices').html(data);
			
			getStatusPlayer();
			NoticeHover();
			NoticeReply();
			NoticeGift();
			Props();
			$("form.form_favor").ajaxForm(favoptions);
			$("form.form_disfavor").ajaxForm(disoptions);
			$("form.form_favor").each(addAjaxHidden);
			$("form.form_disfavor").each(addAjaxHidden);
			focusSong();
			$('li[id=' + $.cookie('cookieCurrentSong') + ']').addClass('playing');
		}
		
		
}

function getNewPublic(latestId) {
	if(latestId != '') {
		var data = $.ajax({
		   type: "POST",
		   url: server + "/index.php?action=getnewnotice&type=public&id=" + latestId,
		   async: false
		 }).responseText;
		 return data;
	}	 
	return ''; 
}
function getNewPersonal(latestId) {
	if(latestId != '') {
		var data = $.ajax({
			   type: "POST",
			   url: server + "/index.php?action=getnewnotice&type=personal&id=" + latestId,
			   async: false
			 }).responseText;
			 return data; 
		}
	return '';	 
}
function updatePlaylist(flag) {
	if($('#pageUser').html() == $('#usCurrent').val() ) {
		var countPlaylist = $('#countPlaylist').html();
		countPlaylist -= 0;
		if(flag == 0) {
			countPlaylist -= 1;
		} else {
			countPlaylist += 1;
		}
		$('#countPlaylist').html(countPlaylist);
	}
}

function updateFavorite(flag) {
	if($('#pageUser').html() == $('#usCurrent').val() ) {
		var countFavorite = $('#countFavorite').html();
		countFavorite -= 0;
		if(flag == 0) {
			countFavorite -= 1;
		} else {
			countFavorite += 1;
		}
		$('#countFavorite').html(countFavorite);
	}
}
function randomText() {
	var num = Math.random()*4;
	if(num <= 1) {
	 	$('#blip-alert').html('Tip: Để tặng bài hát, bạn gõ <strong>@Username</strong> vào nội dung lời nhắn.');
	} else if(num > 1 && num <= 2) {
		$('#blip-alert').html('Tip: Để đặt tag cho một bài hát, bạn gõ <strong>#TừKhóaMuốnTag</strong>');
	} else if(num > 2 && num <= 3) {
		$('#blip-alert').html('Tip: Để search bài hát, bạn có thể gõ tiếng Việt <strong>không dấu</strong>');	 
	} else {
		$('#blip-alert').html('Tip: Gửi bài hát tới <strong>YM</strong> bằng cách thêm <strong>@ym:nickmuốngửi</strong>');
	}
}

function onClick(e) {
     var animStyle = 'slide'
     if(e.srcElement){
         if(e.srcElement.id==='notify'){
             animStyle = 'slide';
         }
     }
     else{
         if(e.target.id==='notify'){
             animStyle = 'slide';
         }
     }
    var content = getNotify(); 
    if(content == '') {
    	content = 'Không có thông báo mới nào';
    }
    
	$(".modalbody").html(content);
    $('#notifyContent').notificationmsg({animation:animStyle});
    $('#notifyContent').notificationmsg('show');
    //$('#notifyContent').toggle();
    //setNotifyStatus('off');
    $('#notify').html('Notify off');
	$('#notify').attr('class','notiOff');
}

function showReg() {
	$('#loginbox').hide();
	$('#subscribersbox').show();
	$('#showimport').html('<a onclick="showNotReg();" href="#" >Tiếp</a>');
}

function showNotReg() {
	$('#loginbox').show();
	$('#subscribersbox').hide();
	$('#showimport').html('<a onclick="showReg();" href="#" >Quay lại</a>');
}

