$(function() {
	$(window).scroll(function() {
		$.scrollMsgs();
	});
	
	$.extend({
		showError: function (msg) {
			var elem = $(document.createElement('div')).addClass('post').css({top: 10});
			$(msg).each(function() {
				elem.append('<p>' + this + '</p>');
			});

			$.addMsg(elem, 'error');
		},
		showInvite: function (msg) {
			var elem = $(document.createElement('div')).addClass('post').css({top: 10});
			$(msg).each(function() {
				var mess = '<p>' + this.message + '</p>';
				mess += '<center>';
				mess += '<table cellpadding="0" cellspacing="0">';
				mess += '<tr><td>'
				mess += '<input type="submit" value="Принять" class="bottom" id="btn_accept_call" binded="no" userid="'+ this.master_user_id +'" />';
				mess += '</td><td><span class="left38"></span></td><td>';
				mess += '<input type="button" value="Отклонить" class="bottom" id="btn_decline_call" binded="no" userid="'+ this.master_user_id +'" />';
				mess += '</td><td><span class="left38"></span></td><td>';
				mess += '<input type="button" value="В черный список" class="bottom" id="btn_blacklist_inviter" binded="no" userid="'+ this.master_user_id +'" />';
				mess += '</td></tr></table>';
				mess += '</center>';
				elem.append(mess);
			});
			$.addMsg(elem, 'invite');
			
			$('[binded=no][id=btn_decline_call]').each(function() {
				$(this).attr('binded', 'yes').click(function() {
					$.ajax({
						type: 'get',
						url: '/bg/events.php', 
						cache: false,
						data: { 'act': 'decline_call', 'user_id': $(this).attr('userid') },
						dataType: 'json',
						success: function(json) {
							if (json.result == 0) {
								elem.fadeOut('slow', elem.remove);
							} else {
								$.showError(json.errors);
							}
						}
					});
				});
			});
			
			$('[binded=no][id=btn_blacklist_inviter]').each(function() {
				$(this).attr('binded', 'yes').click(function() {
					$.ajax({
						type: 'get',
						url: '/bg/events.php', 
						cache: false,
						data: { 'act': 'blacklist_inviter', 'user_id': $(this).attr('userid') },
						dataType: 'json',
						success: function(json) {
							if (json.result == 0) {
								elem.fadeOut('slow', elem.remove);
							} else {
								$.showError(json.errors);
							}
						}
					});
				});
			});
			
			$('[binded=no][id=btn_accept_call]').each(function() {
				var userId = $(this).attr('userid');
				$(this).attr('binded', 'yes').click(function() {
					$.ajax({
						type: 'get',
						url: '/bg/events.php', 
						cache: false,
						data: { 'act': 'accept_call', 'user_id': userId },
						dataType: 'json',
						success: function(json) {
							if (json.result == 0) {
								window.location.href = '/duduphone.php?user_id='+userId+'&code='+json.data.code;
							} else {
								$.showError(json.errors);
								elem.fadeOut('slow', elem.remove);
							}
						}
					});
				});
			});
			
		},
		addMsg: function(elem, type) {
			
			type = type || 'error';
			
			if (this.messageStack == undefined) this.messageStack = {};
			if (this.messageStackCounter == undefined) this.messageStackCounter = 0;
			else this.messageStackCounter++;
		
			this.messageStack[this.messageStackCounter] = {};
			this.messageStack[this.messageStackCounter].type = type;
			this.messageStack[this.messageStackCounter].elem = elem;
			
			elem.css({
				position: 'absolute',
				display: 'none',
				width: (type == 'error' ? 480: 550),
				left: 10 
			})
			.attr('position', this.messageStackCounter)
			.appendTo(document.body);
			
//			$.debug(true);
//			$.log($(window).width());
//			$.log(elem.width());
			this.processMsgs();
		},
		
		removeMsg: function(elem) {
			elem = $(elem);
			for (i in this.messageStack) {
				//alert(this.messageStack[i].elem.attr('position'));
				//alert(elem.attr('position'));
				if (this.messageStack[i].elem.attr('position') != elem.attr('position')) continue;
				//alert('Remove elem: '+ i);
				delete this.messageStack[i];
			}
			this.shiftMsgs();
			//this.processMsgs();
		},
		
		processMsgs: function() {
			var prevTopPosition = $(window).scrollTop() + 10;
			for (i in this.messageStack) {
				var elem = this.messageStack[i].elem;
				var type = this.messageStack[i].type;

				if (type == 'error') {
					elem.css({ display: '' })
					.animate({ top: prevTopPosition }, 100)
					.wait(3000)
					.fadeOut('slow', elem.remove);
				} else if (type == 'invite') {
					elem.css({ display: '' })
					.animate({ top: prevTopPosition }, 100);
				}
				
				prevTopPosition += elem.height() + 30;
			};
			
		},
		
		shiftMsgs: function() {
			var prevTopPosition = $(window).scrollTop() + 10;
			for (i in this.messageStack) {
				var elem = this.messageStack[i].elem;
				elem.animate({ top: prevTopPosition }, { duration: 100, queue: false} );
				prevTopPosition += elem.height() + 30;
			}
		},
		
		scrollMsgs: function() {
			//TODO: scroll messages when window scroll
			this.shiftMsgs();
		}
	});
	
    $.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };

    $.fn.remove = function() {
    	$.removeMsg(this);
    }
   
});
