
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");
		var upload_form = document.getElementById("upload_form");
		upload_form.action = "upload.php";
		upload_form.target = "upload_iframe";
		upload_form.submit();
		
		this.time_started = this.time();
		this.last_response.time = this.time_started;
		
		$("#upload_form_container").hide();
		$("#video_upload_info").show();
		
		$("#info_filename").html($("#upload_name").val());
		
		this.StartProgressWatch();
	},
	
	StartProgressWatch : function()
	{
		var o = this;
		this.progress_timer = setInterval(function() {o.ProgressUpdate();}, 1000);
	},		
	StopProgressWatch : function()
	{
		if(typeof this.progress_timer == "number") {
			clearInterval(this.progress_timer); 
			delete this.progress_timer;
			$("#upload_button").removeAttr("disabled");
		}
	},
	ProgressUpdate : function()
	{
		var vars = {
			action: "getprogress",
			progresskey: $("#progress_key").val()
		}
		$("#info_elapsed").html(VideoUpload.GetFormattedTime(VideoUpload.time() - VideoUpload.time_started));
		sendXmlHttpRequest("get", VideoUpload.actionsPath, xhParseParams(vars), function(jsHttp) 
		{
			eval("var json = " + jsHttp.responseText);
			//var json = jQuery.parseJSON(jsHttp.responseText);
			if (json.Message.Type == "info") 
			{
				if (json.Status)
				{
					
					if (json.Status.complete == 1) {
						VideoUpload.StopProgressWatch();
					}
					
					var speed = 0;
					var remain = json.Status.total - json.Status.uploaded;
					if ((VideoUpload.last_response.time + VideoUpload.calc_delay) < json.Status.time) 
					{
						var time = json.Status.time - VideoUpload.last_response.time;
						var uploaded = json.Status.uploaded - VideoUpload.last_response.uploaded;
						VideoUpload.last_response.time = parseInt(json.Status.time);
						VideoUpload.last_response.uploaded = json.Status.uploaded;
						
						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(json.Status.total));
					$("#info_uploaded").html(VideoUpload.GetFormattedSize(json.Status.uploaded));
					$("#info_remain").html(VideoUpload.GetFormattedSize(remain));
					
					var percent = Math.round(json.Status.uploaded * 100 / json.Status.total);
					$("#info_percent").html(percent);
					document.getElementById("info_progressbar").style.width = Math.round(300*json.Status.uploaded/json.Status.total) + "px";
					//document.getElementById("info_progressbar").style.width = percent + "%";
					
				} else {
					VideoUpload.timeout_counter++;
					if (VideoUpload.timeout_counter > 20) {
						VideoUpload.StopProgressWatch();
						alert("Ошибка при загрузке файла. Возможно файл больше установленных лимитов.");
						location.reload();
					}
				}
			} else {
				return "";
			}
		});
	},
	
	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)
	{
		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);
		}
	}
			
}
