var old_html;
var top_f_div_page = 0; 
var top_m_div_page = 0; 
var next_img = new Image();

function checkMessages() {
	jQuery.ajax({
        type: 'GET',
        url: '/ajax/ajax.php?action=msg',
        data: null,
        cache: false,
        success: function(html){
       		document.getElementById('countMsg').innerHTML = html;
       		readMessage(0); 
       		setTimeout("checkMessages()", 30000);
        }
     }); 
      

}

function checkNotifications() {
	jQuery.ajax({
        type: 'GET',
        url: '/ajax/ajax.php?action=notifications',
        data: null,
        cache: false,
        success: function(html){
       		document.getElementById('countNot').innerHTML = html;
       		readComment(0); 
       		setTimeout("checkNotifications()", 30000);
        }
     }); 
     
}

function ajax(file, data, div, method)
{
     $.ajax({
        type: method,
        url: file,
        data: data,
        cache: false,
        success: function(html){
       		document.getElementById(div).innerHTML = html;
        }
     });
}

function append_notifications(limit)
{
	
     $.ajax({
	    type: "GET",
        url: "/users/more_notifications/"+limit,
        success: function(html){
        	$(".older_events").parent().hide();
       		$("#ntf").append(html);
        }
     });
}

function exec_ajax(file, method)
{
     $.ajax({
        type: method,
        url: file,
        data: null,
        cache: false,
        success: function(html){
        	eval(html);
        }
     });
}

function ajax_eval(file, data, div, method)
{
     $.ajax({
        type: method,
        url: file,
        data: data,
        cache: false,
        success: function(html){
       		eval(html);
        }
     });
}

function periodical_ajax(file, data, div, interval)
{
	$.ajax({
        type: "GET",
        url: file,
        data: data,
        cache: false,
        success: function(html){
        	if (html != old_num) {
           		 $("#"+div).html(html);
           		  $("#"+div).fadeOut("slow");
           		  $("#"+div).fadeIn("slow");
           		  old_html = html;
        	}
			setTimeout("periodical_ajax('"+file+"', '', '"+div+"');", interval);
        }
     }); 
}



//Profile actions
function profileAddFriend(friend_id) {
	//showPreloader();
	ajax_eval('/friends/add_friend/' + parseInt(friend_id) + '/L2FqYXg=', null, 'fr_txt', 'GET');
	return false;
}

// Friends
function acceptFriendRequest(obj, friendId) {
	lastActionObj = obj;

	//showPreloader();
	var url = '/friends/afid/'+parseInt(friendId)+'/L2FqYXg=';
	new Ajax.Request(url, {method: 'get', onSuccess: doAcceptFriendRequest});
	return false;
}

function readComment(n) {
	current = jQuery("#countNot span").html();
	new_v = current-n;
	if (new_v != 1) izvestiq = ' Известия'; else izvestiq = ' Известиe'; 
	jQuery("#countNot span").html(new_v); 
	if ( new_v   < 1 ) jQuery("#countNot span").removeClass("blink_new");
	
	jQuery("#textNot").html(izvestiq);
}

function readMessage(n) {
	current = jQuery("#countMsg span").html();
	new_v = current-n;
	if (new_v != 1) msgs = ' Съобщения'; else msgs = ' Съобщение'; 
	jQuery("#countMsg span").html(new_v); 
	jQuery("#textMsg").html(msgs);
}

function readRemove(obj, id) {
	var p = $(obj).parent();
	
 	$(p).fadeOut(150, function() { $(p).hide();  });

	$('#ntfc').html($('#ntfc').html()-1);
	$.ajax({
        type: "GET",
        url: "/ajax/remove_notification.php?id="+id
     });
    readComment(0);
     var cc = $('#ntfc').html(); 
     if ( cc <= 0 ) $("#myntf").html('<p>Нямате нови известия</p>');
}

var doAcceptFriendRequest = function (t) {
	readComment(1);
	if (t.responseText == '') {
		$('all_friends').innerHTML = parseInt($('all_friends').innerHTML) + 1;
		$('pending_friends').innerHTML = parseInt($('pending_friends').innerHTML) - 1;
		lastActionObj.parentNode.parentNode.parentNode.parentNode.removeChild(lastActionObj.parentNode.parentNode.parentNode);
		if (parseInt($('pending_friends').innerHTML)==0) $('friends_ajax').innerHTML = "<br class=\"clear\"><div class=\"empty\">Нямате покани.</div>"; //<br style=\"clear: both\">
	}
}

function rejectFriendRequest(obj, friendId) {
	lastActionObj = obj;

	if (confirm('Сигурен ли сте, че искте да откажете поканата?')) {
	 	var url = '/friends/rjfid/'+parseInt(friendId)+'/L2FqYXg=';
		new Ajax.Request(url, {method: 'get', onSuccess: doRejectFriendRequest});
	}
	return false;
}

var doRejectFriendRequest = function (t) {
	readComment(1);
	if (t.responseText == '') {
		$('pending_friends').innerHTML = parseInt($('pending_friends').innerHTML) - 1;
		lastActionObj.parentNode.parentNode.parentNode.parentNode.removeChild(lastActionObj.parentNode.parentNode.parentNode);
		if (parseInt($('pending_friends').innerHTML)==0) $('friends_ajax').innerHTML = "<br class=\"clear\"><div class=\"empty\">Нямате покани.</div>"; //<br style=\"clear: both\">
	}
}


function friendsPaging (parameters, page_string, sort_value) {
	var sort = $('sort_friends') ? $('sort_friends').value : '';
	//var online = ( $('only_online').checked == true ) ? $('only_online').value : '';
	var online = '';
	
	var friend_search = empty_find_string == $('friend_search').value ? "" : $('friend_search').value;

	//if (typeof current_letter == 'undefined') current_letter = '';
	if (typeof sort_value != 'undefined') sort = sort_value;

	var func = 'ajax_get_friends';
	if (typeof friends_categories != 'undefined') {
		func = 'ajax_get_cat_friends/'+cat_id;
	}

	var url = '/friends/'+func+'/'+parameters+'?'+page_string+'&search='+encodeURIComponent(friend_search)+'&sort='+encodeURIComponent(sort)+'&online='+online;

	//hidePops();
	//showPreloader();
	new Ajax.Request(url, {method: "get", onSuccess: doFriendsPaging});
}

var doFriendsPaging = function (t) {
	$('friends_ajax').innerHTML = t.responseText;
	//hidePops();

	stylizeSortFld();
}

function _alert(txt) {
	document.getElementById('alert_layout').innerHTML = txt;
	$("#alert_layout").dialog({
		bgiframe: true,
		resizable: false,
		draggable: false,
	 
		modal: true,
		close: false,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
		'ОК': function() {
			$(this).dialog('close');
		}
		}
	});
	$("#alert_layout").dialog("open");
}

function _confirm(txt, f_true, f_false) { 
	document.getElementById('confirm_layout').innerHTML = txt;

	$("#confirm_layout").dialog({
		bgiframe: true,
		resizable: false,
		draggable: false,
	 
		modal: true,
		close: false,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
		'ОК': function() {
			$(this).dialog('close');
			eval(f_true);
		}
		,
		'Откажи': function() {
			$(this).dialog('close');
			eval(f_false);
		}
		}
	});
	$("#confirm_layout").dialog("open");
}

function hide_user(obj, id, ajax_call, send_request, a_obj) {
	krfiends_count = krfiends_count-1;
	if ( ajax_call ) {
		$.ajax({
        type: "GET",
        url: "/ajax/hide_user.php?id="+id,
        success: function() {
        	$('#'+obj).fadeOut(100);
			if ( krfiends_count <= 0 ) {
			$("#know_f").html("<p>Няма намерени потребители</p>");
			}
        }
      });
      
      
	
	} 
	if ( send_request ) {
		$.ajax({
        type: "GET",
        url: "/friends/add_friend/"+id+"/L2FqYXg/?known=1",
        success: function(code) {
        	a_obj.html("Поканен...");
        	$("#"+obj).oneTime("1s", function() {
					$(this).fadeOut(100); 
			 	})
        }
      });
	}
 }
 

function post_comment(sid, stype) {
	comment = $("#cmn").val();
	if ( comment == '' ) return false;
	
	$("#post_comment_f input").attr("disabled", "true");
	$("#post_comment_f input").val("Изпращане ...");
	$("#post_comment_f input").blur();
	$("#post_comment_f textarea").attr("disabled", "true");
	$("#post_comment_f input").removeClass("input");
	$("#post_comment_f input").addClass("submitted");
	
	disable_comments = true;
	$.ajax({
        type: "POST",
        url: "/users/add_comment/"+sid+"/"+stype,
        data: "comment="+comment+"&i="+c_total,
        success: function(js) {
        	eval(js);
        	
        }
      });
      return false;
}

function show_loader(){
	document.getElementById('most_recent_div').innerHTML = '<div class="center margin recent_loader"><img src="/images/loader2.gif"></div>';
}
var old_html_ch = '';
function load_chat(type){
	if( type == 2 ) var url_to_load = '/chat/load_chat/';
	else var url_to_load = '/chat/load_chat_small/'
	jQuery.ajax({
        type: 'POST',
        url: url_to_load,
        data: null,
        cache: false,
        success: function(html){
        	if ( old_html_ch != html ) {
	         document.getElementById('chat2').innerHTML = html;
	         jQuery(".chatbox").scrollTop(jQuery(".chatbox").attr("scrollHeight")+20);
	         
        		old_html_ch = html;
        	}
        }
     });
}

function add_chat_message(user_id, type){
	 if ( !user_id ){ alert('Чата е достъпен само за регистрирани потребители'); return false; }
	 msg = document.getElementById("chat_message").value;
	 jQuery("#chat_message").val("");
	 jQuery("#chat_message").focus();
     if ( msg == '' ) { return false; }
     jQuery.ajax({
        type: 'POST',
        url: '/chat/add_message/',
        data: 'message='+msg,
        cache: false
     });
     
     jQuery(".chatbox").scrollTop(jQuery(".chatbox").attr("scrollHeight")+20);
     load_chat(type);
     return false;
}