/**
 * Глобальные переменные и функции проекта
 */
var Love = {
	user: -1,
	msgUser: -1,
	hideDivs: false,
	isiOS: false,
	token: '',

	/**
	 * Инициализация
	 */
	init: function()
	{
		url = '/ajax/';
		if (typeof this.token !== 'undefiend' && this.token !== '') {
			url = url + '?token=' + this.token
		}

		this.Rpc = jQuery.Ngs.JsonRpc({url: url});
		this.Messanger = new this._Messanger();

		jQuery('body').bind('click', function() { Love.closePopups() });

		jQuery('a.city-selector').
			bind('click', function() { Love.popup('city'); return false; }).
			bind('mouseover', function() { Love.hideDivs = false; }).
			bind('mouseout', function() { Love.hideDivs = true; });

		jQuery('#city').
			bind('mouseover', function() { Love.hideDivs = false; }).
			bind('mouseout', function() { Love.hideDivs = true; });

		iPhone = (navigator.userAgent.indexOf('iPhone') != -1);
		iPod = (navigator.userAgent.indexOf('iPod') != -1);
		iPad = (navigator.userAgent.indexOf('iPad') != -1);
		this.isiOS = iPhone || iPod || iPad;
	},


	initNotes: function()
	{
		this.Notes = new this._Notes();
	},

	/**
	 * Функция, скрывающая все всплывающие слои по клику на БОДИ
	 */
	closePopups: function()
	{
		if (this.hideDivs) {
			$('div.popdivs').hide();
		}
	},


	/**
	 * Функция, показывающая - скрывающия всплывающие слои.
	 */
	popup: function(item)
	{
		if ($('#' + item).css('display') != 'none') {
			$('#' + item).hide();
		} else {
			$('div.popdivs').hide();
			$('#' + item).show();
		}
	},


	/**
	 * Функция, скрывающая все всплывающие слои по клику на БОДИ
	 */
	getEditor: function(options)
	{
		if (this.isiOS) {
			jQuery('div.list-messages').css('height', 'auto');
			return false;
		}
		this.Editor = new this._Editor(options);
		this.Editor.attach();
		return this.Editor;
	},	

	/**
	 * Переменные месенджера
	 */
	_Messanger: function()
	{
		this.msgDiv = '#list-messages .mes';
		this.inbox = '#inbox';
		this.counter = '#new_messages';

		var height = jQuery('div.mes').height();
		if (height > 0) {
			document.getElementById('list-messages').scrollTop = height;

			/**
			 * Вешаем обработчики на иконку спама
			 */
			jQuery('.spam-icon').bind('click', function(e) {
				Love.Messanger.spam(e.target.parentNode.id.substring(4));
			}).bind('mouseover', function() {
				$(this).addClass('spam-icon-active');
			}).bind('mouseout', function() {
				$(this).removeClass('spam-icon-active');
			});

			/**
			 * Вешаем обработчики на иконку спама
			 */
			jQuery('form#write').bind('keypress', function(e) {
				if ((e.ctrlKey) && ((e.keyCode == 0xA) || (e.keyCode == 0xD))) {
					doCheck();
					jQuery('form#write').send.click();
					return false;
				}
			});
		}
			jQuery('#first').bind('click', function(e) {
				Love.Messanger.checkAll(this.form, 0);
			});

			jQuery('#last').bind('click', function(e) {
				Love.Messanger.checkAll(this.form, 1);
			});

			jQuery('#select-all-btn').bind('click', function(e) {
				Love.Messanger.selectAll(this.form);
			});



		/**
		 * Включаем проверку новых сообщений
		 */
		if (Love.user > 0) {
			setInterval(function() {
				Love.Messanger.pingCount()
			}, 30000);
		}

		/**
		 * Включаем проверку новых сообщений
		 */
		if (Love.user > 0 && Love.msgUser > 0) {
			setInterval(function() {
				Love.Messanger.pingMsg()
			}, 30000);
		}
	},


	/**
	 * Переменные для комментариев
	 */
	_Notes: function()
	{
		this.smilesList = ['ooo', 'mad', 'cool', 'smile', 'frown', 'blush', 'crazy', 'laugh', 'shocked', 'smirk', 'confused',
		    		   'grin', 'wink', 'tongue', 'rose', 'kiss', 'bottle', 'die', 'eek', 'fist', 'heart', 'live', 'respect', 'agree',
		    		   'crazy2', 'cry', 'flowers', 'joy', 'lick', 'mad2', 'no', 'pester', 'popcorn', 'sad2', 'shuffle', 'str',
		    		   'susel', 'umn', 'wall', 'wow', 'fuck', 'sorrow', 'sad', 'heart2', 'tease', 'love', 'boogi'];

		jQuery('a.smile-link').click(function(e) {
			Love.Notes.smiles(e);
			return false;
		});

		jQuery('.link-answer a').click(function(e) {
			Love.Notes.addComment(e);
			return false;
		});

		jQuery('.comment a.admin-link').click(function(e) {
			Love.Notes.action(e);
			return false;
		});

		jQuery('.comment-form form').submit(function(e) {

			if(Love.Notes.notEmpty(e)) {
				return true;
			} else {
				return false;
			}
			
		});	


        jQuery('.add-note-form form').submit(function(e) {
			return Love.Notes.notEmpty(e);
		});

	}
}

/**
 * Реализация месенджера
 */
Love._Messanger.prototype = {
	/**
	 * Проверка новых сообщений
	 */
	pingCount: function()
	{
		var messages = Love.Rpc.countNewMessages();
		if (typeof messages !== 'number') {
			return;
		}

		if (messages > 0) {
			jQuery(this.inbox).addClass('active');
			jQuery(this.inbox).addClass('new-pm');
			jQuery(this.counter).html(messages).addClass('bold');
		} else if (messages == 0) {
			jQuery(this.inbox).removeClass('active');
			jQuery(this.inbox).removeClass('new-pm');
			jQuery(this.counter).html(messages).removeClass('bold');
			return;
		}
	},


	/**
	 * Проверка новых сообщений
	 */
	pingMsg: function()
	{
		var node = jQuery(this.msgDiv);
		var height = node.height();
		if (node.length < 1) {
			return;
		}

		var messages = Love.Rpc.getNewMessages(Love.msgUser);
		if (messages == null) {
			return;
		}

		node.html(node.html() + messages);
		node.scrollTop = height;

		var children = node[0].childNodes
		if (children.length > 15) {
			var len = children.length - 15;
			for(var i=0;i<len; i++) {
		         node[0].removeChild(children[i])
		    }
		}
	},


	/**
	 * Пожаловаться на спам
	 *
	 * @param {string} message ид сообщения
	 */
	spam: function(message)
	{
		if (message.length != 24) {
			return;
		}

		if (Love.Rpc.spam(message)) {
			alert('Извещение модератору об этом письме отправлено');
			jQuery('#spam' + message).empty();
		} else {
			alert('Ошибка!');
		}
	},

	checkAll: function(f, controlCheck)
	{
		if (controlCheck == 0) {
			indexControl = 'last';
		} else {
			indexControl = 'first';
	 	}

	 	if (document.getElementById(indexControl).checked == true) {
	 		check = false;
	 	} else {
	 		check = true;
	 	}

	 	l = f.length;
	 	for (i=1;i<l;i++) {
	 		if (f.elements[i].type == "checkbox")
	 			f.elements[i].checked = check;
	 	}
	 	return true;
	},


	selectAll: function(f)
	{
		l = f.length;
		for (i=0;i<l;i++) {
			if (f.elements[i].type == "checkbox")
				f.elements[i].checked = true;
		}
		return true;
	}
}

/**
 * Реализация комментариев
 */
Love._Notes.prototype = {
	action: function(e)
	{
		id = e.target.parentNode.id.substr(6);		
		action = e.target.id.substr(7 + id.length);
		check = true;

		if (action == 'del' || action == 'del-comment') {
			//check = confirm('Вы уверены?');
			reason = prompt('Укажите причину удаления');
			if (reason == null) {
				return false;
			}
			
			var ptrn = /\s*((\S+\s*)*)/;
			reason = reason.replace(ptrn, "$1")
			var ptrn1 = /((\s*\S+)*)\s*/;
			reason = reason.replace(ptrn1, "$1");
			if (reason == '') {
				alert('Не указана причина удаления.');
				check = false;
			} else {
				document.notes.reason.value = reason;
				check = true;
			}
		}
		
		if (check == true) {
			document.notes.action.value = action;
			document.notes.id.value = id;
			document.notes.submit();
		}
	},

	/**
	 * Добавляет смайлик в указанный элемент
	 */
	addSmile: function(smile, id)
	{
		document.getElementById(id).focus();
		document.getElementById(id).value += ' :::' + smile + '::: ';
		return true;
	},

	/**
	 * Показать или скрыть смайлики
	 *
	 * @param note ид заметки
	 * @param reply ответ на комментарий
	 */
	smiles: function(e)
	{
		var id = e.target.id.substr(6).substr(0, e.target.id.substr(6).length - 5);
		if (jQuery('#reply-' + id + '-smiles').css('display') == 'none') {
			if (jQuery('#reply-' + id + '-smiles').html() == '') {
				jQuery('#reply-' + id + '-smiles').html(this._addSmiles('reply-' + id + '-text'));
				jQuery('#reply-' + id + '-smiles').css('width', '550px');
			}
			jQuery('#reply-' + id + '-smiles').show();
			jQuery('#reply-' + id + '-link').html('Скрыть смайлики');
		} else {
			jQuery('#reply-' + id + '-smiles').hide();
			jQuery('#reply-' + id + '-link').html('Смайлики');
		}
		return false;
	},

	/**
	 * Проверяет что элемент с переданным ид не пустой
	 *
	 * @param id ид элемента для проверки
	 */
	notEmpty: function(e)
	{
        if (jQuery('textarea', e.target.parentNode).val().replace(/^\s+|\s+$/g, '') == '') {
			alert ('Тело письма не может быть пустым.');
			return false;
		}
		return true;
	},

	/**
	 * Показывает форму добавления комментариев
	 * @param note ид заметки
	 * @param reply ответ на комментарий
	 */
	addComment: function(e)
	{
		jQuery('#reply-' + e.target.id.substr(5)).toggle();
	},

	/**
	 * Проверяет что элемент с переданным ид не пустой
	 *
	 * @param id ид элемента для проверки
	 */
	_addSmiles: function(id)
	{
		html = '';
		this.smilesList.forEach(function(name) {
			html += '<img src="/static/i/smile/' + name + '.gif" alt="" align="top" onclick="Love.Notes.addSmile(\'' + name + '\', \'' + id + '\'); return false;" style="cursor: pointer; margin: 4px;" />';
		});
		return html;
	}
}



/**
 * Инициализация всего
 */

jQuery(document).ready(function() { 
	Love.init();
//	$(document).pngFix();

	var advtop1 = jQuery("#advtop1").html();
	var advtop2 = jQuery("#advtop2").html();

	if ((advtop1 == '' || advtop1 == ' ') && (advtop2 == '' || advtop2 == ' ')) {
			jQuery("#advtop").css('display', 'none');
	} else {

		if (advtop1 == '' || advtop1 == ' ') {
			jQuery('#advtop1').css('display', 'none');
			jQuery('#advtop2').css('width', 'auto');
			jQuery('#advtopspace').css('display', 'none');

		}

		if (advtop2 == '' || advtop2 == ' ') {
			jQuery('#advtop2').css('display', 'none');
			jQuery('#advtop1').css('width', 'auto');
			jQuery('#advtopspace').css('display', 'none');

		}
	}

	/* Скрываем баннера в Правой колонке контента */

	var advright1 = jQuery("#advright1").html();
	var advright2 = jQuery("#advright2").html();
	var advright3 = jQuery("#advright3").html();

	if ((advright1 == '' || advright1 == ' ') && (advright2 == '' || advright2 == ' ') && (advright3 == '' || advright3 == ' ')) {
		jQuery("#right-blank-td").css('display', 'none');
		jQuery("#right-column").css('display', 'none');
	} else {

		if (advright1 == '' || advright1 == ' ') {
			jQuery('#advright1').css('display', 'none');
		}

		if (advright2 == '' || advright2 == ' ') {
			jQuery('#advright2').css('display', 'none');
		}

		if (advright3 == '' || advright3 == ' ') {
			jQuery('#advright3').css('display', 'none');
		}

	}
	
})

