var ImgAreaSelect = null;

$(document).ready(function(){
  $('.color-item').click(function(){
      if (!$(this).hasClass('active'))
      {
          $('.color-switcher .color-item').removeClass('active');
          $(this).addClass('active');
          $('.phone-bg').css('backgroundColor', ($('.color', this).css('backgroundColor')));
          $('.color-switcher input[type=hidden]').val($(this).attr('rel'));
      }
      return false;
  });
})

function initNotValidRegForm()
{
	var avatar_info = $('#UserProfile_avatar_info').val();
	if (avatar_info.length > 0)
	{
		var data = eval("("+avatar_info+")");
		$('.photo-crop').html('');
		$('.photo-preview').html('');
		$('.photo-crop').append('<img src="'+data.avatar.files.full+'" alt="" />');
		$('.photo-preview').append('<img src="'+data.avatar.files.full+'" alt="" />');
		$('.crop-popup .crop-popup-info').attr('x', data.avatar.area.x);
		$('.crop-popup .crop-popup-info').attr('y', data.avatar.area.y);
		$('.crop-popup .crop-popup-info').attr('pw', data.avatar.img.width);
		$('.crop-popup .crop-popup-info').attr('ph', data.avatar.img.height);
		if (data.avatar.img.width < data.avatar.img.height)
			$('.crop-popup .crop-popup-info').attr('w', data.avatar.img.width);
		else
			$('.crop-popup .crop-popup-info').attr('w', data.avatar.img.height);
		$('.crop-popup .crop-popup-info').attr('avatarId', data.id);
		$('.crop-popup .crop-popup-info').attr('location', data.avatar.files.full);

		$('.phone img').remove();
		$('.phone').append('<img src="'+data.file+'"/>');
		$('#avatar-edit-button').show();
	}
	closeCropDialog();
}

function UploadFile(_this, action)
{
    $(_this).parents('form').attr('action', action);
    $(_this).parents('form').attr('target', 'upload_target');
    $(_this).parents('form').attr('name', 'upload_file');
	$(_this).parents('form').find('.ajax-loader').show();
	$('.action-button').addClass('unclickable');
	$('.file').hide();
    $(_this).parents('form').submit();
    $(_this).parents('form').attr('action', '');
    $(_this).parents('form').attr('target', '');
    $(_this).parents('form').attr('name', '');
}

function UploadSetAvatarInfo(result)
{
	$('#UserProfile_avatar_info').val(result);
}

function UploadFinish(data)
{
	$('.photo-crop').html('');
	$('.photo-preview').html('');
	$('.photo-crop').append('<img src="'+data.url+'" alt="" />');
	$('.photo-preview').append('<img src="'+data.url+'" alt="" />');
	$('.crop-popup-info').attr('x', data.metrics.x);
	$('.crop-popup-info').attr('y', data.metrics.y);
	$('.crop-popup-info').attr('pw', data.metrics.w);
	$('.crop-popup-info').attr('ph', data.metrics.h);
	if (data.metrics.w < data.metrics.h)
		$('.crop-popup-info').attr('w', data.metrics.w);
	else
		$('.crop-popup-info').attr('w', data.metrics.h);
	$('.crop-popup-info').attr('avatarId', data.id);
	$('.crop-popup-info').attr('location', data.url);
	$('#avatar-edit-button').show();

	$('.phone img').remove();
	$('.phone').append('<img src="'+data.url+'"/>');

	$('.ajax-loader').hide();
	$('.action-button').removeClass('unclickable');
	$('.file').show();
	//$('#avatar-edit-button').click();
}

function UploadError(data)
{
	$("#dialog-error .text").empty().html(data);
	$("#dialog").dialog("destroy");

	$("#dialog-error").dialog({
		height: 150,
		width: 500,
		modal: true
	}).parent().find(".ui-dialog-titlebar-close").remove();

	if (jQuery.browser.msie)
		$('.ui-corner-all').corner();

	$('.ajax-loader').hide();
	$('.action-button').removeClass('unclickable');
	$('.file').show();
}

(function() {
	 jQuery.cropImg = null;
	 jQuery.avatarId = '';
	 jQuery.c = null;
	 jQuery.photoInfo = '';
})();

function EditAvatar()
{
	var info = $('.crop-popup-info');
	var popup_id = 'crop_avatar';
	jQuery.avatarId = info.attr('avatarId');
	jQuery.photoInfo = $(info);

	$("#dialog").dialog("destroy");

	$("#dialog-crop-avatar").dialog({
		height: 450,
		width: 550,
		modal: true,
		dragStart: function(event, ui) { if (ImgAreaSelect != null){ImgAreaSelect.setOptions({ hide: true }); ImgAreaSelect.update();} },
		dragStop: function(event, ui) { if (ImgAreaSelect != null){ImgAreaSelect.setOptions({ show: true }); ImgAreaSelect.update();} },
		beforeclose: function(event, ui) {destroyImgSelection();}
	}).parent().find(".ui-dialog-titlebar-close").remove();
	
	if (jQuery.browser.msie)
	{
		$('.ui-corner-all').corner();
	}

	_pw = parseInt(jQuery.photoInfo.attr('pw'));
	_ph = parseInt(jQuery.photoInfo.attr('ph'));
	_w = parseInt(jQuery.photoInfo.attr('w'));
	_x1 = (_pw > _ph)? (_pw - _w)/2 : 0;
	_y1 = (_pw < _ph)? (_ph - _w)/2 : 0;

	ImgAreaSelect = $('.photo-crop img').imgAreaSelect({
		instance: true,
		handles: true,
		x1: _x1, y1: _y1, x2: _w + _x1, y2: _w + _y1,
		aspectRatio: '1:1',
		onInit: preview,
		onSelectChange: preview
	});

	if (ImgAreaSelect != null)
		preview($('.photo-crop img'), ImgAreaSelect.getSelection());
}

function preview(img, selection) {
    var scaleX = 100 / (selection.width || 1);
    var scaleY = 100 / (selection.height || 1);

    $('.photo-preview img').css({
        width: Math.round(scaleX * jQuery.photoInfo.attr('pw')) + 'px',
        height: Math.round(scaleY * jQuery.photoInfo.attr('ph')) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
}

function destroyImgSelection()
{
	if (ImgAreaSelect != null)
	{
		 ImgAreaSelect.setOptions({ hide: true, remove: true });
         ImgAreaSelect.update();
	}
}

function closeCropDialog()
{
	destroyImgSelection();
	$('#dialog-crop-avatar').dialog('destroy');
}


function ajaxCropImg(action)
{
	coord = ImgAreaSelect.getSelection();
	if ((coord.x2-coord.x1) > 0)
	{
		var data = {
			  'img[location]': jQuery.photoInfo.attr('location'),
			  'img[id]': jQuery.avatarId,
			  'img[width]': jQuery.photoInfo.attr('pw'),
			  'img[height]': jQuery.photoInfo.attr('ph'),
			  'img_crop[x1]': coord.x1,
			  'img_crop[y1]': coord.y1,
			  'img_crop[w]': coord.x2-coord.x1,
			  'img_crop[h]': coord.y2-coord.y1
		};

		$.post(action, data, function(result){
			$('.phone img').remove();
			var data = eval("("+result+")");
			$('.phone').append('<img src="'+data.file+'"/>');
			$('#UserProfile_avatar_info').val(result);
			closeCropDialog();
		});
	}
}

function ajaxUploadCropAction(action, location, id, pw, ph, x, y, w, h)
{
	var data = {
		  'img[location]': location,
		  'img[id]': id,
		  'img[width]': pw,
		  'img[height]': ph,
		  'img_crop[x1]':x,
		  'img_crop[y1]': y,
		  'img_crop[w]': w,
		  'img_crop[h]': h
    };

	$.post(action, data, function(result){
		$('.phone img').remove();
		var data = eval("("+result+")");
		$('.phone').append('<img src="'+data.file+'"/>');
		$('#UserProfile_avatar_info').val(result);
	});
}

function deleteUser(action, id)
{
	if (confirm('Удалить пользователя?'))
	{
		$.post(action, {'id': id}, function(){
			$('#user_tr'+id).remove();
		});
	}
}

function openUserPhoneEditor(_button)
{
	$("#dialog").dialog("destroy");

	$("#user-phone-editor-dialog").dialog({
		height: 440,
		width: 800,
		modal: true,
		dragStart: function(event, ui) { $('.zero_clipbloard').remove(); },
		dragStop: function(event, ui) { initClipBoard(); },
		beforeclose: function(event, ui) {$('.zero_clipbloard').remove();}
	}).parent().find(".ui-dialog-titlebar-close").remove();

	if (jQuery.browser.msie)
	{
		$('.ui-corner-all').corner();
		$('.rounded').corner();
	}

	initClipBoard();
}

function uploadPhonePhoto(_this)
{
	$(_this).parents('.input-file-mask').find('input[type=text]').val($(_this).val());
	$(_this).parents('form').find('.ajax-loader').show();
	$('.action-button').addClass('unclickable');
	$('.file').hide();
	$(_this).parents('form').submit();
}

function uploadPhonePhotoFinish(data)
{
	$('.ajax-loader').hide();
	$('.action-button').removeClass('unclickable');
	$('.file').show();

	$('.phone-editor img').remove();
	$('.phone-editor').append('<img src="'+data.file+'" />');
	$('.phone-code textarea').val(data.code);
}

function uploadPhonePhotoError(data)
{
	$('.ajax-loader').hide();
	$('.action-button').removeClass('unclickable');
	$('.file').show();
}

var clip = null;
function initClipBoard() {
	$('.zero_clipbloard').remove();

	ZeroClipboard.setMoviePath( '/js/ZeroClipboard.swf' );
	clip = new ZeroClipboard.Client();
	clip.addEventListener('mouseOver', my_mouse_over);
	clip.addEventListener('complete', my_complete);
	clip.glue('copy_to_clipboard');
}

function my_mouse_over(client) {
 clip.setText( $('.phone-code textarea').val() );
}

function my_complete(client, text) {
	$('.copy_ok').remove();
	$('.copy-message').append('<div class="copy_ok">Код скопирован!</div>');
	$('.copy_ok').fadeOut(1000, function(){$(this).remove();});
}
