var $ = jQuery.noConflict();

$(document).ready(function(){
	var id=1;
	var _width=[];
	var _height=[];
	var _x=[];
	var _y=[];
	
	var __width=[];
	var __height=[];
	var __x=[];
	var __y=[];

	
	var imageselect = $('#photo_in_edit img').livequery(function(){
		$(this).imgAreaSelect({
			onSelectEnd: cropImage,
			aspectRatio: getAspectRatio(1)
		});
	});
	
	$('.photos_to_edit div:first img').livequery(function(){
		$(this).addClass('checked');
	});
		
	$('.photos_to_edit img').livequery(function(){		
		$(this).click(function(){					
			
			$('.photos_to_edit div img').removeClass('checked');
			$(this).addClass('checked');
			id = $(this).parent().attr('id');						
			$('#photo_in_edit img').attr('src', $(this).attr('src'));
			$(imageselect).livequery(function(){
				$(this).imgAreaSelect({aspectRatio: getAspectRatio(id)});
			});
			
			if (_x[id-1])
			$(imageselect).livequery(function(){
				$(this).imgAreaSelect({x1: _x[id-1], y1: _y[id-1], x2: _x[id-1]+_width[id-1], y2: _y[id-1]+_height[id-1]});
			});
			else
			$(imageselect).livequery(function(){
				$(this).imgAreaSelect({x1: 0, y1: 0, x2: 0, y2: 0});
			});
		});
	});
	
	$('button#edit_photos').livequery(function(){
		$(this).click(function(){		
			var a_url= $(this).attr('name');		
			$(imageselect).livequery(function(){
				$(this).imgAreaSelect({
					hide: true		
				});
			}); 
			$.ajax({
					type: 'post',
					url: a_url,
					data: 'width='+__width+'&height='+__height+'&x='+__x+'&y='+__y,
				    dataType: 'html',
				    success: function(t){
				    	if (t)
				    	{
				    		$('#messages').parent().html(t);	
				    	}
				    }
				});
			return false;
		});
	});
	
	
	
	function cropImage(img, selection)
	{
		_width[id-1]= selection.width;
		_height[id-1]= selection.height;
		_x[id-1]= selection.x1;
		_y[id-1]= selection.y1; 
		
		var image_width= $('#photo_in_edit img').width();
		var image_height= $('#photo_in_edit img').height();
		var ratio=0;		
		var mini_size= $('.photos_to_edit img.checked').parent().width();
		var ratio= mini_size/_width[id-1];
		

		var width= parseInt(image_width*ratio);
		var height= parseInt(image_height*ratio);
		var x= parseInt(-_x[id-1]*ratio);
		var y= parseInt(-_y[id-1]*ratio);
		
		__width[id-1]= width;
		__height[id-1]= height;
		__x[id-1]= x;
		__y[id-1]= y; 
		
		$('.photos_to_edit img.checked').css({'width': width, 'height': height});
		$('.photos_to_edit img.checked').css({'left': x+'px', 'top': y+'px'});
	}
	
	function getAspectRatio(id)
	{
		var d_width = $('#'+id).css('width');
		var d_height = $('#'+id).css('height');
		var as = '1:'+(parseInt(d_height)/parseInt(d_width));		
		return as;
	}
});


