/**
 * @author Melnaron
 * 
 * AJAX функции
 */

$.ajaxSetup({
	type: 'post',
	dataType: 'json'
});

/**
 * Login
 */
function ajaxLogin() {
	var email    = $('#loginForm .inpEmail').val();
	var password = $('#loginForm .inpPassword').val();
	$.ajax({
		url: '/ajax/login/',
		data: 'email='+email+'&password='+password,
		error: function(xhr, st) {
			alert(st+':\n\n'+xhr.responseText);
		},
		success: function(data) {
			if (data.success) {
				$('.darkening, #loginForm, #regForm').hide();
				document.location = '/';
			} else {
				$('#loginForm input').parent().parent().removeClass('error');
				var error_text = '';
				for (var i = 0; i < data.errors.length; i++) {
					error_text += '<div>'+data.errors[i].text+'</div>';
					$('#loginForm .inp'+data.errors[i].inp).parent().parent().addClass('error');
				}
				$('#loginForm .error_text').html(error_text);
			}
		}
	});
}

/**
 * Registration
 */
function ajaxReg() {
	var email     = $('#regForm .inpEmail').val();
	var password  = $('#regForm .inpPassword').val();
	var passwordr = $('#regForm .inpPasswordR').val();
	var name      = $('#regForm .inpName').val();
	var lastname  = $('#regForm .inpLastname').val();
	$.ajax({
		url: '/ajax/reg/',
		data: 'email='+email+'&password='+password+'&passwordr='+passwordr+'&name='+name+'&lastname='+lastname,
		error: function(xhr, st) {
			alert(st+':\n\n'+xhr.responseText);
		},
		success: function(data) {
			if (data.success) {
				$('.darkening, #loginForm, #regForm').hide();
				alert(
					'Регистрация успешно завершена.\n\n'+
					'Теперь вы должны дождаться пока вашу учетную запись '+
					'активирует администратор, после чего вы сможете войти в систему.'
				);
			} else {
				$('#regForm input').parent().parent().removeClass('error');
				var error_text = '';
				for (var i = 0; i < data.errors.length; i++) {
					error_text += '<div>'+data.errors[i].text+'</div>';
					$('#regForm .inp'+data.errors[i].inp).parent().parent().addClass('error');
				}
				$('#regForm .error_text').html(error_text);
			}
		}
	});
}

/**
 * Открытие диалога редактирования фотографии
 */
function openPhotoEdit(id, single) {
	$('#photo-edit-id').val(id);
	if (single) {
		$('#photo-edit-name').val($('.single_foto img').attr('alt'));
		$('#photo-edit-desc').val($('.single_foto img').attr('desc'));
		$('#photo-edit-tags').val($('.single_foto img').attr('tags'));
	} else {
		$('#photo-edit-name').val($('#photo-'+id+' .photo-thumb').attr('name'));
		$('#photo-edit-desc').val($('#photo-'+id+' .photo-thumb').attr('tip'));
		$('#photo-edit-tags').val($('#photo-'+id+' .photo-thumb').attr('tags'));
	}
	$('#dialog-photo-edit').popup();
}

/**
 * Редактирование фотографии
 */
function ajaxPhotoEdit(single) {
	var id   = $('#photo-edit-id').val();
	var name = $('#photo-edit-name').val();
	var desc = $('#photo-edit-desc').val();
	var tags = $('#photo-edit-tags').val();
	$('#dialog-photo-edit').find('.dialog-buttons').hide().end().find('.dialog-status').show();
	$.ajax({
		url: '/ajax/photo/edit/',
		data: 'id='+id+'&name='+name+'&desc='+desc+'&tags='+tags,
		success: function(data) {
			if (data.success) {
				if (single) {
					$('.block2 h1').text(name);
					$('.single_foto img').attr('alt', name).attr('desc', desc).attr('tags', tags);
					$('.info_foto .info_name').text(name);
					$('.info_foto .info_desc').text(desc || '-');
					$('.info_foto .info_tags').html(data.tags || '-');
				} else {
					$('#photo-'+id+' .photo-thumb').attr('name', name).attr('tags', tags).tip(desc);
					$('#photo-'+id+' .photo-name').html(name);
				}
				$('#dialog-photo-edit').hide();
			} else {
				alert(data.message);
			}
		},
		complete: function() {
			$('#dialog-photo-edit').find('.dialog-status').hide().end().find('.dialog-buttons').show();
		}
	});
}

/**
 * Удаление фотографии
 */
function ajaxPhotoDelete(id, single) {
	if (! confirm('Вы точно хотите удалить выбранную фотографию?')) {
		return;
	}
	$.ajax({
		url: '/ajax/photo/delete/',
		data: 'id='+id,
		success: function(data) {
			if (data.success) {
				if (single) {
					window.history.go(-1);
				} else {
					$('#photo-'+id).fadeOut('fast');
				}
			} else {
				alert(data.message);
			}
		}
	});
}

/**
 * Добавление фотографии в избранное
 */
function ajaxPhotoAddFavorite(id, single) {
	$.ajax({
		url: '/ajax/photo/addfavorite/',
		data: 'id='+id,
		success: function(data) {
			if (data.success) {
				if (single) {
					$('a.fav span').text('Удалить из избранного');
					$('a.fav')
						.attr('class', 'fav_add')
						.attr('href', 'javascript:void(ajaxPhotoDeleteFavorite('+id+', true));')
					;
				} else {
					$('#photo-'+id+' li.favorite')
						.attr('class', 'favorite_add')
						.find('a')
						.attr('href', 'javascript:void(ajaxPhotoDeleteFavorite('+id+'));')
						.text('Удалить из избранного')
						.tip('Удалить из избранного')
					;
				}
			} else {
				alert(data.message);
			}
		}
	});
}

/**
 * Удаление фотографии из избранного
 */
function ajaxPhotoDeleteFavorite(id, single) {
	$.ajax({
		url: '/ajax/photo/deletefavorite/',
		data: 'id='+id,
		success: function(data) {
			if (data.success) {
				if (single) {
					$('a.fav_add span').text('Добавить в избранное');
					$('a.fav_add')
						.attr('class', 'fav')
						.attr('href', 'javascript:void(ajaxPhotoAddFavorite('+id+', true));')
					;
				} else {
					$('#photo-'+id+' li.favorite_add')
						.attr('class', 'favorite')
						.find('a')
						.attr('href', 'javascript:void(ajaxPhotoAddFavorite('+id+'));')
						.text('Добавить в избранное')
						.tip('Добавить в избранное')
					;
				}
			} else {
				alert(data.message);
			}
		}
	});
}

/**
 * Добавление фотографии в корзину
 */
function ajaxPhotoAddToCart(id, single) {
	$.ajax({
		url: '/ajax/photo/addtocart/',
		data: 'id='+id,
		success: function(data) {
			if (data.success) {
				if (single) {
					$('.block3 .buy').hide();
					$('.block3 .status_ok').html('Фотография добавлена в <a href="/mycart/">корзину</a>.').show();
				} else {
					$('#photo-'+id+' li.basket')
						.attr('class', 'basket_add')
						.find('a')
						.attr('href', 'javascript:void(ajaxPhotoDeleteFromCart('+id+'));')
						.tip('Удалить из корзины')
					;
				}
				$('li.basket > a').text('Корзина ('+data.incart+')');
			} else {
				alert(data.message);
			}
		}
	});
}

/**
 * Удаление фотографии из корзины
 */
function ajaxPhotoDeleteFromCart(id, mycart) {
	$.ajax({
		url: '/ajax/photo/deletefromcart/',
		data: 'id='+id,
		success: function(data) {
			if (data.success) {
				if (mycart) {
					if (data.totalprice >= 0) {
						$('.totalprice').text(data.totalprice);
					} else {
						$('.totalprice').text('0');
						document.location = '/mycart/';
					}
					$('#photo-'+id).slideUp();
				} else {
					$('#photo-'+id+' li.basket_add')
						.attr('class', 'basket')
						.find('a')
						.attr('href', 'javascript:void(ajaxPhotoAddToCart('+id+'));')
						.tip('Добавить в корзину')
					;
				}
				if (data.incart) {
					$('li.basket > a').text('Корзина ('+data.incart+')');
				} else {
					$('li.basket > a').text('Корзина');
				}
			} else {
				alert(data.message);
			}
		}
	});
}

/**
 * Обновление фотографии в корзине
 */
function ajaxPhotoUpdateInCart(id, data) {
	$.ajax({
		url: '/ajax/photo/updateincart/',
		data: 'id='+id+'&data='+data,
		success: function(data) {
			if (data.success) {
				if (data.totalprice >= 0) {
					$('.totalprice').text(data.totalprice);
				} else {
					$('.totalprice').text('0');
					document.location = '/mycart/';
				}
				$('#photo-'+id+' .price').text(data.price);
			} else {
				alert(data.message);
			}
		}
	});
}

/**
 * Установка рейтинга фотографии
 */
function ajaxPhotoSetRating(id, rating) {
	$.ajax({
		url: '/ajax/photo/setrating/',
		data: 'id='+id+'&rating='+rating,
		success: function(data) {
			if (data.success) {
				$('div.rating .lbl').html('Спасибо за вашу оценку.');
				$('div.rating ul').addClass('mine');
				//$('div.rating ul li.star a').attr('href', 'javascript:;');
				$('div.rating ul li.current-rating').css('width', data.rating+'%');
			} else {
				//alert(data.message);
				$('div.rating .lbl').html(data.message);
			}
		}
	});
}

