$(document).ready(function() {

	function CreateCropper(options) {


		var img_orig_width = options.image.orig_width;
		var img_orig_height = options.image.orig_height;
		var img_path = options.image.path;
		var img_name = options.image.name;
		var img_url = options.image.url;

		var parent = options.parent;

		var img_width = parent.attr("data-width");
		var img_height = parent.attr("data-height");

		var holder = parent.find(".new-image");
		var img_holder = holder.find(".new-image-container");

		if (img_holder.find("img").length){
			img_holder.find("img").cropper("destroy").remove();			
		} 

		parent.find(".image-holder.new").show();

		var img_new = $("<img>");
			img_new.attr("src" , img_url + "?" + Date.now());
			img_new.prependTo(img_holder);

		img_holder.imagesLoaded(function(){

			//resize image holder to fit image if image too small
			if (img_holder.height() < 380){
				holder.css({
					"height"	: (img_holder.height()) + "px",
					//"line-height" : (img_holder.height() + 20) + "px",
				});
			} else {
				holder.css({
					"height"	: "381px",
					//"line-height" : "381px",
				});
			}
				


				//calculate the ratio
			var img_zoom_ratio = img_new.width() / img_orig_width;



					
			img_new.cropper({

				"minCropBoxWidth"		: (parseInt(parent.attr("data-height")) > 0) && (parseInt(parent.attr("data-width")) > 0) ? Math.round(parent.attr("data-width") *  img_zoom_ratio) : 0,
				"minCropBoxHeight"		: parseInt(parent.attr("data-height")) > 0 ? Math.round(parent.attr("data-height") *  img_zoom_ratio) : 0,

				"strict"				: true,
				"zoomable"				: false,
				"minContainerHeight"	: img_holder.height(),
				"minContainerWidth"		: img_holder.width(),

				"aspectRatio"			: (parseInt(parent.attr("data-height")) > 0) && (parseInt(parent.attr("data-width")) > 0) ? parent.attr("data-width") / parent.attr("data-height") : 0,

				"built"					: function (edata){

					if (typeof options.crop == "object"){
						var data = {
								left: options.crop.x * img_zoom_ratio,
								top: options.crop.y * img_zoom_ratio,
								width: options.crop.nw * img_zoom_ratio,
								height: options.crop.nh * img_zoom_ratio,
							};

						img_new.cropper("setCropBoxData" ,data);
					} else {
						//initial initialisation

						if ((parent.attr("data-height") > 0)&& (parent.attr("data-width") > 0)) {
							var pRatio = img_width / img_height;
							var sRatio = img_orig_width / img_orig_height;

							if (pRatio == sRatio) {

								var data = {
										left	: 0,
										top		: 0,
										width	: img_orig_width,
										height	: img_orig_height,
								};

							} else { 
								if (pRatio > sRatio) {

									var data = {
											left	: 0,
											top		: 0,
											width	: img_orig_width,
											height	: img_orig_height / pRatio,
									};
								} else {


									var data = {
											left	: 0,
											top		: 0,
											width	: img_orig_height * pRatio,
											height	: img_orig_height,
									};
								}
							}


							img_new.cropper("setCropBoxData" ,data);


						} else {

							//maximise the entire image
							
							var data = {
									left: 0,
									top: 0,
									width: img_orig_width * img_zoom_ratio,
									height: (img_orig_height * img_zoom_ratio) ,
							};
							img_new.cropper("setCropBoxData" ,data);

						}
					}

				},

				crop				: function(data) {

					var crop_data = "";
					
					crop_data = 
						parent.attr("data-width") + ":" + 
						parent.attr("data-height") + ":" + 
						Math.round(data.x) + ":" + 
						Math.round(data.y) + ":"  +
						Math.round(data.width) + ":" + 
						Math.round(data.height) + ":" + 
						img_path + ":" +  
						img_orig_width + ":"  +
						img_orig_height;

					$("#" + parent.attr("data-field") + "_crop_oxbc").val(crop_data);									

				}
				
			});


		});
								


		$("#" + parent.attr("data-field") + "_temp").val(img_name);				
		$("#" + parent.attr("data-field") + "_temp_file").val(img_name);				
		$("#" + parent.attr("data-field") + "_radio_type").val("1");


		//control delete current image
		if (parent.find(".old-image").attr("data-src") != ""){
			parent.find(".delete-old").addClass("disabled");
		}
		

		
		parent.find(".delete-new").removeClass("disabled").click(function(e){
			img_holder.html("");
			$(this).addClass("disabled");

			if (parent.find(".old-image").attr("data-src") != ""){
				parent.find(".delete-old").removeClass("disabled");
			}


			parent.find(".image-holder.new").hide();

			$("#" + parent.attr("data-field") + "_temp").val("");				
			$("#" + parent.attr("data-field") + "_temp_file").val("");				
			$("#" + parent.attr("data-field") + "_radio_type").val("0");
			$("#" + parent.attr("data-field") + "_crop_oxbc").val("");									

			//phisicaly delete the image

			$.ajax({
				url: "index.php?upload-action=image-upload&file=" + img_name,
				type: 'DELETE',
				success: function(result) {
				}
			});						
		});


	}


	//initialize upload field

	if ($(".image-editor .html-file-upload").length){

		$(".image-holder.new").hide();

		$(".image-preview .delete-new , .image-preview .delete-old ").click(function(e){
			e.preventDefault();			
		});


		$(".image-preview .html-file-upload").each(function(e){

			var form = $(this);

			form.fileupload({

				dataType		: "json",

				add: function (e, data) {
					data.url = "index.php?upload-action=image-upload";
					data.submit();

					$(form.attr("data-preview")).find(".progress-holder").slideDown();
					$(form.attr("data-preview")).find(".progress-holder .status").css(
						'width',
						0 + '%'
					);
				},

				done			: function (e , data) {

					var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;

			
					if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {

						//delete file
						$.ajax({
							url: "index.php?upload-action=image-upload&file=" + data.result.files[0].name,
							type: 'DELETE',
							success: function(result) {
							}
						});						

						AlertBox('Image file type not supported. Please upload only JPEG, PNG, GIF.');

			        } else if((typeof data.result.files[0] == "undefined")) {
						AlertBox("Unexpected error: the file size might exceed the server allowed limit.")
					} else if (typeof data.result.files[0]["error"] != "undefined") {
						AlertBox(data.result.files[0]["error"]);
					} else {

						CreateCropper({
							parent	:  $(form.attr("data-preview")),
							
							image : {	
								orig_width  : data.result.files[0].img_width,
								orig_height : data.result.files[0].img_height,
								path		: "../upload/tmp/" + data.result.files[0].name,
								name		: data.result.files[0].name,
								url			: data.result.files[0].url,
							}

						});						

					}

					$(form.attr("data-preview")).find(".progress-holder").slideUp();
				
				},
				progressall	: function (e, data) {

					var progress = parseInt(data.loaded / data.total * 100, 10);					

					$(form.attr("data-preview")).find(".progress-holder .status").css(
						'width',
						progress + '%'
					);
				},

				fail : function (e, data) {
					AlertBox("Cant upload: the file size might exceed the server allowed limit.");
				}
			});
		});

	}



	if ($(".file-uploader .html-file-upload").length){

		$(".file-new").hide();

		$(".file-uploader .delete-new , .file-uploader .delete-old ").click(function(e){
			e.preventDefault();			
		});


		$(".file-uploader .html-file-upload").each(function(e){

			var form = $(this);
			var parent = $(this).closest(".file-preview");

			form.fileupload({

				dataType		: "json",

				add: function (e, data) {
					data.url = "index.php?upload-action=file-upload";
					data.submit();
				},

				done			: function (e , data) {

					var error = false;


					if (parent.attr("data-allowed") != "")	{

						var acceptFileTypes = '/^image\/(' + parent.attr("data-allowed") + ')$/i';
						var patt = new RegExp(acceptFileTypes);

						if((typeof data.result.files[0] == "undefined")){
							AlertBox("Unexpected error: the file size might exceed the server allowed limit.");
							error = true;

						} else if (typeof data.result.files[0]["error"] != "undefined") {
							AlertBox(data.result.files[0]["error"]);
							error = true;
						} else if(data.originalFiles[0]['type'].length && patt.test(data.originalFiles[0]['type']) ) {

							//delete file
							$.ajax({
								url: "index.php?upload-action=file-upload&file=" + data.result.files[0].name,
								type: 'DELETE',
								success: function(result) {
								}
							});						

							AlertBox('File type not supported. Please upload only ' + str_replace("|" , ", " , parent.attr("data-allowed")) + ".");

							error = true;
						} 
			        } 
					if (!error)	{
						if(typeof data.result.files[0] == "undefined") {
							AlertBox("Unexpected error: the file size might exceed the server allowed limit.")
						} else {

							parent.find(".file-new").slideDown();
							parent.find(".file-new .file-name").html(data.result.files[0].name);
							parent.find(".file-new .file-size").html(humanFileSize(data.result.files[0].size));						

							$("#" + parent.attr("data-field") + "_temp").val(data.result.files[0].name);				
							$("#" + parent.attr("data-field") + "_temp_file").val(data.result.files[0].name);				
							$("#" + parent.attr("data-field") + "_radio_type").val("0");

							var file_name = data.result.files[0].name;


							parent.find(".delete-new").removeClass("disabled").click(function(e){
								parent.find(".file-new .file-name, .file-new .file-size").html("");
								parent.find(".file-new").hide();

								$(this).addClass("disabled");


								$("#" + parent.attr("data-field") + "_temp").val("");				
								$("#" + parent.attr("data-field") + "_temp_file").val("");				
								$("#" + parent.attr("data-field") + "_radio_type").val("0");

								//phisicaly delete the image

								$.ajax({
									url: "index.php?upload-action=file-upload&file=" + file_name,
									type: 'DELETE',
									success: function(result) {
									}
								});						
							});

						}
					}

				
				},
				progressall	: function (e, data) {

					var progress = parseInt(data.loaded / data.total * 100, 10);					

					parent.find(".progress-holder .status").css(
						'width',
						progress + '%'
					);
				},

				fail : function (e, data) {
					AlertBox("Cant upload: the file size might exceed the server allowed limit.");
				}
			});
		});

	}

	if ($(".file-uploader .file-old").length) {
		$(".file-uploader .file-old").each(function(e) {

			$(this).hide();

			if ($(this).attr("data-file")){
				$(this).show();
				$(this).find(".file-name").html($(this).attr("data-file") + '<span class="sign sign-download"></span>').attr("href" , $(this).attr("data-download"));

				var holder = $(this).closest(".file-preview");

				holder.find(".delete-old").removeClass("disabled").click(function(e){

					if ($(this).hasClass("disabled")) {

					} else {
						$(this).addClass("disabled");
						holder.find(".file-old").slideUp("");
						//mark file for deletion
						$("#" + holder.attr("data-field") + "_radio_type").val("-1");
					}
				});

			}
		});
	}

	if ($(".image-preview").length){

		$(".image-preview").each(function(e) {
	
			var old = $(this).find(".old-image").hide();

			if (old.attr("data-src")) {
				var img_src = $("<a href=\"" + old.attr("data-src") + "\" rel='prettyPhoto'><img src=\"" + old.attr("data-src") + "\"/></a>");
					img_src.prettyPhoto({social_tools:false});				

				img_src.appendTo(old);

				old.show();

				var holder = old.closest(".image-preview");

				//activate the delete button
					holder.find(".delete-old").removeClass("disabled").click(function(e){

						if ($(this).hasClass("disabled")) {

						} else {
							$(this).addClass("disabled");
							holder.find(".old-image").html("");
							//mark image for deletion
							$("#" + holder.attr("data-field") + "_radio_type").val("-1");
						}
					});

			}

			if ($(this).attr("data-crop")){

				var cropdata = $(this).attr("data-crop").split(":");
				var parent = $(this);

/*
							parent.attr("data-width") + ":" + 
							parent.attr("data-height") + ":" + 
							Math.round(data.x) + ":" + 
							Math.round(data.y) + ":"  +
							Math.round(data.width) + ":" + 
							Math.round(data.height) + ":" + 
							img_path + ":" +  
							img_orig_width + ":"  +
							img_orig_height;

*/
				CreateCropper({
					parent	:  parent,
					
					image : {	
						orig_width  : cropdata[7],
						orig_height : cropdata[8],
						path		: cropdata[6],
						name		: basename(cropdata[6]),
						url			: cropdata[6],
					} ,

					crop : {
						x		: cropdata[2],
						y		: cropdata[3],
						nw		: cropdata[4],
						nh		: cropdata[5],
					}

				});						
			}
		});
	}

});