
show_load_title = false;

var VideoUpload = {
	
	actionsPath : "/actions/video_actions.php",
	progress_timer : null,
	last_response : {
		time : 0,
		uploaded : 0
	},
	time_started : 0,
	calc_delay : 2,
	file_name : "",
	timeout_counter : 0,
	
	time : function()
	{
		var ms = new Date().getTime();
		return Math.round(ms/1000);
	},
	
	StartUpload : function()
	{
		if (!this.CheckFields()) return false;
		$("#upload_button").attr("disabled", "true");
		
		this.time_started = this.time();
		
		$("#upload_form_container").hide();
		$(".info-filename").html($("#upload_name").val());

		if (!window.FormData)
		{
			//alert("Ваш браузер не поддерживает отображение прогресса загрузки. Поддерживаемые браузеры: Firefox, Chrome, Opera 12.0+, Internet Explorer 10+. Будет выполнена обычная загрузка.");
			$("#video_upload_info_simple").show();
			$("#upload_form").submit();
			return true;
		}

		$("#video_upload_info").show();
		var fd = new FormData(document.getElementById("upload_form"));
		//fd.append("videofile", document.getElementById("videofile").files[0]);

		var obj = this;

		var xhr = new XMLHttpRequest();
		xhr.upload.addEventListener("progress", function(event) { obj.ProgressUpdate(event); }, false);
		xhr.addEventListener("load", function(event) { obj.UploadFinish(event); });
        xhr.addEventListener("error", function(event) { obj.UploadError(event); }, false);
        xhr.addEventListener("abort", function(event) { obj.UploadAbort(event); }, false);
		xhr.open("POST", "/upload.php");
		//xhr.setRequestHeader("X-FILE-NAME", this.file_name);
		xhr.send(fd);
	},

	UploadFinish : function(event)
	{
		this.StopProgressWatch();
		var json = jQuery.parseJSON(event.target.response);
		if (json.Redirect) {
			location.href = json.Redirect;
		} else {
			this.SwitchToFrom(json.Message.Text);
		}

	},

	SwitchToFrom : function(message)
	{
		$("#upload_form_container").show();
		$("#video_upload_info").hide();
		$("#upload_messages").html(message);
	},

	UploadError : function(event)
	{
		this.SwitchToFrom("Ошибка во время загрузки");
		this.StopProgressWatch();
	},

	UploadAbort : function(event)
	{
		this.SwitchToFrom("Загрузка прервана");
		this.StopProgressWatch();
	},

	StopProgressWatch : function()
	{
		$("#upload_button").removeAttr("disabled");
	},
	ProgressUpdate : function(event)
	{
		$("#info_elapsed").html(VideoUpload.GetFormattedTime(VideoUpload.time() - VideoUpload.time_started));
		if (!event.lengthComputable) {
			//console.log("not computable");
			return false;
		}
		var speed = 0;
		var remain = event.total - event.loaded;
		if ((VideoUpload.last_response.time + VideoUpload.calc_delay) < this.time())
		{
			var time = this.time() - VideoUpload.last_response.time;
			var uploaded = event.loaded - VideoUpload.last_response.uploaded;
			VideoUpload.last_response.time = parseInt(this.time());
			VideoUpload.last_response.uploaded = event.loaded;

			speed = Math.floor(uploaded/time);
			if (speed > 0) {
				$("#info_eta").html(VideoUpload.GetFormattedTime(time * remain / uploaded));
				$("#info_speed").html(VideoUpload.GetFormattedSize(speed, true) + "/сек");
			} else {
				$("#info_eta").html("∞");
				$("#info_speed").html("0");
			}
		}
		$("#info_total").html(VideoUpload.GetFormattedSize(event.total));
		$("#info_uploaded").html(VideoUpload.GetFormattedSize(event.loaded));
		$("#info_remain").html(VideoUpload.GetFormattedSize(remain));

		var percent = Math.round(event.loaded * 100 / event.total);
		$("#info_percent").html(percent);
		document.getElementById("info_progressbar").style.width = Math.round(300*event.loaded/event.total) + "px";
	},
	
	GetFormattedSize : function(size, round)
    {
		if (round)
 			return (size >= 1048576) ? Math.round(size / 1048576) + " МБайт" : Math.round(size / 1024) + " КБайт";
		else
			return (size >= 1048576) ? (size / 1048576).toFixed(2) + " МБайт" : (size / 1024).toFixed(2) + " КБайт";
    },
	GetFormattedTime : function(time)
	{
		var seconds = Math.floor(time % 60);
		if (seconds < 10) seconds = "0" + seconds; 
		return Math.floor(time / 60) + ":" + seconds;
	},
	
	UpdateFileName : function(sender)
	{
		if (sender.files[0])
		{
			var file = sender.files[0];
			if (file) {
				if (file.size > 400000000) {
					alert("Размер файла больше установленного лимита.");
					$("#upload_button").attr("disabled", "true");
					return false;
				}
			}
		}
		$("#upload_button").removeAttr("disabled");
		this.file_name = sender.value;
		var filename = sender.value.replace(/_/gi, " ");
		var regex = new RegExp("^(.*\\\\)*(.*)(\\..*)$")
		filename = filename.replace(regex, "$2");
		if ($("#upload_name").val() == "") $("#upload_name").val(filename);
	},
	
	CheckFields : function()
	{
		if ($("#videofile").val() == "") {
			alert("Выберите файл");
			return false;
		}
		if ($("#upload_name").val() == "") {
			alert("Введите название");
			return false;
		}
		if ($("#upload_dir").val() == "0") {
			alert("Выберите раздел");
			return false;
		}
		return true;
	}
		
}

var Video = 
{		
	actionsPath : "/actions/video_actions.php",
	statusTimer : null,
	
	ShowHint : function(sender, event, data)
	{
		//new data: 0 - title, 1 - date,  2 - dirname, 3 - views, 4 - comments count
		var video_hint = document.getElementById("video_hint");
		var html = "";
		html += "Название: <b>" + data[0] + "</b><br>";
		//html += "Раздел: " + data[2] + "<br>";
		html += "Комментариев: " + data[4] + "<br>";
		html += "Дата добавления: " + data[1] + "<br>";
		var pos = getBounds(document.getElementById(sender.id));
		document.getElementById("video_hint_html").innerHTML = html;
		video_hint.style.left = pos.left + "px";
		video_hint.style.top = pos.top + 88 + "px";
		video_hint.style.display = "block";
	},
	
	HideHint : function(event)
	{
		document.getElementById("video_hint").style.display = "none";
	},
	
	UpdateConvertStatus : function(video_id)
	{
		this.statusTimer = setInterval(function(){Video.GetConvertStatus(video_id)}, 1500);
	},
	
	GetConvertStatus : function(video_id)
	{
		var vars = "action=getconvertstatus&videoid="+ video_id;
		sendXmlHttpRequest("post", this.actionsPath, vars, function(jsHttp) 
		{
			eval("var json = " + jsHttp.responseText);
			if (json.Message.Type == "info") 
			{
				var status = "";
				switch (json.Status)
				{
					case "idle":
						status = "Ожидание";
						break;
					case "converting":
						status = "Конвертирование";
						break;
					case "error":
						status = "Ошибка конвертирования";
						clearInterval(Video.statusTimer);
						$("#video_status_img").hide();
						break;
					case "ok":
						status = "Конвертирование завершено";
						clearInterval(Video.statusTimer);
						location.reload();
						break;
					default:
						status = "Ошибка конвертирования";
						clearInterval(Video.statusTimer);
						$("#video_status_img").hide();
				}
				document.getElementById("video_status_" + video_id).innerHTML = status + "...";
			} else {
				return "";
			}
		});
	},
	
	DeleteVideoConfirm : function(video_id)
	{
		$("#dialog").dialog({
			bgiframe: false,
			resizable: false,
			width: 300,
			height: 200,
			modal: true,			
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Удалить ролик': function() {
					Video.DeleteVideo(video_id);
					$(this).dialog('close');
				},
				"Отмена": function() {
					$(this).dialog('destroy');
				}
			}
		});
		$("#dialog").dialog('open');
	},
	
	ShowInfoDialog : function(text)
	{
		$("#info_dialog").dialog({
			bgiframe: true,
			height: 140,
			modal: true
		});
		$("#info_dialog p").html(text);
		$("#info_dialog").dialog('open');
	},
	
	DeleteVideo : function(video_id)
	{
		var vars = "action=deletevideo&videoid="+ video_id;
		//if (confirm("Удалить ролик?") == false) return false;
		try {
			sendXmlHttpRequest("post", this.actionsPath, vars, function(jsHttp) 
			{
				eval("var json = " + jsHttp.responseText);
				if (json.Message.Type == "info") 
				{
					if (json.Result == true) 
					{
						//alert("Ролик удалён");
						Video.ShowInfoDialog("Ролик удалён");
						location.reload(); 
					}
				} else {
					//alert(json.Message.Type + ":\n" + json.Message.Text);
					Video.ShowInfoDialog(json.Message.Type + ":\n" + json.Message.Text);
				}
			});
		} catch (e) {
			alert(e);
		}
	},
	
	ShowEditForm : function(video_id)
	{
		$("#edit_window").html("<div style=\"text-align: center; padding-top: 100px;\"><img src=\"/img/big_throbber.gif\"></div>");
		var vars = {
			action: "geteditform",
			videoid: video_id
		}
		sendXmlHttpRequest("post", this.actionsPath, xhParseParams(vars), function(jsHttp) 
		{
			eval("var json = " + jsHttp.responseText);
			if (json.Message.Type == "info" && json.Html) 
			{
				$("#edit_window").html(json.Html);
			}
		});
		$("#edit_window").dialog({
			bgiframe: true,
			resizable: false,
			width: 500,
			height: 590,
			modal: true,			
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			close: function(event, ui) {
				$(this).dialog("destroy");
			},
			buttons: {
				"Сохранить изменения": function() {
					Video.SaveEdit(video_id);
				},
				"Отмена": function() {
					$(this).dialog("destroy");
				}
			}
		});
		$("#edit_window").dialog('open');
	},
	
	SaveEdit : function(video_id)
	{
		var vars = {
			action: "saveedit",
			videoid: video_id,
			name: xh_prepare_str($("#edit_name").val()),
			text: xh_prepare_str($("#edit_text").val()),
			dirid: $("#edit_dirid").val(),
			thumb_num: $("#thumb_num").val(),
			adult: $("#edit_adult").attr("checked") ? "on" : "",
			public: $("#edit_public").attr("checked") ? "on" : "",
			tags: $("#photo_tags").val()
		}
		sendXmlHttpRequest("post", this.actionsPath, xhParseParams(vars), function(jsHttp) 
		{
			eval("var json = " + jsHttp.responseText);
			if (json.Message.Type == "info" && json.Result) 
			{
				var thumb_path = $("#thumb" + video_id + " > a > img").attr("src");
				$("#thumb" + video_id + " > a > img").attr("src", thumb_path.replace(/-0([1-5]).jpg/, "-0"+vars.thumb_num+".jpg"));
				
				$("#thumb-info" + video_id + " > .thumb-info-title > a").html(vars.name.slice(0, 50));
				
				$("#edit_window").dialog("destroy");
			} else {
				$("#messages").html(json.Message.Text);
			}
		});
	},
	
	GetCommentsRange : function(id, comment_id)
	{
		var comments_range = document.getElementById("comments_range_"+id);
		if (comments_range.innerHTML.length != 0) {
			comments_range.style.display = "block";
			return;
		}
		var vars = "action=getcommentsrange&id=" + id +"&commentid=" + comment_id;
		try {
			sendXmlHttpRequest("post", this.actionsPath, vars, function(jsHttp) {
				eval("var json = " + jsHttp.responseText);
				if (json.Message.Type == "info") {
					comments_range.style.display = "block";
					document.getElementById("comments_range_"+id).innerHTML = json.Html;
				} else {
					alert(json.Message.Type + ":\n" + json.Message.Text);
				}
			} 
			);
		} catch (e) {
			alert(e);
		}
	},
	
	
	
	Rate : function(video_id, rate)
	{
		var vars = {
			"action": "rate",
			"videoid": video_id,
			"rate": rate
		}
		try {
			sendXmlHttpRequest("post", this.actionsPath, xhParseParams(vars), function(jsHttp) 
			{
				eval("var json = " + jsHttp.responseText);
				if (json.Message.Type == "info") 
				{
					if (rate == 1)
						$("#video_votes_yes_" + video_id).html(json.Votes);
					else
						$("#video_votes_no_" + video_id).html("-" + json.Votes);
				} else {
					alert(json.Message.Type + ":\n" + json.Message.Text);
				}
			});
		} catch (e) {
			alert(e);
		}
	}
			
}

