$('document').ready( function() {
});

window.onload = function() {	
	var start_crop = [];
	if ( $('#x').val()) {
		start_crop = [
			Number($('#x').val()),
			Number($('#y').val()),
			Number($('#x2').val()),
			Number($('#y2').val())
		];
	}
	else {
		start_crop = ( [0,0,$('#cropbox').width(),$('#cropbox').height()]);
	}

	var ar = $('#ar').val();
	if ( ar == 'unlocked'){
		ar = 0.0;
	}
	else if ( ar == 'current') {
		ar = (start_crop[2]-start_crop[0])/(start_crop[3]-start_crop[1]);
	}
	
	var api = $.Jcrop( '#cropbox', {
		onChange: updateOnChange,
		onSelect: updateOnSelect,
		aspectRatio: ar,
		setSelect: start_crop
	});
	
	$('#fz').click( function(){
		if ( this.checked) {
			$('#focal_zone').css('visibility','visible');
			$('#wh').css('margin-top','25px');
		}
		else {
			$('#focal_zone').css('visibility','hidden');
			$('#wh').css('margin-top', 0);
		}
	});
	
	$('#scs').click( function(){
		if ( this.checked) {
			$('#tl,#br,#wh').css('visibility','visible');
		}
		else {
			$('#tl,#br,#wh').css('visibility','hidden');
		}
	});
	
	$('#sts').click( function(){
		if ( this.checked) {
			$('#thumbs_frame').slideDown('slow');
			vertically_center_thumbs();	
		}
		else {
			$('#thumbs_frame').slideUp('slow');				
		}
	});
		
	$('#aspect_ratio').change(function(e) {
		r = getNewCoords( api, this.value);
		if ( this.value == 'unlocked'){
			api.setOptions( { aspectRatio:0.0 });
			$('#car, #car_wrap').show();
		}
		else if ( this.value == 'current') {
			cd = api.tellSelect();
			ca = cd['w']/cd['h'];
			api.setOptions( { aspectRatio:ca});
			$('#car, #car_wrap').show();
			// $('#car').val('(number)');
		}
		else {
			api.setOptions( { aspectRatio:this.value });
			$('#car, #car_wrap').hide();
		}
		nothing( e);
		// alert( r);
		return false;
	});
	
	$('#frame_size').change(function(e) {
		if ( this.value == 'custom') {
			w = $('#fw').val();
			if (w < 50) { w = 50; $('#fw').val(50); }
			h = $('#fh').val();
			if (h < 50) { h = 50; $('#fh').val(50); }
			
			$('#fw, #fh, [@for=fw], [@for=fh]').show();
		}
		else {
			c = this.value.split('x');
			w = c[0];
			h = c[1];
			$('#fw, #fh, [@for=fw], [@for=fh]').hide();
		}
		$('#preview_wrapper').css({ 'width':Number(w), 'height':Number(h) });
		showPreview(api.tellSelect());
	});
	
	$('#fw, #fh').change(function() {
		$('#frame_size').trigger('change');
	});
	
	// add the focal zone image & coordinate read outs to the DOM
	$('.jcrop-holder div div img').after('<div id="focal_zone"><img src="focal_zone.png" /></div>');
	$('#focal_zone').after('<div id="tl">'+$('#y').val()+','+$('#x').val()+'</div>');
	$('#focal_zone').after('<div id="br">'+$('#y2').val()+','+$('#x2').val()+'</div>');
	$('#focal_zone').after('<div id="wh">'+$('#w').val()+','+$('#h').val()+'</div>');
	
	// set some default values
	var state = $('#fz').attr('checked') ? 'visible' : 'hidden';
	$('#focal_zone').css('visibility',state);
	var offset = (state == 'visible') ? '25px' : 0;
	$('#wh').css( 'margin-top', offset);
	state = $('#scs').attr('checked') ? 'visible' : 'hidden';
	$('#tl,#br,#wh').css('visibility', state);
	state = $('#sts').attr('checked');
	if ( state)
	{
		$('#thumbs_frame').show();
		vertically_center_thumbs();
	}
	else {
		$('#thumbs_frame').hide();
	}
	
	// track thumb frame scroll position
	$('#thumbs_frame').scroll( function() {
		$('#scroll_pos').val($('#thumbs_frame').scrollLeft());
	});
	// position thumb frame scroll bar
	$('#thumbs_list li a').click( function() {
		this.href += '&pos=' + $('#scroll_pos').val();
	});
	$('#thumbs_frame').scrollLeft($('#scroll_pos').val());
	
	$('#aspect_ratio').val($('#ar').val());
	
	if ( $('#frame_size').val() != 'custom') {
		$('#fw, #fh, [@for=fw], [@for=fh]').hide();
	}
	$('#frame_size').trigger('change');

};

function vertically_center_thumbs() {
	$('#thumbs_list img').each(function(){
		fh = $(this).parent().height();
		ih = this.height;
		tm = (fh - ih)/2;
		$(this).css('margin-top', tm+'px');
	});	
}

function getNewCoords( api, a) {
	n = api.tellSelect();
	xo = n['x']; yo = n['y']; x2o = n['x2']; y2o = n['y2']; wo = n['w']; ho = n['h'];
	ao = wo / ho;
	ao = Math.round(ao*100)/100;
	if ( ao < a) {
		if (a < 1) {
			w = ho*a;
			dx = (w-wo)/2;
			dy = 0;
		}
		else if (ao < 1) {
			w = ho;
			h = w/a;
			dx = (w-wo)/2;
			dy = (h-ho)/2;
		}
		else {
			w = ho*a;
			dx = (w-wo)/2;
			dy = 0;
		}
		api.animateTo([xo-dx, yo-dy, x2o+dx, y2o+dy]);
	}
	else if ( a < ao) {
		if (ao < 1) {
			w = ho*a;
			dx = (w-wo)/2;
			dy = 0;
		}
		else if ( a < 1) {
			w = ho;
			h = w/a;
			dx = (w-wo)/2;
			dy = (h-ho)/2;
		}
		else {
			w = ho*a;
			dx = (w-wo)/2;
			dy = 0;
		}
		api.animateTo([xo-dx, yo-dy, x2o+dx, y2o+dy]);
	}
	return a;
	// return { 'x':xo, 'y':y, 'x2':x2, 'y2':y2, 'w':w, 'h':h }
}

function nothing( e)
{
	e.stopPropagation();
	e.preventDefault();
	return false;
};

function updateOnChange(coords){
	showCoords( coords);
	showPreview( coords);
}
function updateOnSelect(coords){
	showCoords( coords);
	showPreview( coords);	
}

// Our simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showCoords(c)
{
	$('#x').val(c.x);
	$('#y').val(c.y);
	$('#tl').text(c.y+','+c.x);
	$('#x2').val(c.x2);
	$('#y2').val(c.y2);
	$('#br').text(c.y2+','+c.x2);
	$('#w').val(c.w);
	$('#h').val(c.h);
	$('#wh').text(c.w+','+c.h);
	if ( $('#aspect_ratio').val() == 'unlocked')
	{
		$('#car').val(Number(c.w/c.h).toFixed(2));
	}
};

function showPreview( coords)
{
	var ww = $('#preview_wrapper').width();
	var wh = $('#preview_wrapper').height();
	var iw = $('#cropbox').width();
	var ih = $('#cropbox').height();
	var cw = coords.w;
	var ch = coords.h;
	var pw, ph;
	
	var wa = Math.round((ww / wh) * 100) / 100;
	var ia = Math.round((iw / ih) * 100) / 100;
	var ca = Math.round((coords.w / coords.h) * 100) / 100;
	
	// set holder size, aspect == crop aspect, fit in wrapper
	if ( ca <= wa) {
		hw = wh * ca;
		hh = wh;
	}
	else if (ca > wa) {
		hw = ww;
		hh = Math.round( ww/ca);
	}
	$('#preview_holder').css({ 'width':hw, 'height':hh });
	
	// set the image size, scale proportionally to match the holder	
	pw = Math.round(iw/cw * hw);
	ph = Math.round(ih/ch * hh);
	$('#preview').css({ 'width':pw, 'height':ph });
		
	// position image in the holder
	mt = Math.round( coords.y * ph/ih);
	ml = Math.round( coords.x * pw/iw);		
	$('#preview').css({ 'marginTop':-mt, 'marginLeft':-ml });
	
	// position holder in wrapper
	mt = Math.round((wh-hh)/2);
	ml = Math.round((ww-hw)/2);
	$('#preview_holder').css({'marginTop':mt, 'marginLeft':ml });
	
	// set the form #pw & #ph fields
	$('#pw').val(hw);
	$('#ph').val(hh);
};

function changeAspectRatio( ar) {
	
}

