function fileDialogStart()
{
	error_name = "";
	free_limits_error = false;
	server_limits_error = false;
}

function fileQueueError(fileObj, error_code, message) {
	try {
		switch(error_code)
		{
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				
				if (this.customSettings.is_free
					&& fileObj.size / 1024 > this.customSettings.upload_limit[0]
				){
					free_limits_error = true;
				}
				else
				{
					if (fileObj.size / 1024 > this.customSettings.upload_limit[1])
					{
						server_limits_error = true;
					}
				}
				
			break;
		
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				error_name += msgEmptyFile.replace('{filename}',fileObj.name);
			break;
		
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				error_name += msgWrongFormat.replace('{filename}',fileObj.name);
			break;
		
			default:
				showExceededLimits(message);
			break;
		}

	} catch (ex) { this.debug(ex); }

}

function fileDialogComplete(selected, num_files_queued, totalQueued) {
	try {
		if (free_limits_error && num_files_queued == 0)
		{
			var params = {
				freeLimit: this.customSettings.upload_limit[0]/1024,
				premiumLimit: this.customSettings.upload_limit[1]/1024
			};
			xajax_showModal('uploadLimitsExceeded', params);
		}
		
		if (server_limits_error && num_files_queued == 0)
		{
			var params = {
				freeLimit: this.customSettings.upload_limit[0]/1024,
				premiumLimit: this.customSettings.upload_limit[1]/1024
			};
			xajax_showModal('uploadServerLimits', params);
		}
		
		if (error_name != "" && num_files_queued == 0)
		{
			alert(error_name);
		}
		
		if (num_files_queued > 0) {
			
			if (error_name != "")
			{
				var msg = msgProblematicImages + "\n\n";
				msg += error_name;
				msg += "\n" + msgCannotBeUploaded;
				
				if (!confirm(msg))
				{
					//clear queue
					var i = 0;
					var file = this.getFile(i);
				
					while (file)
					{
						this.cancelUpload(file.id);
						
						file = this.getFile(++i);
					}

					
					return false;
				}
			}
			
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadProgress(fileObj, bytesLoaded) {

	try {
		this.customSettings.done_button.getElementsByTagName('input')[0].value = globalCancel;
		this.customSettings.done_button.style.display = "inline-block";
		var percent = Math.ceil((bytesLoaded / fileObj.size) * 100);

		var progress = new FileProgress(fileObj,  this.customSettings.upload_target);
		this.customSettings.progress_holder.style.display = 'block';
		//this.customSettings.current_file_progress.style.width = percent+"%";
		//this.customSettings.current_file_percent.innerHTML = percent+"%";
		progress.SetProgress(percent);
		if (percent === 100) {
			//progress.SetStatus("Creating thumbnail...");
			progress.SetStatus("<img src='img/ajax-loader-uploading.gif' /><span>"+globalUploading+"</span>");
			progress.ToggleCancel(false);
			progress.ToggleCancel(true, this, fileObj.id);
		} else {
			progress.SetStatus("<img src='img/ajax-loader-uploading.gif' /><span>"+globalUploading+"</span>");
			progress.ToggleCancel(true, this, fileObj.id);
		}
	} catch (ex) { this.debug(ex); }
}

function uploadSuccess(fileObj, server_data) {
	try {
		// upload.php returns the thumbnail id in the server_data, use that to retrieve the thumbnail for display
		
		//AddImage("thumbnail.php?id=" + server_data);
		
		var serverObj = eval('(' + server_data + ')');
		
		serverObj.path = this.customSettings.processing_img_path;
		
		
		
		if(serverObj.id == "ERROR")
		{
			AddLimitMessage(serverObj.id, serverObj.value);	
		}
		else
		{
			AddImage(serverObj.path, serverObj.id);
			AddInput(serverObj.id, serverObj.value);
		}
		
		xajax_processUpload(serverObj.id);
		
		var progress = new FileProgress(fileObj,  this.customSettings.upload_target);

		progress.SetStatus("<img src='img/ajax-loader-uploading.gif' />");
		progress.ToggleCancel(false);


	} catch (ex) { this.debug(ex); }
}

function uploadComplete(fileObj) {
	try {
		var status = this.getStats();
		var all = status.files_queued + status.successful_uploads + status.upload_errors + status.queue_errors;
		var done = all - status.files_queued;
		var percent = Math.ceil((done / all ) * 100); 
		
		this.customSettings.all_files_progress.style.width = percent+"%";
		this.customSettings.all_files_percent.innerHTML = percent+"%";
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued > 0) {
			this.startUpload();
		} else {
			var progress = new FileProgress(fileObj,  this.customSettings.upload_target);
			progress.SetComplete();
			progress.SetStatus(globalUploadCompleted);
			this.customSettings.progress_holder.style.display = 'none';
			
			status = this.getStats();
			status.successful_uploads = 0;
			status.upload_errors = 0;
			status.queue_errors = 0;
			this.setStats(status);
			this.customSettings.all_files_progress.style.width = "0%";
			this.customSettings.all_files_percent.innerHTML = "0%";
			progress.ToggleCancel(false);
			this.customSettings.done_button.getElementsByTagName('input')[0].value = globalDone;
			this.customSettings.done_button.style.display = "inline-block";
			
			this.file_progress_id = "divFileProgress";
			this.fileProgressWrapper = document.getElementById(this.file_progress_id);
			this.fileProgressElement = this.fileProgressWrapper.firstChild;
			this.fileProgressElement.childNodes[2].firstChild.nodeValue = "";

			xajax_afterUploadCallback(uploader_config.gallery_id);
			
			if (free_limits_error)
			{
				var params = {
					freeLimit: this.customSettings.upload_limit[0]/1024,
					premiumLimit: this.customSettings.upload_limit[1]/1024
				};					
				xajax_showModal('uploadLimitsExceeded', params);
			}
		}
	} catch (ex) { this.debug(ex); }
}

function uploadError(fileObj, error_code, message) {
	var image_name =  "error.gif";
	try {
		switch(error_code) {
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				try {
					var progress = new FileProgress(fileObj,  this.customSettings.upload_target);
					progress.SetCancelled();
					progress.SetStatus(globalUploadError);
					progress.ToggleCancel(true, this, fileObj.id);
				}
				catch (ex) { this.debug(ex); }
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				image_name = "uploadlimit.gif";
			break;
			case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
				//showModal();
				//SWFUpload.cancelUpload();
			break;
			default:
				//alert(message);
			break;
		}

		AddImage("img/" + image_name);

	} catch (ex) { this.debug(ex); }

}

function fileQueueFrontImageError(fileObj, error_code, message)
{
	try {
		var error_name = "";
		
		switch(error_code)
		{
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				error_name = this.customSettings.errorTooMany;
			break;
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				if(this.customSettings.is_free &&
					fileObj.size / 1024 < this.customSettings.upload_limits[1])
				{
					var params = {
						freeLimit: this.customSettings.upload_limits[0]/1024,
						premiumLimit: this.customSettings.upload_limits[1]/1024
					};
					xajax_showModal('uploadLimitsExceeded', params);
				}
				else
				{
					error_name = this.customSettings.errorTooBig;
					error_name = error_name.replace("[max_image_size]", this.customSettings.upload_limits[1]);
				}
			break;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				error_name = "Empty image file !";
			break;
			default:
				error_name = this.customSettings.errorGeneral;
			break;
		}
		
		var uploadInfo = $(this.customSettings.uploadInfo);
		uploadInfo.className = 'error';
		uploadInfo.update(error_name);
		uploadInfo.show();
		this.stopUpload();

	} catch (ex) { this.debug(ex); }
}

/**
 * Validates if there is a file selected.
 * @author Kamen Hursev
*/
function fileDialogFrontImageComplete(selected, num_files_queued, totalQueued)
{
	try
	{
		if (num_files_queued > 0)
		{
			this.startUpload();
		}
	}
	catch (ex)
	{
		this.debug(ex);
	}
}

/**
 * Displayls Status message when the upload begins.
 * @author Kamen Hursev
 */
function uploadFrontImageStart()
{
	var uploadInfo = $(this.customSettings.uploadInfo);
	uploadInfo.show();
	uploadInfo.className = '';
	uploadInfo.innerHTML = this.customSettings.messageUploading;
	uploadInfo.insert({'top':
					  new Element('img', {src: 'img/ajax-loader-uploading.gif'})
	});
}

/**
 * Upadates page after the server response.
 * @author Kamen Hursev
 */
function uploadFrontImageSuccess(fileObj, server_data)
{
	try
	{
		var serverObj = eval('(' + server_data + ')');
		var uploadInfo = $(this.customSettings.uploadInfo);
		if(serverObj.id == "ERROR")
		{	
			uploadInfo.className = 'error';
			uploadInfo.innerHTML = serverObj.error;
			
			uploadInfo.down('img').remove();
		}
		else
		{
			uploadInfo.hide();
			var frontImageConteiner = $(this.customSettings.frontImageConteiner);
			var image = frontImageConteiner.getElementsBySelector('img')[0];
			image.src = serverObj.path;
			displayChangeFrontImage();
			runFrontImageSlideshow = false;
			frontImage.up('div').setStyle({width: 'auto', height: 'auto'});
			frontImage.up('a').setStyle({width: 'auto', height: 'auto', cursor: 'auto'});
			frontImage.up('a').removeAttribute('href');
			
			if(typeof(_gaq) !== "undefined")
			{
				_gaq.push(['_trackEvent', 'Change Profile Image', 'Upload']);
			}
		}
	}
	catch (ex)
	{
		this.debug(ex);
	}
}


/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */

function FileProgress(fileObj, target_id) {
	this.file_progress_id = "divFileProgress";

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

		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("span");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(fileObj.name));

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

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

		this.fileProgressElement.appendChild(progressCancel);
		//this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(target_id).appendChild(this.fileProgressWrapper);
		FadeIn(this.fileProgressWrapper, 0);

	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.fileProgressElement.childNodes[2].firstChild.nodeValue = fileObj.name;
	}

	this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.SetProgress = function(percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";
	
}
FileProgress.prototype.SetComplete = function() {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetError = function() {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetCancelled = function() {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetStatus = function(status) {
	this.fileProgressElement.childNodes[1].innerHTML = status;
}

FileProgress.prototype.ToggleCancel = function(show, upload_obj, file_id) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (upload_obj) {
		this.fileProgressElement.childNodes[0].onclick = function() { upload_obj.cancelUpload(); return false; };
	}
}

function FadeIn(element, opacity) {
	var reduce_opacity_by = 15;
	var rate = 30;	// 15 fps


	if (opacity < 100) {
		opacity += reduce_opacity_by;
		if (opacity > 100) opacity = 100;

		if (element.filters) {
			try {
				element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 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.
				element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
			}
		} else {
			element.style.opacity = opacity / 100;
		}
	}

	if (opacity < 100) {
		setTimeout(function() { FadeIn(element, opacity); }, rate);
	}
}

function AddImage(src, id) {
	
	var new_img = new Element('img');
	/*new_img.style.margin = "5px";
	new_img.style.verticalAlign = "middle";*/
	
	//If we have an id we add the image in a separate container in order to be able to hide it if the image is deleted
	if(id != null) 
	{
		var thumbnail = new Element('div', {'class': 'thumbnail'}).update(new_img);
		
		var photo = new Element("div",
								{
								  'class': 'photo',
								  'id': 'thumbnails_'+id
								 }).update(thumbnail);
		
		$("thumbnails").insert({bottom: photo});
	}
	else
	{
		$("thumbnails").insert({bottom: new_img});
	}
	if (new_img.filters) {
		try {
			new_img.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			new_img.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
		}
	} else {
		new_img.setStyle({opacity: 0});
	}
	
	new_img.onload = function () { FadeIn(new_img, 0); };
	
	new_img.writeAttribute('src', src);
	
	new_img.setStyle({'marginTop':'12px'})
}

function AddInput(id, value) 
{
	var del_btn = new Element('a',
							  {'class': 'btn_delete',
								'title': globalClickToDelete}
							  ).update('<span>'+globalDelete+'</span>');
	var new_input = new Element("input", {type: 'text', 'value': value, 'id': id});
	var new_description = new Element("textarea").update(globalClickToAddDescription);
	
	var new_title_p = new Element("p");
	new_title_p.insert({bottom: del_btn});
	new_title_p.insert({bottom: new Element('label').update(globalRename+": ")});
	new_title_p.insert({bottom: new_input});
	
	var new_description_p = new Element("p");
	new_description_p.insert({bottom: new Element('label').update(globalDescription)});
	new_description_p.insert({bottom: new_description});
	
	$("thumbnails_"+id).insert({bottom: new_title_p});
	$("thumbnails_"+id).insert({bottom: new_description_p});

	del_btn.observe('click', function()
		{
			if (confirm(globalDeteleteConfim)) {
            	xajax_deleteImageBase(id);
            	
				$("thumbnails_"+id).remove();
            	
				var err_span = document.getElementById("ErrorSpan");
            	if(err_span)
            	{
            		$("thumbnails").removeChild(err_span);
            	}
        	}
		});

	//new_input.onclick = function () { this.className = 'inputedit'; };
	new_input.observe('change', function(event)
		{
			var elem = event.findElement();
			saveImgTitle(
							elem.readAttribute('id'),
							elem.value != '' ? elem.value : 'untitled'
						);
		});
	//new_input.onblur = function () { this.className = 'inputread'; };
	new_input.onload = function () { FadeIn(new_img, 0); };
	
	new_description.id = 'd'+id;
	new_description.onclick = function () { 
		this.style.color ="#000000";
		this.innerHTML = ''; 
		this.onclick = function(){};
	};
	new_description.onchange = 
		function() 
			{ 
				saveImgDescription(this.id, this.value != '' ? this.value : globalClickToAddDescription); 
			};
}

function AddLimitMessage(id, value)
{
	err_span = document.getElementById("ErrorSpan");
	document.getElementById("btnBrowse").disabled = true;
	if(!err_span)
	{
		var new_span = document.createElement("div");
		new_span.innerHTML = value;
		new_span.id = "ErrorSpan";
		document.getElementById("thumbnails").appendChild(new_span);
		this.getStats().files_queued = 0;
		return;
	}
	else
	{
		err_span.style.display = "inline";
	}
}

/*
function AddInput(id, value) 
{
	var new_title = document.createElement("span");
	var new_br_first = document.createElement("br");
	var new_input = document.createElement("input");
	var del_btn = document.createElement("img");
	var new_br = document.createElement("br");
	var new_description = document.createElement("textarea");
	var new_last_div = document.createElement("div");
	var holder = document.getElementById("thumbnails_"+id);
		
	holder.appendChild(new_title);
	holder.appendChild(new_br_first);
	holder.appendChild(new_input);
	holder.appendChild(del_btn);
	holder.appendChild(new_br);
	holder.appendChild(new_description);
	holder.appendChild(new_last_div);

	new_title.innerHTML = globalRename+": ";
	new_input.value = value;
	new_input.id = id;
	new_input.className = "inputread";
	new_input.onclick = function () { this.className = 'inputedit'; };
	new_input.onchange = function() { saveImgTitle(this.id, this.value!=''?this.value:'untitled'); };
	new_input.onblur = function () { this.className = 'inputread'; };
	new_input.onload = function () { FadeIn(new_img, 0); };
	
	del_btn.id = id;
	del_btn.src = "img/cancel.gif";
	del_btn.title = globalDelete;
	
	del_btn.onclick = 
		function()
		{
			if (confirm(globalDeteleteConfim)) {
            	xajax_deleteImageBase(this.id)
            	document.getElementById("thumbnails_"+this.id).style.display = "none";
            	var err_span = document.getElementById("ErrorSpan");
            	if(err_span)
            	{
            		document.getElementById("thumbnails").removeChild(err_span);
            	}
        	}
		};
	del_btn.className = "imbtn multiupload_positon_fix";
	
	new_description.rows = 3;
	new_description.className = "new_comment";
	new_description.id = 'd'+id;
	new_description.innerHTML = globalClickToAddDescription;
	new_description.innerHTML = globalClickToAddDescription;
	new_description.onclick = function () { 
		this.style.color ="#000000";
		this.innerHTML = ''; 
		this.onclick = function(){};
	};
	new_description.onchange = 
		function() 
			{ 
				saveImgDescription(this.id, this.value != '' ? this.value : globalClickToAddDescription); 
			};
}

function AddLimitMessage(id, value)
{
	err_span = document.getElementById("ErrorSpan");
	document.getElementById("btnBrowse").disabled = true;
	if(!err_span)
	{
		var new_span = document.createElement("div");
		new_span.innerHTML = value;
		new_span.id = "ErrorSpan";
		document.getElementById("thumbnails").appendChild(new_span);
		this.getStats().files_queued = 0;
		return;
	}
	else
	{
		err_span.style.display = "inline";
	}
}

function AddImage(src, id) {
	
	var new_img = document.createElement("img");
	//new_img.style.margin = "5px";
	//new_img.style.verticalAlign = "middle";
	
	//If we have an id we add the image in a separate container in order to be able to hide it if the image is deleted
	if(id != null) 
	{
		var img_section = document.createElement("span");
		var img_section_clear = document.createElement("div");
		img_section_clear.className = "div_clear";
		img_section.id = "thumbnails_"+id;
		
		img_section.className = "img_section";

		document.getElementById("thumbnails").appendChild(img_section);
		//document.getElementById("thumbnails").appendChild(img_section_clear);
		img_section.appendChild(new_img);
	}
	else
	{
		document.getElementById("thumbnails").appendChild(new_img);
	}
	if (new_img.filters) {
		try {
			new_img.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			new_img.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
		}
	} else {
		new_img.style.opacity = 0;
	}
	new_img.onload = function () { FadeIn(new_img, 0); };
	new_img.src = src;
}
*/
