var swfu;
var wgrane_poprawnie = new Array();
var wgrane_handlers = new Array();
var wgrane_licznik = 0;
var wgrane_uploaded = 0;
var wgrane_sprawdzaj = true;
var wgrane_iterator = 0;

var ImageUplaoder_File;
var ImageUplaoder_Files = new Array();

function ImageUploader_SetInfo(html, ajax, error) {
	if (typeof(error) == 'boolean' && error) {
		html = '<span style="color:red;">'+ html +'</span>';
	}
	if (typeof(ajax) == 'boolean' && ajax) {
		html = '<img src="http://s.emuzyka.pl/img/ikonki/24x24/ajax.gif" align="absmiddle" />' + html;
	}

	$('#upload_info').html(html).show();
}
function ImageUploader_CheckExtenstion(obj, acceptable, ok_f) {
	var f_name = $(obj).val();
	var f_ext = f_name.toLowerCase().match(/[a-z,0-9]{3,4}$/)[0];
	acceptable = acceptable.split(',');

	for (i=0; i<acceptable.length; i++) {
		if (f_ext == acceptable[i]) {
			ok_f();
			return true;
		}
	}

	ImageUploader_SetInfo('Wybrałeś plik o nieprawidłowym formacie. Wybierz .jpg lub .jpeg!', false, true);
	return false
}
function ImageUploader_Send() {
	$('#image_upload_form').submit();
	$('#image_upload_browse').attr('disabled','disabled');
	ImageUploader_SetInfo('Trwa wgrywanie fotki.');

	ImageUplaoder_File = new Object({
		"id" : 'SWFUpload_0_'+ (wgrane_iterator++),
		"name" : $('#image_upload_browse').val()
	});

	swfu.fileQueued(ImageUplaoder_File);

	var progress = new FileProgress(ImageUplaoder_File, swfu.customSettings.progressTarget);
	progress.setStatus("Wysyłanie");
	progress.toggleCancel(true, this);
}
function ImageUploader_Write(post_params) {
	var url = '' + this.location;
	var base = url.substring(0, url.indexOf('.pl/')+4);

	//	alert(var_dump(post_params));

	var settings = {
		flash_url : "http://s.emuzyka.pl/img/swf/swfupload.swf",
		upload_url : base + "ajax/upload_albums.php",
		file_post_name : "Thumbnail1_1",
		post_params : post_params,
		file_size_limit : "10 MB",
		file_types : "*.jpg; *.jpeg; *.JPG; *.JPEG; *.png; *.PNG; *.gif; *.GIF; *.bmp; *.BMP",
		file_types_description : "Fotki",
		file_upload_limit : ImageUploader_AlbumMaxFileCount,
		file_queue_limit : ImageUploader_AlbumMaxFileCount,
		custom_settings : {
			progressTarget : "upload_queue"
		},
		debug: false,

		button_placeholder_id : "upload_browse_overlay",
		button_image_url : base + "img/blank.gif",
		button_width: $('#upload_browse_button').width(),
		button_height: $('#upload_browse_button').height(),
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,

		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		queue_complete_handler : queueComplete,
		swfupload_loaded_handler : swfuploadLoaded
	};
	swfu = new SWFUpload(settings);
}
function ImageUploader_complete(odp) {
	$('#image_upload_browse').removeAttr('disabled').val('');
	ImageUploader_SetInfo('Fotka została dodana. Wybierz następną lub <a href="'+ ImageUploader_AlbumUrl +'">przejdź do albumu</a>.');
	swfu.uploadSuccess(ImageUplaoder_File, 'OK:'+odp);
}
function ImageUploader_error(odp) {
	$('#image_upload_browse').removeAttr('disabled').val('');
	ImageUploader_SetInfo('Wystąpił błąd podczas wgrywania fotki.', false, true);
	swfu.uploadError(ImageUplaoder_File, 0, odp);
}


/**
* HANDLERS (zmodyfikowane)
*/

function swfuploadLoaded() {
	$('#image_upload_form').hide();
	$('#uploadBrowseLayer').css({width:'128px'});
	$('.swfupload_form').show();
}
function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		this.startUpload();
	} catch (ex) {
		this.debug(ex);
	}
}
function fileQueued(file) {
	try {
		//alert(var_dump(file));
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Dodano do kolejki");
		progress.toggleCancel(true, this);
	} catch (ex) {
		this.debug(ex);
	}
}
function fileQueueError(file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("Wybrano za dużo fotek. Odśwież stronę, by dodać kolejne zdjęcia!");
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("Plik jest za duży");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Nie można wysłać pustego pliku");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Nieprawidłowy format pliku");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Nieznany błąd");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}
function uploadStart(file) {
	try {
		ImageUploader_SetInfo('Trwa wgrywanie fotek.');

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Wysyłanie");
		progress.toggleCancel(true, this);
	}
	catch (ex) {
		this.debug(ex);
	}
	return true;
}
function uploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("Wysyłanie "+percent+"%");
	} catch (ex) {
		this.debug(ex);
	}
}
function uploadSuccess(file, serverData) {
	try {
		var temp =  serverData.split(':');
		if (temp[0] == 'OK') {
			wgrane_poprawnie.push(temp[1]);
			wgrane_handlers.push(file.id);
			wgrane_licznik++;

			if (wgrane_sprawdzaj) {
				wgrane_sprawdzaj = false;
				setTimeout("sprawdz_fotki();", 10000);
			}

			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setStatus("Przetwarzanie");
			progress.setComplete();
			progress.toggleCancel(false);
		} else {
			this.uploadError(file, 0, temp[1]);
		}
	} catch (ex) {
        this.debug(ex);
    }
}
function uploadError(file, errorCode, message) {

	try {
		this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Błąd wysyłania: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Błąd wysyłania");
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Błąd przesyłania danych");
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Błąd bezpieczeństwa");
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Przekroczono limit");
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Walidacja nie powiodła się. Pominięty");
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			// If there aren't any files left (they were all cancelled) disable the cancel button
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("Anulowane");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Zatrzymane");
			break;
		default:
			progress.setStatus(message);
			break;
		}
		
		progress.setError();
		progress.toggleCancel(false);
	} catch (ex) {
        this.debug(ex);
    }
}
function queueComplete(numFilesUploaded) {
	var html = '';

	if (wgrane_poprawnie.length == (numFilesUploaded+wgrane_uploaded)) {
		if (numFilesUploaded > 1) {
			html = 'Fotki zostały dodane do ';
		} else {
			html = 'Fotka została dodana do ';
		}
	} else {
		html = 'Dodano '+wgrane_poprawnie.length+ ' fotek z '+ (numFilesUploaded+wgrane_uploaded) + ' przesłanych do ';
	}
	if (typeof(modules_albums_moje) == 'boolean' && !modules_albums_moje) {
		html += 'moderacji w <a href="'+ImageUploader_AlbumUrl+'">albumie</a>.';
	} else {
		html += '<a href="'+ImageUploader_AlbumUrl+'">albumu</a>.';
	}

	wgrane_uploaded += numFilesUploaded;
	ImageUploader_SetInfo(html);
}

function sprawdz_fotki() {
	data = new Object();
	data.ids = wgrane_poprawnie;
	action('sprawdz_fotki', data);
}
function sprawdz_fotki_complete(ans) {
	url = ans.data.url;
	id = ans.data.id;
	
	for (key in wgrane_poprawnie) {
		if (typeof(url[wgrane_poprawnie[key]]) != 'undefined') {
			html = '<a href="'+ImageUploader_AlbumUrl+'zdjecia/'+id[wgrane_poprawnie[key]]+'" target="_blank"><img src="'+url[wgrane_poprawnie[key]]+'" /></a>';

			$('#'+wgrane_handlers[key]).html(html);
			delete(wgrane_poprawnie[key]);
			wgrane_licznik--;
		}
	}
	if (wgrane_licznik > 0) {
		setTimeout("sprawdz_fotki();", 10000);
	} else {
		wgrane_sprawdzaj = true;
	}
}
function sprawdz_fotki_error() {}


/**
* FILEPROGRESS
*/

/*
	A simple class for displaying file information and progress
	Note: This is a demonstration only and not part of SWFUpload.
	Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/

// Constructor
// file is a SWFUpload file object
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
function FileProgress(file, targetID) {
	this.fileProgressID = file.id;

	this.opacity = 100;
	this.height = 0;
	

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(file.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressBarBackground = document.createElement("div");
		progressBarBackground.className = "progressBarBackground";
		progressBarBackground.appendChild(progressBar);

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBarBackground);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.reset();
	}

	this.height = this.fileProgressWrapper.offsetHeight;
	this.setTimer(null);


}

FileProgress.prototype.setTimer = function (timer) {
	this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function (timer) {
	return this.fileProgressElement["FP_TIMER"] || null;
};

FileProgress.prototype.reset = function () {
	this.fileProgressElement.className = "progressContainer";

	this.fileProgressElement.childNodes[2].innerHTML = "&nbsp;";
	this.fileProgressElement.childNodes[2].className = "progressBarStatus";
	
	this.fileProgressElement.childNodes[3].className = "progressBarBackground";
//	this.fileProgressElement.childNodes[3].style.width = "0%";
	
	this.appear();	
};

FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].childNodes[0].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].childNodes[0].style.width = percentage + "%";

	this.appear();	
};
FileProgress.prototype.setComplete = function () {
//	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].childNodes[0].className = "progressBarComplete";
//	this.fileProgressElement.childNodes[3].childNodes[0].style.width = "";

	var oSelf = this;
//	this.setTimer(setTimeout(function () {
//		oSelf.disappear();
//	}, 10000));
};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

//	var oSelf = this;
//	this.setTimer(setTimeout(function () {
//		oSelf.disappear();
//	}, 5000));
};
FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 2000));
};
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

FileProgress.prototype.appear = function () {
	if (this.getTimer() !== null) {
		clearTimeout(this.getTimer());
		this.setTimer(null);
	}
	
	if (this.fileProgressWrapper.filters) {
		try {
			this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
		}
	} else {
		this.fileProgressWrapper.style.opacity = 1;
	}
		
	this.fileProgressWrapper.style.height = "";
	
	this.height = this.fileProgressWrapper.offsetHeight;
	this.opacity = 100;
	this.fileProgressWrapper.style.display = "";
	
};

// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {

	var reduceOpacityBy = 15;
	var reduceHeightBy = 4;
	var rate = 30;	// 15 fps

	if (this.opacity > 0) {
		this.opacity -= reduceOpacityBy;
		if (this.opacity < 0) {
			this.opacity = 0;
		}

		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100;
		}
	}

	if (this.height > 0) {
		this.height -= reduceHeightBy;
		if (this.height < 0) {
			this.height = 0;
		}

		this.fileProgressWrapper.style.height = this.height + "px";
	}

	if (this.height > 0 || this.opacity > 0) {
		var oSelf = this;
		this.setTimer(setTimeout(function () {
			oSelf.disappear();
		}, rate));
	} else {
		this.fileProgressWrapper.style.display = "none";
		this.setTimer(null);
	}
};
  
