//
// Multiupload
//

nextFieldId = 0;

function createField(source) {
	if($(".field").length == max_num_imgs) { alert("Du darfst nur " + max_num_imgs + " Bilder hochladen!"); return false; }
	$("	<div class='field' id='img" + nextFieldId + "'>\
			<a href='javascript:toggleField(" + nextFieldId + ");void(0);'><img src='/res/imgs/source_" + source + ".png' /></a>\
			<input type='" + (source == "local" ? "file" : "text") + "' name='img" + nextFieldId + "' />\
			" + (nextFieldId != 0 ? "<a href='javascript:deleteField(" + nextFieldId + ");void(0);'><img src='/res/imgs/delete.png' /></a>" : "") + "\
		</div>").appendTo($("#fields"));
	nextFieldId++;
	fixFirefoxFieldWidth();
	$(".step").eq(2).css("margin-top", 28 + $(".field").length * 35 + "px");
}

function createFieldLastType() {
	createField($(".field:last input").attr("type") == "file" ? "local" : "remote");
}

function toggleField(id) {
	var source = $("#img" + id + " input").attr("type") == "text" ? "local" : "remote";
	$("#img" + id).html("\
			<a href='javascript:toggleField(" + id + ");void(0);'><img src='/res/imgs/source_" + source + ".png' /></a>\
			<input type='" + (source == "local" ? "file" : "text") + "' name='img" + id + "' />\
			" + (id != 0 ? "<a href='javascript:deleteField(" + id + ");void(0);'><img src='/res/imgs/delete.png' /></a>" : "") + "\
		");
	fixFirefoxFieldWidth();
}

function deleteField(id) {
	$("#img" + id).remove();
	$(".step").eq(2).css("margin-top", 23 + $(".field").length * 35 + "px");
}

firefoxFileSize = false;

function fixFirefoxFieldWidth() {
	if($("#fields").length == 0) return;
	if(navigator.product == "Gecko") {
		if(firefoxFileSize == false) {
			$("input[type=file]").css("width", "auto");
			firefoxFileSize = 20;
			while($("input[type=file]")[0].scrollWidth < 340 && firefoxFileSize < 60) {
				$("input[type=file]").attr("size", firefoxFileSize++);
			}
			$("input[type=file]").css("width", "350px");
		} else {
			$("input[type=file]").attr("size", firefoxFileSize);
		}
	}
}

//
// Filetype-Switch, erstes Feld
//

$(document).ready(function() {
	$("#filetype a img").fadeTo(0, 0.3);
	$("#filetype a img").mouseover(function() { $(this).fadeTo(0, 1) });
	$("#filetype a img").mouseout(function() { $(this).fadeTo(0, 0.3) });
	if($("#fields").length > 0) {
		if(document.location.pathname != '/archive.php') {
			createField("local");
		} else {
			fixFirefoxFieldWidth()
		}
	}
});


//
// Upload-Optionen
//

function newGalleryDialog() {
	openDialog("neue Galerie anlegen", "\
		<input id=\"newname\" type=\"text\" name=\"name\" value=\"Name\" onclick=\"this.value = ''; this.onclick = '';\" /><br />\
		<input id=\"newdesc\" type=\"text\" name=\"desc\" value=\"Beschreibung\" onclick=\"this.value = ''; this.onclick = '';\" /><br />\
		<button onclick=\"\
			$.get('/calls/createGallery.php?name=' + encodeURIComponent($('#newname').val()) + '&amp;desc=' + encodeURIComponent($('#newdesc').val()), function(response) {\
				if(isNaN(response)) {\
					$('#newanswer').html(response);\
				} else {\
					$('#galleryselect option:selected').val(response);\
					$('#galleryselect option:selected').html($('#newname').val());\
					closeDialog();\
				}}); return false;\"\
			>anlegen</button>\
			<div id=\"newanswer\"></div>");
}

function useFormat() {
	$('#resizeselect option:selected').val($('#newsize').val());
	if($('#newsize').val().match(/^[0-9]{1,4}x[0-9]{1,4}$/)) {
		$('#resizeselect option:selected').html("Passend in " + $('#newsize').val());
	} else {
		$('#resizeselect option:selected').html("Lange Seite " + $('#newsize').val() + " Pixel");
	}
	closeDialog();
}

function newResizeDialog() {
	openDialog("eigenes Format", "\
		Format (z.B. 1024x768 für passend in 1024x768 Pixel<br />oder 800 für lange Seite 800 Pixel):<br />\
		<input id=\"newsize\" type=\"text\" name=\"format\" value=\"\" onclick=\"this.value = ''; this.onclick = '';\" onkeyup=\"$('#dialog button')[0].disabled = !this.value.match(/^[0-9]{1,4}(?:x[0-9]{1,4})?$/) \" /><br />\
		" + (user_logged_in ? "\
			<input type=\"checkbox\" name\"save\" id=\"saveformat\" /> <label for=\"saveformat\">Format speichern?</label>\
			<button onclick=\"\
				if($('#saveformat').val() == 'on') {\
					$.get('/calls/createResize.php?size=' + encodeURIComponent($('#newsize').val()));\
					useFormat();\
				} else {\
					useFormat();\
				}\
				return false;\"\
			disabled=\"disabled\">Format nutzen</button>\
		" : "\
			<button onclick=\"useFormat(); return false;\" disabled=\"disabled\">Format nutzen</button><br />Als angemeldeter Benutzer könntest du deine Formate auch speichern.") + "\
		");
}

function editResizeDialog() {
	openDialog("eigene Formate", "<div id='editformats'></div>");
	javascript:$('#editformats').load('/calls/editResize.php');
}


//
// Progress
//

$(document).ready(function() {
	var upId = '';
	for (var i = 0; i < 32; i++) {
		upId += Math.floor(Math.random() * 16).toString(16);
	}
	if($("#uploadForm").length == 1) {
		$("#uploadForm")[0].action = 'upload.php?X-Progress-ID=' + upId;
		$("#uploadForm").submit(function() {
			if(typeof(flashloaded) == "undefined" || flashloaded == false)
			updater = window.setInterval(function() { getProgress(upId); }, 1000);
			var foo = new Date();
			startTime = foo.getTime();
		});
	}
});

function getProgress(uId) {
	if(navigator.userAgent.indexOf("Safari") !== -1 && document.location.href.indexOf("Iframe") == -1) {
		if($("#progressIframe").length == 0) {
			$("#content").empty();
			$("<iframe src='/calls/progressIframe.php' id='progressIframe' style='width: 450px; height: 50px'>").appendTo($("#content"));
		}
		if($("#progressIframe").length == 1 && typeof($("#progressIframe")[0].contentWindow) !== "undefined" && typeof($("#progressIframe")[0].contentWindow.getProgress) !== "undefined") {
			$("#progressIframe")[0].contentWindow.getProgress(uId);
		}
	} else {
		$.ajax({
			type:		"GET",
			url:		"/progress",
			beforeSend:	function(xhr) { xhr.setRequestHeader('X-Progress-ID', uId); },
			dataType:	"text",
			cache:		false,
			success:	updateProgress,
			timeout:	500
		});
	}
}

function updateProgress(data, status) {
	var data = eval(data);
	if(data.size == 0) {
		$("#content").html("Du hast den Upload abgebrochen.");
		document.title = "Abgebrochen - abload.de";
		window.clearInterval(updater);
	}
	switch(data.state) {
		case "starting":
			break;
		case "error":
			$("#content").html("Bei deinem Upload ist leider ein Fehler aufgetreten. Sollte dies öfter der Fall sein, setze dich bitte mit uns in Verbindung");
			window.clearInterval(updater);
			break;
		case "uploading":
			showProgressBar();
			$("#progressBar").css("width", Math.floor(data.received / data.size * 400));
			progressBarVisible = true;
			var time = new Date();
			time = time.getTime() - startTime;
			$("#progressText").html(Math.floor(data.received / 1024 / 1024 * 10) / 10 + ' MB von ' + Math.floor(data.size / 1024 / 1024 * 10) / 10 + ' MB (' + Math.floor((data.received / 1024) / (time / 1000) * 100) / 100 + ' kB/s)');
			document.title = Math.floor(data.received / data.size * 100) + "% - abload.de";
			break;
		case "done":
			if(typeof(progressBarVisible) == "undefined") {
				showProgressBar();
				$("#progressBar").css("width", 400);
				progressBarVisible = true;
			}
			$("#progressText").html("Upload fertig. Bilder werden verarbeitet.");
			window.clearInterval(updater);
			break;
	}
}

function showProgressBar() {
	if($("#progress").length == 0) {
		$("#content").empty();
		$("<div id='progress'><div id='progressBar' /><div id='progressText' /></div>").appendTo($("#content"));
	}
}

//
// Flashupload
//

function thisMovie(movieName) {
	 if (navigator.appName.indexOf("Microsoft") != -1) {
		 return window[movieName];
	 } else {
		 return document[movieName];
	 }
 }
 function startFlashUpload() {
	$("#flashuploader")[0].addFinishArg('gallery', $("#galleryselect").val());
	$("#flashuploader")[0].addFinishArg('resize', $("#resizeselect").val());
	if($("input[name=captcha_code]").length == 1) {
		$("#flashuploader")[0].addFinishArg('captcha_code', $("input[name=captcha_code]").val());
		$("#flashuploader")[0].addFinishArg('captcha_answer', $("input[name=captcha_answer]").val());
	}
	$("#flashuploader")[0].startUpload();
 }
 
function uploadStarted() {
	$("#abloadbutton")[0].onclick = function() { $("#flashuploader")[0].cancelUpload(); };
	$("#abloadbutton").val("Abbruch");
}

function setFlashHeight(newH){
	$('#flashuploader').css('height', newH + "px");
	$('.step:eq(2)').css('margin-top', 70 + (newH - 80) + "px");
}

function uploadCanceled() {
	$("#abloadbutton")[0].onclick = function() { startFlashUpload(); };
	$("#abloadbutton").val("Abload!");
}
function openDialog(title, html) {
	$("<div id='greyBox'>").appendTo("body");
	$("<div id='dialog'><h1>" + title + "</h1><a id='dialog_close' href='javascript:closeDialog();void(0)'>schließen [X]</a><div id='dialogcontent'>" + html + "</div></div>").appendTo("body");
	$("#dialog").css("margin-left", -$("#dialog").width() / 2 + "px");
	$("#dialog_close").focus();
	$("#flashuploader").css("visibility", "hidden");
}

function closeDialog() {
	$("#greyBox").remove();
	$("#dialog").remove();
	if(window.opera) {
		$("body").css("background", "#80b7ff url(/res/imgs/gradient.jpg) repeat-x");
	}
	$("#flashuploader").css("visibility", "visible");
}

function resizeDialog(width) {
	$("#dialog").css("width", width + "px");
	$("#dialog").css("margin-left", -$("#dialog").width() / 2 + "px");
}

function confirmDialog(html, url) {
	openDialog('Bestätigung', html + '<button style="float: left" onclick="document.location.href = \'' + url + '\'">OK</button><button style="float: right" onclick="closeDialog()">Abbrechen</button>');
	resizeDialog(500);
}
