/** 
 * jQuery plugin JUser
 *
 *  http://moda.ru/
 *
 *  jQuery required. Download it at http://jquery.com/
 *
 */

(function(jQuery) {

	jQuery.fn.juser = function(options) {
		
		if(this.length == 0) 
			return this;
		
		if(typeof arguments[0] == 'string') {
			if(this.length > 1) {
				var args = arguments;
				return this.each(function() {
					$.fn.jdialog.apply($(this), args);
    			});
			};
			
			$.fn.jdialog[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			
			return this;
		};
		
		// Настройки по умолчанию
		var defaults = {
			speed: 300,
			delay: 300,
			lang_info: 'Страница пользователя',
			lang_message: 'Написать сообщение',
			lang_photo: 'Личные фотографии',
			lang_album: 'Альбомы',
			lang_friend_add: 'Добавить в друзья',
			lang_friend_del: 'Удалить из друзей',
			lang_gift: 'Подарить подарок',
			lang_blog: 'Блог пользователя',
			lang_journal: 'Журнал пользователя',
			lang_info_my: 'Моя страница',
			lang_message_my: 'Мои сообщения',
			lang_photo_my: 'Мои фотографии',
			lang_album_my: 'Мои альбомы',
			lang_friend_my: 'Мои друзья',
			lang_gift_my: 'Мои подарки',
			lang_blog_my: 'Мой блог',
			lang_journal_my: 'Мой журнал',
			onComplete: function() {}
		};
		
		var options = $.extend(defaults, options);
		
		var self = this;
		var $this = $(this);
		
		var items = {};
		var ids = [];
		var tip = null;
		var tpl = null;
		
		/**
		 * Инициализация плагина
		 */
		init = function() {
			
			$.each(self, function(key, val) {
				
				var id = parseInt($(val).attr('user'));
				
				if (id) {
					items[key] = {};
					items[key].id = id;
					items[key].el = val;
					items[key].hasImg = $(this).children('img').length;
					
					ids.push(id);
					
					$(val).css({
						'cursor': 'pointer'
					}).click(function() {
						document.location.href = '/user/view/' + id + '/'
					});
				}
			});
			
			if (ids.length) {
				load();
			}
		}
		
		/**
		 * Инициализация события
		 * @param {Object} obj
		 */
		initEvent = function(obj) {
			$(obj.el).hover(
				function() {
					options.obj = obj;
					tip.appendTo($(obj.el));
					setUTip(obj);
					startUTimer();
				},
				function() {
					stopUTimer();
					hideUTip();
					tip.remove();
				}
			);
		}
		
		/**
		 * Инициализация всплывающего меню
		 */
		initTip = function() {
			tip = '<div id="usertip">' + 
			'<div class="frame">' + 
			'<div class="frame_tail_leftm"></div>' +
			'<table border="0"><tbody>' +
			'<tr><td class="frame_tl"></td><td class="frame_tc"></td><td class="frame_tr"></td></tr>' +
			'<tr><td class="frame_ml"></td><td class="frame_mc"></td><td class="frame_mr"></td></tr>' +
			'<tr><td class="frame_bl"></td><td class="frame_bc"></td><td class="frame_br"></td></tr>' +
			'</tbody></table></div><div class="clear"></div></div>';
			
			tip = $(tip).appendTo($('body'));
		}
		
		/**
		 * Инициализация шаблона
		 */
		initTpl = function() {
			tpl = '' +
			'<ul>' +
			'<li class="u_login"></li>' +
			'<li class="u_avatar"><img src="" /></li>' +  
			'<li class="u_message"><a href="#"></a></li>' +
			'<li class="u_photo"><a href="#"></a></li>' +
			'<li class="u_album"><a href="#"></a></li>' +
			'<li class="u_friend">' + 
				'<a add="#" href="javascript:void(0);">' + options.lang_friend_add + '</a>' + 
				'<a del="#" href="javascript:void(0);">' + options.lang_friend_del + '</a>' +
				'<a my="#" href="javascript:void(0);">' + options.lang_friend_my + '</a>' +
			'</li>' +
			'<li class="u_gift"><a href="#"></a></li>' +
			'<li class="u_info"><a href="#"></a></li>' +
			'<li class="u_blog"><a href="#"></a></li>' +
			'<li class="u_journal"><a href="#"></a></li>' +
			'</ul>';
			
			tpl = $(tpl).appendTo(tip.find('td.frame_mc'));
			
			return tpl;
		}
		
		/**
		 * Обработка шаблона
		 * @param {Object} obj
		 */
		parseTpl = function(obj) {
			
			tpl.find('li.u_login').html(obj.info.user_login);
			tpl.find('li.u_message a').attr('href', '/message/read/' + obj.info.user_id + '/').html(options.lang_message);
			tpl.find('li.u_photo a').attr('href', '/user/photo/' + obj.info.user_id + '/').html(options.lang_photo);
			tpl.find('li.u_album a').attr('href', '/album/list/' + obj.info.user_id + '/').html(options.lang_album);
			tpl.find('li.u_gift a').attr('href', '/user/gift/' + obj.info.user_id + '/').html(options.lang_gift);
			tpl.find('li.u_info a').attr('href', '/user/view/' + obj.info.user_id + '/').html(options.lang_info);
			tpl.find('li.u_blog a').attr('href', '/blog/list/' + obj.info.user_id + '/').html(options.lang_blog);
			tpl.find('li.u_journal a').attr('href', '/journal/list/' + obj.info.user_id + '/').html(options.lang_journal);
			tpl.find('li.u_friend a[my]').hide();
			tpl.find('li.u_friend a[add]').attr('add', obj.info.user_id);
			tpl.find('li.u_friend a[del]').attr('del', obj.info.user_id);
			
			if(!obj.info.user_auth) {
				tpl.find('li.u_message').hide();
				tpl.find('li.u_photo').hide();
				tpl.find('li.u_album').hide();
				tpl.find('li.u_gift').hide();
				tpl.find('li.u_info').hide();
				tpl.find('li.u_blog').attr('class', 'u_border');
			}
			
			if (obj.info.friend == 'no' && !obj.info.user_owner) {
				tpl.find('li.u_friend a[add]').show();
				tpl.find('li.u_friend a[del]').hide();
			}
			else if(obj.info.friend == 'yes' && !obj.info.user_owner) {
				tpl.find('li.u_friend a[add]').hide();
				tpl.find('li.u_friend a[del]').show();
			}
			else {
				tpl.find('li.u_friend a[add]').hide();
				tpl.find('li.u_friend a[del]').hide();
			}
			
			if(!obj.hasImg) {
				tpl.find('li.u_avatar img').
					attr('src', obj.info.user_avatar).
					click(function(){
						document.location.href = '/user/view/' + obj.info.user_id + '/'
					}).css({
						'cursor': 'pointer'
					});
				
				tpl.find('li.u_avatar').show();
			}
			else {
				tpl.find('li.u_avatar').hide();
			}
			
			Cufon.replace('li.u_login');
			
			options.onComplete();
		}
		
		/**
		 * Обработка шаблона
		 * @param {Object} obj
		 */
		parseTplMy = function(obj) {
		
			tpl.find('li.u_login').html(obj.info.user_login);
			tpl.find('li.u_message a').attr('href', '/message/read/' + obj.info.user_id + '/').html(options.lang_message_my);
			tpl.find('li.u_photo a').attr('href', '/user/photo/' + obj.info.user_id + '/').html(options.lang_photo_my);
			tpl.find('li.u_album a').attr('href', '/album/list/' + obj.info.user_id + '/').html(options.lang_album_my);
			tpl.find('li.u_gift a').attr('href', '/user/gifts/' + obj.info.user_id + '/').html(options.lang_gift_my);
			tpl.find('li.u_info a').attr('href', '/user/view/' + obj.info.user_id + '/').html(options.lang_info_my);
			tpl.find('li.u_blog a').attr('href', '/blog/list/' + obj.info.user_id + '/').html(options.lang_blog_my);
			tpl.find('li.u_journal a').attr('href', '/journal/list/' + obj.info.user_id + '/').html(options.lang_journal_my);
			tpl.find('li.u_friend a[my]').attr('href', '/user/friends/' + obj.info.user_id + '/').show();
			tpl.find('li.u_friend a[add]').hide();
			tpl.find('li.u_friend a[del]').hide();
			
			if(!obj.hasImg) {
				tpl.find('li.u_avatar img').
					attr('src', obj.info.user_avatar).
					click(function(){
						document.location.href = '/user/view/' + obj.info.user_id + '/'
					}).css({
						'cursor': 'pointer'
					});
				
				tpl.find('li.u_avatar').show();
			}
			else {
				tpl.find('li.u_avatar').hide();
			}
			
			Cufon.replace('li.u_login');
			
			options.onComplete();
		}
		
		/**
		 * Установка положения и значений меню
		 * @param {Object} obj
		 */
		setUTip = function(obj) {
			var offset = $(obj.el).parent().offset();
			var top = offset.top - 20;
			var left = offset.left + $(obj.el).width() + 30;
			
			if(!obj.hasImg) {
				top -= 9;
				left += 8;
			}
			
			if(obj.info.user_owner)
				parseTplMy(obj);
			else
				parseTpl(obj);
			
			if($.browser.msie || $.browser.opera) {
				
				if(!obj.hasImg) {
					top += 8;
					left += 0;
				}
			}
			
			tip.css({
				top: top,
				left: left
			})
		}
		
		hideUTip = function() {
			tip.hide();
		}
		
		/**
		 * Отображение меню
		 */
		showUTip = function() {
			stopUTimer();
			tip.animate({
				"left": "-=40px", 
				"opacity": "toggle"
			}, options.speed);
		}
		
		/**
		 * Загрузка данных с сервера
		 */
		load = function() {
			$.post('/user/handlerInfo', {
			 	users: $.toJSON(ids)
			}, 
			function(response) {
				if(response) {
					$.each(items, function(key, val) {
						items[key].info = response[val.id];
						initEvent(items[key]);
					});
					
					initTip();
					initTpl();
				}
			}, 
			"json");
		}
		
		/**
		 * Запуск таймера
		 */
		startUTimer = function() {
			$this.showUTipTimer = setInterval('showUTip()', options.delay);
		}
		
		/**
		 * Остановка таймера
		 */
		stopUTimer = function() {
			clearInterval($this.showUTipTimer);
		}
		
		/**
		 * Запуск
		 */ 
		init();
	}
	
	$.extend($.fn.juser, {
		friend_change: function() {
		}
	});
		
})(jQuery);