$.fn.isMouseOn = function(x, y) {
	var top = $(this).offset().top;
	var left = $(this).offset().left;
	
	if (x > left && x < left + $(this).outerWidth() && y > top && y < top + $(this).outerHeight()) {
		return true;
	} else {
		return false;
	}
};


function AJAXError(text)
{
	alert(text ? text : 'Ошибка AJAX-запроса. Действие не выполнено.');
}

function HTMLMessage(data)
{
	return $('<div>')
		.addClass('message')
		.append('<i class="corner tl"></i>')
		.append('<i class="corner tr"></i>')
		.append('<i class="corner br"></i>')
		.append('<i class="corner bl"></i>')
		.append(data);
}

function box(data, element)
{
	element = $(element);
	
	$('body > div.box').each(function() {
		$(this).fadeOut('fast', function() { $(this).hide(); });
	});
	
	var template = $('<div class="box" style="display:none;">'+
		'<table>'+
			'<tbody>'+
				'<tr class="top">'+
					'<td class="left" colspan="2"></td>'+
					'<td class="center"><div></div></td>'+
					'<td class="right" colspan="2"></td>'+
				'</tr>'+
				'<tr class="center">'+
					'<td class="left"></td>'+
					'<td class="left-white"></td>'+
					'<td class="content"></td>'+
					'<td class="right-white"></td>'+
					'<td class="right"></td>'+
				'</tr>'+
				'<tr class="bottom">'+
					'<td class="left" colspan="2"></td>'+
					'<td class="center"><div></div></td>'+
					'<td class="right" colspan="2"></td>'+
				'</tr>'+
				'<tr class="tail">'+
					'<td colspan="5">'+
						'<div></div>'+
					'</td>'+
				'</tr>'+
			'</tbody>'+
		'</table>'+
	'</div>');
	
	template.find('td.content').append(data);
	
	function hide()
	{
		template.fadeOut('fast', function() { $(this).hide(); });
	}
	
	template.click(hide);
	
	$(document.body).append(template);
	
	var elementOffset = element.offset();
	
	template.css({
		top: (elementOffset.top - template.outerHeight(true) - 5) + 'px',
		left: (elementOffset.left - 15) + 'px'
	});
	
	template.fadeIn('fast');
	
	setTimeout(hide, 3000);
}

// Dialogs
var Dialog = function(title, content, buttons)
{
	var __self = this;
	
	this.dialog = $('<div>', {id: 'dialog'}).addClass('dialog')
		.append(
			$('<div>').addClass('border')
			.append(
				$('<div>').addClass('body')
				.append(
					$('<div>').addClass('title')
						.append($('<a>', {href: '#'}).addClass('close').click(function() { __self.close(); return false; }).text('закрыть'))
						.append('<span>'+title+'</span>')
				)
				.append($('<div>').addClass('content').append(content))
			)
		);
	
	if(buttons && typeof buttons == 'boolean')
	{
		var button = $('<button>', {className: 'button-blue'})
			.append('<span>Закрыть</span>')
			.click(function() {
				__self.close();
			});
		this.dialog.find('.body').append($('<div>', {className: 'buttons'}).css('text-align', 'right').append(button));
	}
	else if(buttons && (typeof buttons == 'string' || typeof buttons == 'object'))
	{
		this.dialog.find('.body').append($('<div>', {className: 'buttons'}).css('text-align', 'right').append(buttons));
	}
	
	this.verticalAlign();
	
	$(window).resize(function() {
		__self.verticalAlign();
	});
};

Dialog.prototype = {
	dialog: null,
	
	onClose: function() {},
	
	show: function() {
		var __self = this;
		
		this.dialog
			.hide()
			.appendTo(document.body)
			.fadeIn('fast');
		
		this.verticalAlign();
	},
	
	close: function() {
		this.dialog.fadeOut('fast', function() { $(this).remove(); });
		
		this.onClose();
	},
	
	verticalAlign: function() {
		var positionTop = $(window).height()/2 - this.dialog.outerHeight()/2;
		
		if (positionTop >= 0)
		{
			this.dialog.css('top', positionTop+'px');
		}
		else
		{
			this.dialog.css('top', 0);
		}
	}
};

var ConfirmDialog = function(title, content, confirm, buttonText)
{
	var __self = this;
	
	var buttonOk = $('<button>', {className: 'button-orange', id: 'confirm_dialog_button'})
		.append('<span>'+(buttonText || 'Да')+'</span>')
		.click(function() {
			if(__self.confirm())
			{
				__self.close();
			}
			$("#confirm_dialog_button").remove(); //anti double and triple click
		});
	
	var buttonCancel = $('<button>', {className: 'button-blue'})
		.append('<span>Отмена</span>').click(function() {
			__self.cancel();
		});
	
	var buttons = buttonOk.after(buttonCancel);
	
	this.dialog = new Dialog(title, content, buttons);
	
	buttonOk.focus();
	
	if(typeof confirm == 'function')
	{
		this.confirm = confirm;
	}
};

ConfirmDialog.prototype = {
	dialog: null,
	
	show: function() {
		this.dialog.show();
	},
	
	close: function() {
		this.dialog.close();
		this.dialog = null;
	},
	
	confirm: function() {},
	
	cancel: function()
	{
		this.dialog.close();
		this.dialog = null;
	}
};

var AlertDialog = function(title, content, buttonText)
{
	var __self = this;
	
	var button = $('<button>', {className: 'button-orange'})
		.append('<span>'+(buttonText || 'Закрыть')+'</span>')
		.click(function() {
			__self.close();
		});
	
	this.dialog = new Dialog(title, content, button);
	
	button.focus();
};

AlertDialog.prototype = {
	dialog: null,
	
	show: function() {
		this.dialog.show();
	},
	
	close: function() {
		this.dialog.close();
		this.dialog = null;
	},
	
	cancel: function()
	{
		this.dialog.close();
		this.dialog = null;
	}
};

var User = {
	menu : function() {
		var menu = $('#userbar_menu');
		
		var checkBodyClick = function(e) {
			if (!menu.isMouseOn(e.pageX, e.pageY)) {
				menu.hide();
				$(document).unbind('click', checkBodyClick);
			}
		};
		
		if (menu.css('display') == 'none') {
			menu.show();
			
			$(document).bind('click', checkBodyClick);
		}
	},
	
	helpDialog: function()
	{	
		var sendComplete = function(response)
		{
			if(response.success)
			{
				(new Dialog('Написать модератору', 'Спасибо! Ваше сообщение отправлено.', true)).show();
			}
			else
			{
				(new Dialog('Написать модератору', 'Ошибка при отправке сообщения.', true)).show();
			}
		};
		
		var confirmDialog = function()
		{				
			var problem = $('#problem').val();
			var matter = $('#matter').val();
			
			if(problem == '0')
			{
				$('#problem_error').text('выберите подходящую проблему').show();
				return false;
			}
			
			if(matter == '')
			{
				$('#problem_error').text('напишите описание проблемы').show();
				return false;
			}
			
			$.ajax({
				url: Config.baseURL+'helper/json_send_mail',
				data: {problem: problem, matter: matter},
				type: 'post',
				dataType: 'json',
				error: sendComplete,
				success: sendComplete
			});

			return true;
		};
		
		var prepareDialog = function()
		{
			var content = $('<div>').append('<p>Выберите подходящую проблему, о которой вы хотите сообщить<br /> модератору:</p>');
			
			var selection = $('<select>', {id: 'problem', name: 'problem'})
				.append($('<option>', {val: '0'}).text('выберите причину...'));
			
			selection.append($('<option>', {val: 'Вопрос по функционалу сайта'}).text('Не могу понять как это работает?'));
			selection.append($('<option>', {val: 'Ошибка на сайте!'}).text('Хочу сообщить об ошибке, которую я заметил.'));
			selection.append($('<option>', {val: 'Проблема с паролем, sms, SM!'}).text('Проблемы с паролем, sms, SM, помогите.'));
			selection.append($('<option>', {val: 'Нарушение правил на сайте'}).text('Сообщить о нарушении правил сайта.'));
			selection.append($('<option>', {val: 'Проблема у пользователя'}).text('Другое, суть изложу ниже'));
			
			content
				.append($('<p>').append(selection).append('<br /><span id="problem_error" style="display:none;color:#d01515"></span>'))
				.append('<p>Описание проблемы:</p><p id="matter_wrapper"><textarea name=matter" id="matter" style="width:80%;height:70px;"></textarea></p>');
			
			(new ConfirmDialog('Написать модератору', content, confirmDialog, 'Отправить')).show();
		};
		prepareDialog();
		
	},
	
	login: function()
	{
		var content = $('.login-form').clone().show();
		
		(new Dialog('Авторизация', content)).show();
	}
};

function voteUnverifiedError()
{
	(new Dialog('Голосование запрещено', 'Вы не можете проголосовать, т.к. Вы не подтвердили свой профиль.<br />Для подтверждения профиля перейдите в раздел <a href="'+Config.baseURL+'settings/mobile">настроек</a>.')).show();
};


/**
 * Example: inputPlaceholder( document.getElementById('my_input_element') )
 * @param {Element} input
 * @param {String} [color='#AAA']
 * @return {Element} input
 */
function inputPlaceholder (input, color) {

	if (!input) return null;

	// Do nothing if placeholder supported by the browser (Webkit, Firefox 3.7)
	if (input.placeholder && 'placeholder' in document.createElement(input.tagName)) return input;

	color = color || '#AAA';
	var default_color = input.style.color;
	var placeholder = input.getAttribute('placeholder');

	if (input.value === '' || input.value == placeholder) {
		input.value = placeholder;
		input.style.color = color;
		input.setAttribute('data-placeholder-visible', 'true');
	}

	var add_event = /*@cc_on'attachEvent'||@*/'addEventListener';

	input[add_event](/*@cc_on'on'+@*/'focus', function(){
	 input.style.color = default_color;
	 if (input.getAttribute('data-placeholder-visible')) {
		 input.setAttribute('data-placeholder-visible', '');
		 input.value = '';
	 }
	}, false);

	input[add_event](/*@cc_on'on'+@*/'blur', function(){
		if (input.value === '') {
			input.setAttribute('data-placeholder-visible', 'true');
			input.value = placeholder;
			input.style.color = color;
		} else {
			input.style.color = default_color;
			input.setAttribute('data-placeholder-visible', '');
		}
	}, false);

	input.form && input.form[add_event](/*@cc_on'on'+@*/'submit', function(){
		if (input.getAttribute('data-placeholder-visible')) {
			input.value = '';
		}
	}, false);

	return input;
}


function ctrlEnter(event, formElement)
{
	if((event.ctrlKey) && ((event.keyCode == 10)||(event.keyCode == 13)))
    {
		$(formElement).submit();
	}
};

jQuery.print = function(message, insertionType) {
  if (typeof(message) == 'object') {
    var string = '{\n',
        values = [],
        counter = 0;
    $.each(message, function(key, value) {
      if (value && value.nodeName) {
        var domnode = '&lt;' + value.nodeName.toLowerCase();
        domnode += value.className ? ' class="' + value.className + '"' : '';
        domnode += value.id ? ' id="' + value.id + '"' : '';
        domnode += '&gt;';
        value = domnode;
      }
      values[counter++] = key + ': ' + value;
    });
    string += values.join(',\n');
    string += '\n}';
    message = string;
  }
  
  alert(message);
};

var Geo = {
	switchRegion: function(regionId)
	{
		$.ajax({
			url: Config.baseURL+'geo/change_city',
			data: {new_region_id: regionId, space: 'global'},
			type: 'get',
			dataType: 'json',
			error: function() { AJAXError(); },
			success: function(response)
			{
				if (response.redirect){
					window.location.href = response.redirect;
				}
			}
		});
	},
	
	changeCity: function(regionAlias) 
	{        
	                 
		var prepareDialog = function() 
		{ 
			var content = $('<div style="margin: 10px;">').append('<img src="'+Config.baseURL+'media/production/images/cities/'+regionAlias+'.jpg" />'); 
	                         
			content
				.append($('<div>').append('<p>Выберите город:</p>'));
			
			$.ajax({ 
				url: Config.baseURL+'geo/get_city_list',
				data: {},
				type: 'post', 
				dataType: 'json', 
				error: function() { AJAXError(); }, 
				success: function(response)
				{	
					for (city_id in response.cities) 
					{
						content.append($('<div class="cities-list">').append('<a href="#" onclick="Geo.switchRegion('+city_id+'); return false;">' + response.cities[city_id] + '</a>'));
					}
				}
			});
						
			(new Dialog('Изменить город', content)).show(); 
		}; 
		prepareDialog(); 
	                 
	 }
};

var MinicontestPhotos = {
	selectAlbum: function(tag)
	{
		$.ajax({
			url: Config.baseURL+'photos/json_user_albums',
			type: 'get',
			dataType: 'json',
			error: function() { AJAXError(); }, 
			success: function(response)
			{
				var albums = $('<ul>');
				
				for(var i = 0; i < response.length; ++i)
				{
					$('<li>')
						.append($('<a>', {href: Config.baseURL+'photos/upload/'+response[i].id+'?tags='+tag}).text(response[i].title+' ('+response[i].count_photos+')'))
						.appendTo(albums);
				}
				
				var content = $('<div>')
					.append('<p><b>Выберите альбом для загрузки:</b></p>')
					.append(albums)
					.append('<p><br />Или создайте <a href="'+Config.baseURL+'photos/new">новый фотоальбом</a></p>');
				
				(new Dialog('Выберите альбом', content, true)).show(); 
			}
		});
	}
};

$(document).ready(function() {
	$('img').parent('a').css('text-decoration', 'none');
	
	$('#menu_contests .mainlink').mouseover(function() {
		$('#menu_contests .submenu').show();
	});
	
	$('#menu_contests .submenu').mouseleave(function() {
		$(this).hide();
	});
});
