var suo = null;
var suo2 = null;
var img_ok = "http://img.movavi.com/support/uploader/pics/tick.png";
var img_err = "http://img.movavi.com/support/uploader/pics/error.png";
var img_cancel = "http://img.movavi.com/support/uploader/pics/control_stop.png";
var max_size_bytes = 5 * 1073741824; //5 GB

var today = new Date( ); 
var s3_params = {
	policyDoc64			: "CgkJeyJleHBpcmF0aW9uIjogIjIwMTQtMTItMDlUMTA6NDQ6MDFaIiwKCQkJImNvbmRpdGlvbnMiOiBbCgkJCQl7ImJ1Y2tldCI6ICJtb3Zhdmktc3VwcG9ydCJ9LAoJCQkJWyJzdGFydHMtd2l0aCIsICIka2V5IiwgIiJdLAoJCQkJWyJzdGFydHMtd2l0aCIsICIkZmlsZW5hbWUiLCAiIiBdLCAKCQkJCXsiYWNsIjogInB1YmxpYy1yZWFkIn0sCgkJCQlbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LURpc3Bvc2l0aW9uIiwgIiJdLAoJCQkJWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsIDAsIDUzNjg3MDkxMjBdCgkJCV0KCQl9CgkJ",
	sigPolicyDoc		: "8OiEJWIVES2MXLzgto/lqbMmaDQ=",
	AWSAccessKeyId	: "1808JEKCEX23Z97FSRG2",
	max_size_bytes	: max_size_bytes,
	S3_FOLDER				: today.getFullYear() + "/" + (today.getMonth() + 1) + "-" + today.getDate() + "/" + today.getTime( ) + "/"
};
var upload_path = "http://movavi-support.s3.amazonaws.com/";
var uploading_file_item_template = null;
var upload_file_list_item_template = null;
var upload_file_list_item_template2 = null;

function add_url(url, file) {
	$(".upload_files_list_container").show();
	$(".upload_files_list_container:visible").append(upload_file_list_item_template, {
		id: file.id ,
		name: file.name,
		url: encodeURIComponent(url),
		filesize: SWFUpload.speed.formatBytes(file.size)
	});
	
	$("#upload_file_"  + file.id).click(function() {
		$("#upload_file_div_"  + file.id).remove();
	});
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_progress").progressbar('option', 'value', file.percentUploaded.toFixed(0));
}

function fileQueued(file) {
	//add new file to list
	$("#uploading_files_placeholder").append(uploading_file_item_template, { 
			id: file.id ,
			name: file.name,
			filesize: SWFUpload.speed.formatBytes(file.size)
		}
	);
	
	$("#btn_cancel_" + file.id).click(function () {
		var id = $(this).attr("fileid");
		suo.cancelUpload(id);
		$("div.uploading_file_div[fileid='" + file.id + "']").slideUp(300);
	});
	
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_progress").progressbar({ value: 0 });
}
function uploadComplete(file) {
	//$("#upload_stats").fadeOut(500);
	this.startUpload();
}

function uploadSuccess(file, data, response) {
	var url = upload_path + encodeURI(this.params.S3_FOLDER + file.name).replace(/\+/g, "%2B").replace(/#/g, "%23");
	var dot_pos = file.name.lastIndexOf('.');
	add_url(url, file);
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_cancel").html("<img src='"+img_ok+"'>");
}

function uploadError(file, err_code, message){
	
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_cancel").html("<img src='"+img_err+"'>");
}

function fileQueueError(file, err_code, message) {
	alert("file '" + file.name + "': " + message);
}

function fileDialogComplete(selected, queued, inqueue) {
	if(queued > 0 ) {
		$("#add_file_form").dialog('open');
			suo.params = s3_params;
			suo.setFileSizeLimit(s3_params.max_size_bytes / 1024);
			suo.addPostParam("key", s3_params.S3_FOLDER + "${filename}");
			suo.addPostParam("AWSAccessKeyId", s3_params.AWSAccessKeyId);
			suo.addPostParam("acl", "public-read");
			suo.addPostParam("policy", s3_params.policyDoc64);
			suo.addPostParam("signature", s3_params.sigPolicyDoc);
			suo.addPostParam("Content-Disposition", "attachment; filename=${filename}");
			suo.startUpload();
	}
}


//-------------------



function add_url2(url, file) {
	$(".upload_files_list_container2").show();
	$(".upload_files_list_container2:visible").append(upload_file_list_item_template, {
		id: file.id ,
		name: file.name,
		url: encodeURIComponent(url),
		filesize: SWFUpload.speed.formatBytes(file.size)
	});
	
	$("#upload_file_"  + file.id).click(function() {
		$("#upload_file_div_"  + file.id).remove();
	});
}

function uploadProgress2(file, bytesLoaded, bytesTotal) {
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_progress").progressbar('option', 'value', file.percentUploaded.toFixed(0));
}

function fileQueued2(file) {
	//add new file to list
	$("#uploading_files_placeholder").append(uploading_file_item_template, { 
			id: file.id ,
			name: file.name,
			filesize: SWFUpload.speed.formatBytes(file.size)
		}
	);
	
	$("#btn_cancel_" + file.id).click(function () {
		var id = $(this).attr("fileid");
		suo2.cancelUpload(id);
		$("div.uploading_file_div[fileid='" + file.id + "']").slideUp(300);
	});
	
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_progress").progressbar({ value: 0 });
}
function uploadComplete2(file) {
	//$("#upload_stats").fadeOut(500);
	this.startUpload();
}

function uploadSuccess2(file, data, response) {
	var url = upload_path + encodeURI(this.params.S3_FOLDER + file.name).replace(/\+/g, "%2B").replace(/#/g, "%23");
	var dot_pos = file.name.lastIndexOf('.');
	add_url2(url, file);
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_cancel").html("<img src='"+img_ok+"'>");
	$("#add_file_form").dialog('close');
}

function uploadError2(file, err_code, message){
	
	$("div.uploading_file_div[fileid='" + file.id + "'] .uploading_file_cancel").html("<img src='"+img_err+"'>");
}

function fileQueueError2(file, err_code, message) {
	alert("file '" + file.name + "': " + message);
}

function fileDialogComplete2(selected, queued, inqueue) {
	if(queued > 0 ) {
		$("#add_file_form").dialog('open');

		$('#add_file_form').dialog('option', 'height', 411);
		$('#add_file_form').dialog('option', 'width', 455);
		
			suo2.params = s3_params;
			suo2.setFileSizeLimit(s3_params.max_size_bytes / 1024);
			suo2.addPostParam("key", s3_params.S3_FOLDER + "${filename}");
			suo2.addPostParam("AWSAccessKeyId", s3_params.AWSAccessKeyId);
			suo2.addPostParam("acl", "public-read");
			suo2.addPostParam("policy", s3_params.policyDoc64);
			suo2.addPostParam("signature", s3_params.sigPolicyDoc);
			suo2.addPostParam("Content-Disposition", "attachment; filename=${filename}");
			suo2.startUpload();
	}
}

function destroyUploader2() {
	if(suo2 !== null) {
		suo2.destroy();
		suo2 = null;
	}	
	$("#uploading_files_placeholder2").html("");
	$("#upload_button_holder_container2").html("");
}

function destroyUploader() {
	if(suo !== null) {
		suo.destroy();
		suo = null;
	}	
	$("#uploading_files_placeholder").html("");
	$("#upload_button_holder_container").html("");
}

function initUploader() {
	if(suo === null) {
		suo = new SWFUpload({
			// Backend Settings
			upload_url: upload_path,
			assume_success_timeout: 10,
			requeue_on_error: false,
			http_success : [200, 201, 204],

			// File Upload Settings
			file_size_limit : "5 GB",
			file_types : "*.*",
			file_types_description : "Video Files",
			file_upload_limit : "10",
			file_post_name : "file",
			
			button_width: "100",
			button_height: "20",
			button_placeholder_id: "spanButtonPlaceHolder",
			button_cursor : SWFUpload.CURSOR.HAND,
			button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
			
			file_queue_error_handler : fileQueueError,
			file_queued_handler : fileQueued,
			file_dialog_complete_handler: fileDialogComplete,
			upload_progress_handler : uploadProgress,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,
			// Flash Settings
			flash_url : "http://img.movavi.com/support/uploader/js/lib/SWFUpload/swfupload.swf"	// Relative to this file
		});
	}
}

function initUploader2() {
	if(suo2 === null) {
		suo2 = new SWFUpload({
			// Backend Settings
			upload_url: upload_path,
			assume_success_timeout: 10,
			requeue_on_error: false,
			http_success : [200, 201, 204],

			// File Upload Settings
			file_size_limit : "5 GB",
			file_types : "*.*",
			file_types_description : "Video Files",
			file_upload_limit : "10",
			file_post_name : "file",
			
			button_width: "100",
			button_height: "20",
			button_placeholder_id: "spanButtonPlaceHolder2",
			button_cursor : SWFUpload.CURSOR.HAND,
			button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
			
			file_queue_error_handler : fileQueueError2,
			file_queued_handler : fileQueued2,
			file_dialog_complete_handler: fileDialogComplete2,
			upload_progress_handler : uploadProgress2,
			upload_success_handler : uploadSuccess2,
			upload_complete_handler : uploadComplete2,
			// Flash Settings
			flash_url : "http://img.movavi.com/support/uploader/js/lib/SWFUpload/swfupload.swf"	// Relative to this file
		});
	}
}


$(document).ready(function () {
	//read templates
	uploading_file_item_template = $.template($("div[tid='uploading_file_item_template']").outerHTML());
	$("#uploading_files_placeholder").html("");
	
	upload_file_list_item_template = $.template($("div[tid='upload_file_list_item_template']").outerHTML());
	upload_file_list_item_template2 = $.template($("div[tid='upload_file_list_item_template2']").outerHTML());
	$("#templates").remove();
			
	$("#add_file_form").dialog(
	{ 
		//modal: true, 
		width: 450,
		height: 410,
		minWidth: 350,
		minHeight: 350,
		resizable: true,
		autoOpen: false,
		bgiframe: true,
		resize: function(event, ui) {
			var height = $("#add_file_form").height();

			$("#uploading_files_placeholder").height(height - 60);
		},
		open:function(event, ui){
			var height = $("#add_file_form").height();
			$("#uploading_files_placeholder").height(height - 60);	
			// Instantiate a SWFUpload Instance

		},
		buttons: { 
			"Close": function()	{ 

				$(this).dialog("close");

			}
		}
	});
});