$(function(){
	var button = $("#upload");
	var url = "/upload.php";
	var preload = [new Image(), new Image()];
	preload[0].src = "/static/progress.gif";
	preload[1].src = "/static/progress-bg.gif";

	if (DetectFlashVer(0,0,0)) {
		swfupload(button, url, success, $("div.progress"));
	} else {
		var uploadText = button.find("div");
		var i = 0;
		var interval;

		new AjaxUpload(button, {
			action: url,
			name: "img",
			responseType: "json",
			onSubmit: function(file, ext){
				// change button text, when user selects file
				uploadText.eq(0).hide();
				uploadText.eq(1).show();
				uploadText.eq(2).hide();

				// If you want to allow uploading only 1 file at time,
				// you can disable upload button
				this.disable();

				// Uploding -> Uploading. -> Uploading...
				if (interval) {
					window.clearInterval(interval);
				}

				interval = window.setInterval(function(){
					++i;

					if (i > 3) {
						uploadText.eq(1).text(uploadText.eq(1).text().substr(0, uploadText.eq(1).text().length - 3));
						i = 0;
					} else {
						uploadText.eq(1).text(uploadText.eq(1).text() + '.');
					}
				}, 500);
			},
			onComplete: function(file, data){
				window.clearInterval(interval);

				uploadText.eq(1).hide();
				uploadText.eq(2).show();

				this.enable();

				success(data);
			}
		});
	}
});

function success(r) {
	var html = '<tr><td>';

	// add file to the list
	if (r.error) {
		html += 'Ошибка (' + r.error + ')';
	}

	if (r.full) {
		if (r.thumb) {
			html += '<div style="width:220px;"><a href="' + r.view + '" target="_blank"><img src="' + r.thumb + '" alt="" /></a></div>';
			html += '</td>';
			html += '<td><h2>Thumbnail (zoom by clicking)</h2><br />HTML';
			html += '<input type="text" readonly="readonly" value="<a href=&quot;http://iceimg.com/' + r.view + '&quot;><img src=&quot;http://iceimg.com/' + r.thumb + '&quot; alt=&quot;IceImg &mdash; image hosting&quot; /></a>" />';
			html += '<br /><br />';
			html += 'BBCode';
			html += '<input type="text" readonly="readonly" value="[url=http://iceimg.com/' + r.view + '][img]http://iceimg.com/' + r.thumb + '[/img][/url]" />';
			html += '<br /><br /><br />';
		} else {
			html += '<img src="' + r.full + '" alt="" />';
			html += '</td><td>';
		}

		html += '<h2>Full image</h2><br />HTML';
		html += '<input type="text" readonly="readonly" value="<a href=&quot;http://iceimg.com/' + r.view + '&quot;><img src=&quot;http://iceimg.com/' + r.full + '&quot; alt=&quot;IceImg &mdash; image hosting&quot; /></a>" />';
		html += '<br /><br />';
		html += 'BBCode';
		html += '<input type="text" readonly="readonly" value="[url=http://iceimg.com/' + r.view + '][img]http://iceimg.com/' + r.full + '[/img][/url]" />';
		html += '<br /><br />';
		html += 'View page';
		html += '<input type="text" readonly="readonly" value="http://iceimg.com/' + r.view + '" />';
		html += '<br /><br />';
		html += 'URL';
		html += '<input type="text" readonly="readonly" value="http://iceimg.com/' + r.full + '" />';
	}

	html += '</td></tr>';

	if (!$("#content table").length) {
		html = '<table>' + html + '</table>';

		$("#content").append(html);
	} else {
		$("#content table").prepend(html);
	}

	$(":text").unbind().focus(function(){
		this.select();
	}).mouseup(function(){
		return false;
	});
}

function swfupload(obj, url, successFunc, progressbar) {
	var totalFiles = 0;
	var filesUploaded = 0;
	var progress = 0;

	var updateProgress = function(){
		progressbar.show();

		if (totalFiles == 1) {
			progress = 1;
		}

		progressbar.find("span").width(Math.round(progress * 100) + "%");
	};

	obj.swfupload({
		upload_url: url,
		file_post_name: "img",
		button_image_url: "/static/swf-button-en.png",
		button_width: 173,
		button_height: 47,
		button_placeholder: obj[0],
		button_window_mode: SWFUpload.WINDOW_MODE.OPAQUE,
		flash_url: "/static/swfupload.swf"
	})
	.bind("fileQueued", function(e, file){
		obj.swfupload("startUpload");
	})
	.bind("fileDialogComplete", function(e, numFilesSelected, numFilesQueued){
		totalFiles = numFilesSelected;
		filesUploaded = 0;
		progress = 0;

		updateProgress();
	})
	.bind("uploadProgress", function(e, file, bytesLoaded){
		//progress = (filesUploaded / totalFiles) + (bytesLoaded / file.size / totalFiles);
		//updateProgress();
	})
	.bind("uploadSuccess", function(e, file, serverData){
		var d = $.parseJSON(serverData);

		if (d.error) {
			alert(d.error);
		} else {
			successFunc(d);
		}
	})
	.bind("uploadComplete", function(e, file){
		++filesUploaded;
		progress = filesUploaded / totalFiles;

		updateProgress();

		if (progress == 1) {
			progressbar.delay(100).hide();
		}

		obj.swfupload("startUpload");
	});
}

