var mod_passport_im_loader = 
{
	params: {
		user_id: 0,
		obj: 0,
		type: 0,
		title: 0,
		url: 0,
		reload: 0
	},
	
	stack: null,
	size: 0,
	tags : {
		B: 0,
		I: 0,
		U: 0,
		S: 0,
		QUOTE: 0,
		SMALL: 0,
		URL: 0,
		EMAIL: 0,
		LIST: 0,
		CENTER: 0,
		LEFT: 0,
		RIGHT: 0,
		JUSTIFY: 0,
		MEDIA: 0
	},

	push: function(val)
	{
		if(this.stack == null)
			this.stack = new Array(1000);
		this.stack[this.size++] = val;
	},

	pop: function()
	{
		if(this.stack == null)
			this.stack = new Array(1000);
		return this.stack[--this.size];
	},

	insertsmile: function(val)
	{
		this.showsmiles(false);
		this.appendEditor(val);
		this.focusEditor();
	},

	inserttag: function(tag)
	{
	    if(tag=='URL')
	        return this.inserturl();
	    if(tag=='EMAIL')
	        return this.insertemail();
	    if(tag=='MEDIA')
	        return this.insertmedia();
		if(tag=='QUOTE')
			return this.quote();
		ta = $('#im_form_text').get(0);
		var cltag = '';
		if(tag == 'B' || tag == 'I' || tag == 'U' || tag == 'S' || tag == 'QUOTE' ||
		    tag == 'SMALL' || tag == 'URL' || tag == 'EMAIL' || tag == 'LIST' || tag == 'CENTER' ||
		    tag == 'LEFT' || tag == 'RIGHT' || tag == 'JUSTIFY')
			cltag = '/'+tag;
		var single = true;
		if (document.selection && document.selection.createRange)
		{
			ta.focus();
			sel1 = ta.value.substr(0, ta.selectionStart);

			var sel = document.selection;
			var text = '';
			var rng = sel.createRange();

			rng.colapse;

			if ( (sel.type == "Text" || sel.type == "None") && rng != null )
			{			
				if ( cltag != "" && rng.text.length > 0)
				{
					text = '['+tag+']' + rng.text + '[/'+tag+']';
					single = false;
				}
					
				rng.text = text;
			}
		}
		if(single == true)
		{
			if(this.tags[tag] == 0)
			{
				this.appendEditor('['+tag+']');
				this.push(tag);
				this.tags[tag] = 1;
			}
			else
			{
				var tag2;
				do
				{
					tag2 = this.pop();
					this.appendEditor('[/'+tag2+']');
					this.tags[tag2] = 0;
				}while(tag2 != tag);
			}
		}
		this.focusEditor();
	},

	quote: function()
	{
		txt = '';
		if (document.getSelection) { txt = document.getSelection(); } else if (document.selection) { txt = document.selection.createRange().text; }
		if ( txt ) txt='[QUOTE]'+txt+'[/QUOTE]\n';
		this.appendEditor(txt);
		this.focusSubmit();
		this.focusEditor();
	},

	appendEditor: function(val)
	{
		$('#im_form_text').get(0).value = $('#im_form_text').get(0).value + val;
	},
	focusEditor: function()
	{
		$('#im_form_text').focus();
	},

	inserturl: function()
	{
	    var url = window.prompt('Введите адрес сайта', '');
	    if(url == '' || url == null)
	        return;
	        
	    var inserted = false;
	    
		ta = $('#im_form_text').get(0);
	    
	    if (document.selection && document.selection.createRange)
		{
			ta.focus();
			sel1 = ta.value.substr(0, ta.selectionStart);

			var sel = document.selection;
			var text = '';
			var rng = sel.createRange();

			rng.colapse;

			if ( (sel.type == "Text" || sel.type == "None") && rng != null )
			{			
				if (rng.text.length > 0)
				{
		            inserted = true;
					text = rng.text;
					rng.text = '[URL='+url+']'+text+'[/URL]';
				}
			}
		}
		if(inserted == false)
		{
	        text = window.prompt('Введите текст ссылки', '');
	        if(text == '' || text == null)
	            text = url;
	        this.appendEditor('[URL='+url+']'+text+'[/URL]');
	    }    
	},

	insertemail: function()
	{
	    var url = window.prompt('Введите адрес электронного почтового ящика', '');
	    if(url == '' || url == null)
	        return;
	    
	    var inserted = false;
	    
		ta = $('#im_form_text').get(0);
	    
	    if (document.selection && document.selection.createRange)
		{
			ta.focus();
			sel1 = ta.value.substr(0, ta.selectionStart);

			var sel = document.selection;
			var text = '';
			var rng = sel.createRange();

			rng.colapse;

			if ( (sel.type == "Text" || sel.type == "None") && rng != null )
			{
				if (rng.text.length > 0)
				{
				    inserted = true;
					text = rng.text;
				    rng.text = '[EMAIL='+url+']'+text+'[/EMAIL]';
				}
			}
		}
		if(inserted == false)
		{
	        text = window.prompt('Введите описание ссылки', '');
	        if(text == '' || text == null)
	            text = url;
	        this.appendEditor('[EMAIL='+url+']'+text+'[/EMAIL]');
	    }    
	},

	insertmedia: function()
	{
	    var url = window.prompt('Введите адрес страницы видеоролика', '');
	    if(url == '' || url == null)
	        return;
	        
	    var inserted = false;
	    
		ta = $('#im_form_text').get(0);
	    
	    if (document.selection && document.selection.createRange)
		{
			ta.focus();
			sel1 = ta.value.substr(0, ta.selectionStart);

			var sel = document.selection;
			var text = '';
			var rng = sel.createRange();

			rng.colapse;

			if ( (sel.type == "Text" || sel.type == "None") && rng != null )
			{			
				if (rng.text.length > 0)
					url = rng.text;				
		        inserted = true;
				rng.text = '[MEDIA]'+url+'[/MEDIA]';
			}
		}
		if(inserted == false)
		{
	        this.appendEditor('[MEDIA]'+url+'[/MEDIA]');
	    }    
	},
	
	showgallery: function(url, container) {

		var input = $(container);
		var cont = input[0].value;

		$(container).insertAtCaretPos(' ');
		if (cont != input[0].value)
			input[0].value = cont;

		window.open(url,'_blank', 'width=650,height=450,directories=1,location=1,menubar=1,resizable=1,toolbar=1,scrollbars=1');
		window.getUserGalleryContainer = function() {
			return container;
		}
	},
	
	showsmiles: function(show)
	{
		if(show != false)
		{
			$("#im_form_smiles").show();
			$("#im_form_smiles").bind("mouseleave", function(e){
				$("#im_form_smiles").unbind();
		        $("#im_form_smiles").hide();
		    });
		}
		else
			$("#im_form_smiles").hide();
	},

	load: function(user_id, obj, type, title, url, reload)
	{	
		reload = ( !reload ) ? 0 : 1;
		
		mod_passport_im_loader.params.user_id	= user_id;
		mod_passport_im_loader.params.obj		= obj;
		mod_passport_im_loader.params.type		= type;
		mod_passport_im_loader.params.title		= title;
		mod_passport_im_loader.params.url		= url;
		mod_passport_im_loader.params.reload	= reload;
		
		$.ajax({
			url: '/passport/im/ajax_new.php',
			dataType: 'json',
			data: {
				to:user_id,
				m:obj, 
				type: type,
				url: url,
				title: title,
				rand:Math.random()},
			success: function(data){mod_passport_im_loader.success_loaded(data, type, title, url, reload)},
			type: 'GET'});	
	},
	
	makeread: function(obj)
	{
		$.ajax({
			url: '/passport/im/ajax_new.php',
			dataType: 'json',
			data: {
				to:0,
				m:obj, 
				type: '',
				url: '',
				title: '',
				rand:Math.random()},
			success: function(data){location.href=location.href;},
			type: 'GET'});
	},
	
	success_loaded: function(data, type, title, url, reload)
	{
		if(data.status == 'ok' || data.status == 'login')
		{
			/*var params = '<input type="hidden" id="im_type" value="'+type+'">'+
						 '<input type="hidden" id="im_url" value="'+url+'">'+
						 '<input type="hidden" id="im_title" value="'+title+'">'+
						 '<input type="hidden" id="im_reload" value="'+reload+'">';*/
		    $.fn.nyroModalManual({
				modal: true,				
				type: 'manual',
				content: '<div id="im_form_container" style="opacity: 0;filter: alpha(opacity=0);">' + data.data + '</div>',
				endShowContent: mod_passport_im_loader.rendered,
				hideContent: mod_passport_im_loader.hideContent,
				endRemove: function(){if(reload)location.href=location.href;}
		    });			
			
			if ( data.status == 'ok' ) 
			{
				//$('.nyroModalSend').click(this.send);
				
				$('#im_form_itype').val(type);
				$('#im_form_ititle').val(title);
				$('#im_form_iurl').val(url);
				
				$('#im_form').ajaxForm({
			        beforeSubmit: function(a,f,o) {
						$('#imSendButton').attr('disabled', true);
			        },
			        success: function(data){
						if(data.substr(0,1) != '{')
							data = {status: 'error', data: 'Не удалось отправить сообщение, возможно вы прикрепили слишком большой файл!'};
						else
							data = eval('('+data+')'); // jquery.form не разбирает пришедшие данные
						mod_passport_im_loader.success_loaded(data, type, url, title, reload)
					}
			    });
				
			}
			else
				$('.nyroModalSend').click(this.login);
		}
		else if(data.status == 'added')
		{
			$.nyroModalRemove();
			if(reload==1)
				location.href=location.href;
		}
		else if(data.status == 'error')
		{
			$('#imSendButton').attr('disabled', false);
			alert(data.data);
		}
	},
	
	hideContent: function(elts, settings, callback)
	{
		elts.contentWrapper.hide();
		if ($.isFunction(callback))
			callback();
	},
	
	send: function()
	{
		$('#imSendButton').attr('disabled', true);
		$.ajax({
			url: '/passport/im/ajax_new.php',
			dataType: 'json',
			data: {
				action:	'im_ajax_new',
				to:		$('#im_form_to').val(),
				text:	$('#im_form_text').val(),
				itype:	mod_passport_im_loader.params.type,
				ititle:	mod_passport_im_loader.params.title,
				iurl:	mod_passport_im_loader.params.url,
				rand:Math.random()
			},
			success: function(data){mod_passport_im_loader.success_loaded(data, mod_passport_im_loader.params.type, mod_passport_im_loader.params.url, mod_passport_im_loader.params.title, mod_passport_im_loader.params.reload)},
			type: 'POST'});	
	},
	
	login: function()
	{	
		$('#imSendButton').attr('disabled', true);
		$.ajax({
			url: '/passport/login.php',
			dataType: 'json',
			data: {
				action:		'login_ajax',
				email:		$('#ajax_email').val(),
				password:	$('#ajax_password').val(),
				remember:	$('#ajax_remember').get(0).checked ? 1 : 0,
				to:			mod_passport_im_loader.params.user_id,
				m:			mod_passport_im_loader.params.obj, 
				type:		mod_passport_im_loader.params.type,
				url:		mod_passport_im_loader.params.url,
				title:		mod_passport_im_loader.params.title,
				rand:		Math.random() 
			},
			success: function(data){mod_passport_im_loader.success_loaded(data, mod_passport_im_loader.params.type, mod_passport_im_loader.params.url, mod_passport_im_loader.params.title, mod_passport_im_loader.params.reload)},
			type: 'POST'});	
	},
	
	rendered: function()
	{
		var h = $.nyroModalSize.height;
		var hc = $('#im_message_text').height();
		var hc2 = $('#im_form_container').height();

		//alert('wrapper '+h+' im_message_text '+hc+' im_form_container '+hc2);
		if(hc2 > h)
		{
			$('#im_message_text').css({
				overflow: 'auto',
				height: (hc - (hc2 - h)) + 'px'
			});
		}
		$('#im_form_container').css({
			opacity: 1,
			filter: 'alpha(opacity=100)'
		});
		mod_passport_im_loader.focusEditor();
		

	},
	
	black_list: function(user_id, type)
	{
		$.ajax({
			url: '/passport/',
			dataType: 'json',
			data: {
				action:	'black_list',
				user_id: user_id,
				type: type
			},
			success: function(data)
			{
				if (data.status == 'ok')
				{
					$("#blacklist_"+user_id).hide();
					$("#blacklist_del_"+user_id).show();
				}
				else if (data.status == 'ok_add')
				{
					$(".blacklist_"+user_id).hide();
					$(".blacklist_add_"+user_id).show();
				}
				else if (data.status == 'error')
				{
					alert('Ошибка удаления пользователя из черного списка.');
				}
			},
			type: 'POST'
		});
	}
}
