var x1 = x2 = y1 = y2 = 0;

$(document).ready(function() {
	$('#image').Resizable({
		maxWidth: 800,
		maxHeight: 600,
		handlers: {
			se: '#resizeSE',
			e: '#resizeE',
			ne: '#resizeNE',
			n: '#resizeN',
			nw: '#resizeNW',
			w: '#resizeW',
			sw: '#resizeSW',
			s: '#resizeS'
		}
	});
	$('#image').Draggable({
		opacity: 0.7,
		zIndex: 10
	});
	
	$("#ratio").click(function() {
		if ($(this).is(":checked"))
			drag_ratio(1);
		else
			drag_ratio(0);
	});
	
	$("#upload").click(function() {
		$.ajaxUpload({
			uploadform:document.f,
			url:'plugins/flash-countdown/upload.php',
			secureuri:false,
			dataType:'json',
			success:function(msg){
							
				if(msg.success == 0) {
					alert(msg.message);
					return false;
				}
				else {
					$('#image').attr("src","plugins/flash-countdown/" + msg.name).css({height:msg.height,width:msg.width,left:0,top:0});
					$("#border").val("0;0;0;0");
					$('#container').css({"background-color":"#"+ $("#cf").val()});
					$("#image-move").show();	
				}
			}
		});						  
	});

	$("#submit").click(function() {
		if (change == 0) {
			position();
			var line = 'cmd=generate&image='+ $("#image").attr("src") +'&x1='+ x1.toString() +'&x2='+ x2.toString() +'&y1='+ y1.toString() +'&y2='+ y2.toString() +'&cf='+ $("#cf").val();
		}
		else
			var line = 'cmd=generate&image='+ $("#bi").val() +'&x1=0&x2=350&y1=0&y2=200&cf='+ $("#cf").val() + "&border=" + $("#border").val();

		$.ajax({
			type: "POST",
			url: "plugins/flash-countdown/ajax.php",
			data: line,
			success: function(msg){
				var result = eval("("+msg+")");
				
				if (result.success == 0) {
					alert(result.message);
				}
				else {
					$("#bi").val(result.name);
					reloadFlash();
				}
				
				change = 0;
				$("#image-move").hide();
			}
		});
	});
});

function drag_ratio(option) {
	$('#image').ResizableDestroy();
	
	var ratio_op = 0;
	if ($("#image").width() > $("#image").height())
		ratio_op = $("#image").height() / $("#image").width();
	else
		ratio_op = $("#image").width() / $("#image").height();
	
	if (option == 1) {	
		$('#image').Resizable({
			maxWidth: 800,
			maxHeight: 600,
			ratio:  ratio_op,
			handlers: {
				se: '#resizeSE',
				e: '#resizeE',
				ne: '#resizeNE',
				n: '#resizeN',
				nw: '#resizeNW',
				w: '#resizeW',
				sw: '#resizeSW',
				s: '#resizeS'
			}
		});	
	}
	else {
		$('#image').Resizable({
			maxWidth: 800,
			maxHeight: 600,
			handlers: {
				se: '#resizeSE',
				e: '#resizeE',
				ne: '#resizeNE',
				n: '#resizeN',
				nw: '#resizeNW',
				w: '#resizeW',
				sw: '#resizeSW',
				s: '#resizeS'
			}
		});	
	}
}

function position() {
	x1 = parseInt($("#image").css("left").replace(/px/, ""));
	x2 = parseInt($("#image").css("left").replace(/px/, "")) + parseInt($("#image").width());
	y1 = parseInt($("#image").css("top").replace(/px/, ""));
	y2 = parseInt($("#image").css("top").replace(/px/, "")) + parseInt($("#image").height());
	$("#border").val(x1 + ";" + y1 + ";" + x2 + ";" + y2);
}