//
// Image Upload and Croptool.
//
// Options:
//
//  - cropArea  Selector to element to be filled with cropper
//  - button Selector to upload button
//  - titleField Optional title field for use with MediaController
//  - onSubmit - callback fired before form is submitted (scoped to the form being submitted)
//  - onComplete - callback fired after form response is recieved (scoped to form being submitted)
//
ImageUpload = new Class({
	options : {
		cropArea : null,
		button : null,
		uploadUrl : '/media/prepare_image',
		showCropper : true,
		titleField : null,
		onSubmit : function (){ },
		onComplete : function (){ }
	},
	init : function(options) {
		this.options = options = jQuery.extend({}, this.options, options);
		if (options.button === null || options.cropArea === null || options.uploadUrl === null) {
			throw('Missing required options');
		}
		if (jQuery.fn.ajaxSubmit === undefined || jQuery.fn.imgAreaSelect === undefined) {
			throw('Requires jQuery.form & imgAreaSelect plugins');
		}
		this.button = $(options.button);
		this.form = $(this.button.get(0).form);
		this.cropArea = $(options.cropArea);
		jQuery.fn.exists = function(){return jQuery(this).length>0;}
		this.button.bind('click', {that : this}, this.doUpload);
	},
//
// Upload handler.
//
	doUpload : function(event) {
		var that = event.data.that;
		event.preventDefault();
		event.stopPropagation();
		//alert(that.options.uploadUrl)
		var options = {
			url : that.options.uploadUrl,
			beforeSubmit : that.beforeSubmit,
			dataType : 'json',
			success : that.doSuccess.bind(that)	
		};
		if (that.options.titleField) {
			options.data = {};
			options.data["data[Media][title]"] = $(that.options.titleField).val();
		}
		var $form = $(this.form);
          
		$form.bind('form-submit-notify', that.options.onSubmit);
		$form.bind('ajaxSuccess', that.options.onComplete);

		$form.ajaxSubmit(options);
	},
	//
// Handle form completion
//
	doSuccess : function (responseText, statusText) {
		//alert(responseText.cropUrl);
		 responseText.data = responseText;		
		if (!responseText.data.cropUrl || !responseText.data.mediaId || responseText.status == 'error') {
			var message = responseText.data.message || YouFoot.i18n.get('error');
			alert(message);
			return;
		}
		var mediaId = $('<input type="hidden" />').attr({
			value : responseText.data.mediaId,
			id : "MediaMediaId",
			name : 'data[Media][media_id]'
		});
		this.form.append(mediaId);
		if (responseText.status == 'success') {	
			$("#ImageCropArea").empty();
			var container = this.cropArea.parent();
			var  $class= container.attr('class');
			if ($class != "content image-upload clearfix") {
				if ($("#CropIframe").exists()) {
					container = $("#CropIframe").parent();
					container.empty();
				}
				else 
					container.empty();
			}
			else 
				if ($class == "content image-upload clearfix") {
					if ($("#CropIframe").exists()) {
						container = $("#CropIframe").parent();
						$("#CropIframe").remove();
					}
				}
		} 
		var iframe = document.createElement('IFRAME');
		var $iframe = $(iframe);
		$iframe.attr('id', 'CropIframe');
		$iframe.attr('name', 'CropIframe');
		$iframe.attr('src', responseText.data.cropUrl);
		$iframe.attr('scrolling', 'no');
		$iframe.height(450);
		container.append(iframe);
		$('.myDefaultPicture1').hide();
		$('.myDefaultRecherche1').css('border','0');
	},
//
// Validate form submission.
//
	beforeSubmit : function(formData, jqForm, options) {
		if (options.extraData["data[Media][title]"] == '') {
			alert(YouFoot.i18n.get('nameRequired'));
			return false;
		}
		if (jqForm.get(0)["data[Media][file]"].value == '' && jqForm.get(0)["data[Media][image_url]"].value == '') {
			alert(YouFoot.i18n.get('fileOrNameRequired'));
			return false;
		}
		return true;
	},
	loadImage: function(cropUrl) {		
		var container = this.cropArea.parent();
		container.empty();
		var iframe = document.createElement('IFRAME');
		var $iframe = $(iframe);
		$iframe.attr('id', 'CropIframe');
		$iframe.attr('name', 'CropIframe');
		$iframe.attr('src', cropUrl);
		$iframe.attr('scrolling', 'no');
		container.append(iframe);
	}
});