var imId = 1;
var imTop = 0;

$(document).ready(function() {

    $(window).scroll(function () {
		if ($(window).scrollTop() > 220) var s = $(window).scrollTop(); else var s = 220;
		$('#floating').animate({top:s-210+"px" },{queue: false, duration: 350});
    });

	$('#colorPicker').farbtastic(
		function(color) {
			$('#colorField').val(color.replace('#', ''));
			$('#colorPickerButton').css({background:color});
		}
	);
	$('#colorPickerButton').css({background:'#'+$('#colorField').val()});

    //initUploader();

    $('#resultAva').resizable({
    	handles: 's',
    	maxHeight: 500
	});

	$('#avaConstructor').click(function(e) {
		if (e.target.id != 'colorPickerButton' && e.target.id != 'colorPicker') {
			$('#colorPicker').hide();
		}
	});
})

function getByUrl(url) {
	loadingToggle();
	$.ajax({
		url: '/ava/get_by_url', 
		data: { url: url },
		type: 'POST',
		dataType: 'html',
		success: function(data, status) {
	        $('#urlUploadedImg').html(data);
		}
	});
}

function vkActivate() {
	$('#vkActivateButton').val('загрузка...');
	$('#vkActivateButton').attr('disabled', true);
	$.ajax({
		url: '/ava/vk_activate', 
		type: 'POST',
		dataType: 'html',
		success: function(data, status) {
			$('#activateResult').html(data).slideDown();
			$('#vkActivateButton').val('Отправить 1 голос');
			$('#vkActivateButton').attr('disabled', false);
		}
	});	
}

function activateCode() {
	var code = $('#activate_code').val();
	if (code == '') {
		alert('Нужно ввести код');
	}
	else {
		$.ajax({
			url: '/ava/activate', 
			data: { code: code },
			type: 'POST',
			dataType: 'html',
			success: function(data, status) {
				$('#activateResult').html(data).slideDown();
			}
		});
	}
}

function resetAva() {
	if (confirm('Очистить область конструктора чтобы создать новый аватар?')) {
		$('.imHandler').each(function() {
			$(this).remove();
		});
	}
}

function saveAva() {
	var idata = '';
	var d = '';
	var ok = false;
	var t = '';
	var l = '';
	$('.imHandler').each(function() {
		ok = true;
		if ($(this).hasClass('ui-resizable')) {
			t = $(this).parent().css('top')
			l = $(this).parent().css('left')
		}
		else {
			t = $(this).css('top')
			l = $(this).css('left')			
		}
		d = $(this).attr('src') + '|' + t + '|' + l + '|' + $(this).css('width') + '|' + $(this).css('height');
		idata += d + ',';
	})
	if (ok) {
		$('#avaSaveButton').attr('disabled', true);
		$('#avaSaveButton').val('сохранение...');
		$.ajax({
			url: '/ava/save', 
			data: { idata: idata, height: $('#resultAva').css('height') },
			type: 'POST',
			dataType: 'html',
			success: function(data, status) {
				$('#receiver').html(data);
				$('#avaConstructor').hide();
				$('#receiver').slideDown();
				$('#avaSaveButton').val('Сохранить');
				$('#avaSaveButton').attr('disabled', false);
			}
		});
	}
	else {
		alert('Зачем тебе пустая аватара?');
	}
}

function closePreview() {
	$('#receiver').slideUp();
	$('#avaConstructor').slideDown();
}

function addCamPhoto() {
	loadingToggle();
	$.ajax({
		url: '/ava/add_cam_photo', 
		type: 'POST',
		dataType: 'html',
		success: function(data, status) {
	        $('#console').html(data);	        
		}
	});
}

function addPhoto(photo, w, h, addTop, noResize) {
	if ($('#loading').length && $('#loading').css('display')=='block') {
		loadingToggle(); 
	}

    $('#resultAva').append('<img src="'+photo+'" width="'+w+'" height="'+h+'" id="im'+imId+'" class="imHandler" />');

	if (!noResize) {
		$('#im'+imId).resizable({handles:'all', aspectRatio: true}).parent().draggable().css('position','absolute');
	}
	else {
		$('#im'+imId).draggable();
	}
	
	if (addTop) {
		if (noResize) {
			$('#im'+imId).css('top', imTop+'px');
		}
		else {
			$('#im'+imId).parent().css('top', imTop+'px');
		}
		if (addTop) imTop += 30;
    }
    else {
		$('#im'+imId).css('top', '0px');
    }

	imId++;

	//$('#im'+imId).css('z-index', 1);
    //$('#im'+imId).draggable();
    /*$('#im'+imId).dblclick(function() {
	$(this).css('z-index', parseInt($(this).css('z-index'))+500);
	alert($(this).css('z-index'));
    });*/
}

function initUploader() {
    $('#fileInput').uploadify({
		'uploader'  : '/js/upl/uploadify.swf',
		//'checkScript': '/ava/check_upload',
		'script'    : '/ava/upload',
		'cancelImg' : '/img/cancel.png',
		'auto'      : true,
		'folder'    : 'upload/tmp',
		//'buttonText': 'Загрузить файл',
		'buttonImg' : '/img/ava_upload_btn.png?1',
		'width'	    : 141,
		'height'    : 18,
		'wmode'	    : 'transparent',
		'scriptData': { one: 'two' },
		'multi'	    : false,
		'fileDesc'  : 'Изображения',
		'fileExt'   : '*.jpg;*. jpeg;*.gif;*.png',
		'sizeLimit' : 10*1024*1024,
		'onComplete': function(event, queueID, fileObj, response, data) {
			var respData = response.split(' ');
			if (respData[0] == 'ok') {
				addPhoto('/upload/tmp/'+respData[1]+'.jpg', respData[2], respData[3], true);
			}
			else {
				alert('Ошибка '+respData[1]);
			}
		}
    });
}

function setMasksCategory(category_id)
{
    $('.masksList').hide();
    $('#masks'+category_id).show();
}

function colorPicker() {
	var t = $('#colorPickerButton').offset();
	$('#colorPicker').css({top:t.top+14+'px',left:t.left-88+'px'});
	$('#colorPicker').toggle();
}

function fontsList() {
	$('#fontsList').toggle();
}

function setFont(font) {
	$('#font').val(font);
	$('#fontPreview').attr({src: 'data/fonts/'+font+'.gif'});
	$('#fontsList').hide();
}

function textAdd() {
	params = { color: $('#colorField').val(), font: $('#font').val(), text: $('#textt').val(), size: $('#fontSize').val() };
	$.ajax({
		url: '/ava/add_text',
		type: 'POST',
		dataType: 'html',
		data: params,
		success: function(data, status) {
			var respData = data.split(' ');
			if (respData[0] == 'ok') {
				addPhoto('/upload/tmp/'+respData[1]+'.png', respData[2], respData[3], false, true);
			}
		}
	});
}
