
var plupload_flash_swf_url = "/js/plupload/js/plupload.flash.swf";
var plupload_silverlight_xap_url = "/js/plupload/js/plupload.silverlight.xap";
var plupload_upload_url = "/admin/images/upload";



/*--------------------- test newsletter email ---------------- */

function send_test_email(event, trigger){
	
	var $form = $(trigger).closest('form');
	var $data = $form.serialize();
	var $action = $form.attr('action');
	
	if(!$('#PostMailTestAdress').val()){
		alert('Pirma įrašykite gavėjo adresą');
		return;
	}
	
	var $trigger_value = $(trigger).html();
	$(trigger).html('Siunčiama...');
	
	$.post($action, $data, function(data){
		data = $.parseJSON(data);
		if(data.status == 'success'){
			alert('Laiškas išsiųstas');
		} else {
			alert('Laiško išsiųsti nepavyko. Bandykite dar kartą arba kreipkitės į sistemos administratorių');
		}
		$(trigger).html($trigger_value);
	});
	
}

function deleteImage(event, trigger, url){
	if(event.preventDefault) {
		event.preventDefault();
	} else {
		event.returnValue = false;
	}
	$.post(url, function(data){
		data = $.parseJSON(data);
		if(data.status == 1){
			$(trigger).closest('div.image-wrapper').remove();
		} else {
			alert('Nuotraukos ištrinti nepavyko. Bandykite perkrauti puslapį ir bandyti dar kartą, arba kreipkitės į sistemos administratoriu.');
		}
	});
};

/*--------------------- plupload image ---------------- */

function pluploadToGallery(){
	
	$gallery = $("#plupload-gallery");
	$galleryContainer = $("#plupload-images-gallery");
	$imgCount = 0;
	
	this.uploader = new plupload.Uploader({
		runtimes : "gears,html5,flash,silverlight,browserplus",
		flash_swf_url: plupload_flash_swf_url,
		browse_button: "plupload-browse",
		url:  plupload_upload_url,
		filters : [{title : "Image files", extensions : "jpg,jpeg,gif,png"}],
		resize : {width : 800, height : 800, quality : 90}
	});
	
	this.uploader.init();
	
	this.uploader.bind("FilesAdded", function(up, files) {
		$.each(files, function(index, value){
			var $img = $('<div class="image-wrapper" id="'+value.id+'">'+
			 			  '<div class="image loading"></div>'+
			 			  '<p class="image-name">'+value.name+'</p>'+
			 		  '<div>');
			
			$galleryContainer.append($img);
		});
		$gallery.removeClass('empty');
		up.start();
	});
	
	this.uploader.bind('UploadProgress', function(up, file) {
		$('#'+file.id+' div.image').html(file.percent + "%");
	});
				
	this.uploader.bind("Error", function(up, err) {
		alert("Error: "+err.code+", Message: "+err.message);
		up.refresh(); // Reposition Flash/Silverlight
	});
	
	this.uploader.bind("FileUploaded", function(up, file, response) {
		response = $.parseJSON(response.response);
		$('<img />').attr("src", response.url).load(function(){
			$('#'+file.id+' div.image').removeClass("preloading");
			$('#'+file.id).addClass('preloaded');
			$('#'+file.id+' div.image').html("").append($(this));
			$input = $('<input type="hidden" name="data[images]['+$imgCount+']" />').val(response.file);
			$gallery.append($input);
			$imgCount++;
		});
	});
	
}

function pluploadImage(imageName, crop, options){
	
	
	this.uploader = new plupload.Uploader({
		runtimes : "gears,html5,flash,silverlight,browserplus",
		//runtimes : "flash",
		flash_swf_url: plupload_flash_swf_url,
		silverlight_xap_url : "plupload_silverlight_xap_url",
		browse_button: imageName+"-plupload-browse",
		url:  plupload_upload_url,
		filters : [{title : "Image files", extensions : "jpg,jpeg,gif,png"}],
		drop_element: imageName+"-plupload-image"
	});
	
	this.uploader.init();
		    
	this.uploader.bind("FilesAdded", function(up, files) {
		if(crop){
			$("#"+imageName+"-plupload-image img").imgAreaSelect({remove: true});
		}
		$("#"+imageName+"-plupload-image").html("").addClass("preloading");
		up.start();
	});
	
	this.uploader.bind('UploadProgress', function(up, file) {
		$("#"+imageName+"-plupload-image").html(file.percent + "%");
	});
				
	this.uploader.bind("Error", function(up, err) {
		alert("Error: "+err.code+", Message: "+err.message);
		up.refresh(); // Reposition Flash/Silverlight
	});
	
	this.uploader.bind("FileUploaded", function(up, file, response) {
		response = $.parseJSON(response.response);
		$("#"+imageName+"-plupload-image-url").val(response.file);
		$('<img name="'+imageName+'" id="'+imageName+'">').attr("src", response.url).load(function(){
			$("#"+imageName+"-plupload-image").removeClass("preloading");
			$("#"+imageName+"-plupload-image").html("").append($(this));
			$("#"+imageName+"-plupload-image-url").val(response.file);
			if(crop) selectImgArea($(this), options);
		});
	});
	
	
};

/* --------------------- crop image ---------------- */

function update(img, selection){
	var imgName = $(img).attr('name');
	$("#"+imgName+"-image-x1").val(selection.x1);
	$("#"+imgName+"-image-y1").val(selection.y1);
	$("#"+imgName+"-image-x2").val(selection.x2);
	$("#"+imgName+"-image-y2").val(selection.y2);
	$("#"+imgName+"-image-width").val(selection.width);
	$("#"+imgName+"-image-height").val(selection.height);
}

function select(image, options, default_args){

	for(var index in default_args) {
		if(typeof options[index] == "undefined") options[index] = default_args[index];
	};
	
	if(options["x2"] == "0" || options["y2"] == "0"){
		if(options["aspectRatio"]){
			var currentRatio = options["imageWidth"]/options["imageHeight"];
			var requiredRatioArgs = options["aspectRatio"].split(":");
			var requiredRatio = requiredRatioArgs[0]/requiredRatioArgs[1];
			
			if(currentRatio < requiredRatio){
				options["x2"] = options["imageWidth"];
				options["y2"] = options["imageWidth"]/requiredRatio;
			} else if(currentRatio > requiredRatio){
				options["x2"] = options["imageHeight"]*requiredRatio;
				options["y2"] = options["imageHeight"];
			} else {
				options["x2"] = options["imageWidth"];
				options["y2"] = options["imageHeight"];
			}
		} else {
			options["x2"] = options["imageWidth"];
			options["y2"] = options["imageHeight"];
		}
	}
	
	//console.log(options);
	
	image.imgAreaSelect({
		imageWidth: options["imageWidth"],
		imageHeight: options["imageHeight"],
		x1: options["x1"],
		y1: options["y1"],
		x2: options["x2"],
		y2: options["y2"],
		aspectRatio: options["aspectRatio"],
		persistent: options["persistent"],
		onInit: update,
		onSelectChange: update
	});
	
}

function selectImgArea(image, options) {
	
	var default_args = {
		"x1" : "0",
		"y1" : "0",
		"x2" : "0",
		"y2" : "0",
		"aspectRatio" : false,
		"persistent" : true,
		"onInit" : update,
		"onSelectChange" : update
	};
	
	if(typeof options == "undefined") options = new Array();
	
	if(typeof options['imageWidth'] == "undefined" || typeof options['imageHeight'] == "undefined"){
		$("<img>").attr("src", image.attr("src")).load(function(){
			default_args["imageWidth"] = this.width;
			default_args["imageHeight"] = this.height;			
			select(image, options, default_args);
		});
	} else {
		select(image, options, default_args);
	};
	
}

$(document).ready(function(){
	
	$("input.date").datepicker({
		dateFormat: 'yy-mm-dd'
	});
	
	$("div.ui-tabs").tabs({
		create: function(event, ui) {
			//tinyMCE.execCommand('mceAddControl',false,'mydiv');
		}
	});
	
});


