// uploadState(n) - set upload state to n and return previous value
// uploadState() - get upload state
// 0 - upload not started
// 1 - upload in progress
// 2 - upload finished
var uploadState = function(state) {
	// function mode: get
	if (state == undefined) {
		if ($('#upload-button').data('state') == undefined) {
			return 0;
		} else {
			return $('#upload-button').data('state');
		}
	}
	// function mode: set
	var prev_state = $('#upload-button').data('state');
	if (prev_state == undefined) {
		prev_state = 0;
	}
	if (state > 0) {
		$('#button-newslot').addClass('button-gray-3');
		$('#updealer_id').get(0).disabled = true;
		$('#input_agreement').get(0).disabled = true;
		$('#text-agreement').addClass('text-gray-5');
		$('#upload-button').val(txt_str.FileUpload.dalsi_upload);
		$('#upload-button').data('state',state);
	} else {
		$('#button-newslot').removeClass('button-gray-3');
		$('#updealer_id').get(0).disabled = false;
		$('#input_agreement').get(0).disabled = false;
		$('#text-agreement').removeClass('text-gray-5');
		$('#upload-button').val(txt_str.FileUpload.nahrat);
		$('#upload-button').data('state',0);
	}
	return prev_state;
}
var setCurrentUpload = function(i) {
	var prev = i-1;
	// set previous file elements
	if (prev >=0) {
		$('#progress_info').attr('id','progress_info_'+prev); 
		$('#upload_status').attr('id','upload_status_'+prev); 
		$('#progress_bar').attr('id','progress_bar_'+prev);
		$('#upload_status').attr('id','upload_status_'+prev);
		// progress statistics
		$('#percent').attr('id','percent_'+prev);
		$('#speed').attr('id','speed_'+prev);
		$('#time').attr('id','time_'+prev);
		$('#current').attr('id','current_'+prev);
		$('#total_kbytes').attr('id','total_kbytes_'+prev);
		$('#remain').attr('id','remain_'+prev);
	}
	// set current file elements
	$('#progress_info_'+i).attr('id','progress_info'); 
	$('#upload_status_'+i).attr('id','upload_status'); 
	$('#progress_bar_'+i).attr('id','progress_bar'); 
	$('#upload_status_'+i).attr('id','upload_status');
	// progress statistics
	$('#percent_'+i).attr('id','percent');
	$('#speed_'+i).attr('id','speed');
	$('#time_'+i).attr('id','time');
	$('#current_'+i).attr('id','current');
	$('#total_kbytes_'+i).attr('id','total_kbytes');
	$('#remain_'+i).attr('id','remain');
	$('#input_info_description_'+i).val($('#input_initinfo_description_'+i).val());
	if($('#input_initinfo_private_file_'+i).attr('checked') == 1) $('#input_info_private_file_'+i).attr('checked', 1)
}

// show category form on the i-th file
var showCategoryForm = function(i) {
	$('#warning-fileinfo-'+i+'-3').addClass('nodisplay');
	var tmp;
	$.ajax({
		url: 'ajax.php',
		type: 'GET',
		data: 'rqdt=TRUE&iter='+i,
		dataType: 'json',
		success: function(result){
			if(result) $('#form-fileinfo-'+i+'-3').append(result.html_content);
			else alert('neni result');
			$('#input_category_id_'+i).change(changeFileType);

			//alert(result.data);
			//tmp = result;
			/*
			$('#ajaxEmalingSuccesMsg').fadeIn('slow', function(){
				setTimeout(function(){
					$('#ajaxEmalingSuccesMsg').fadeOut('slow');
					}, 2500);
			});
			*/
			}
		});
	//alert(tmp);
	//$('#form-fileinfo-'+i+'-3').append('<input type="text" name="test" value="baf" />');
	$('#form-fileinfo-'+i+'-3').removeClass('nodisplay');
}
// sets 
var setInputValue = function(el, value)
{
	$('#' + el).val(value);
	$('#' + el).data('_defaultValue',value);
}

var setFolderUploadLinks = function(content)
{
	$('#uploaded-folders').hide();
	$('#fileinfo-folder-0').append(content);
	$('#fileinfo-folder-0 .js-input-selectable').focus(function() {
		$(this).select();
	});

}

// modify file slot structure for usage as i-th slot
// newFileSlot - slot to be modified
// newFileSlotNum - slot number after modification
// [oldFileSlotNum] - slot number before modification (starts with 0, 0 is default)
// [setSlotGraphics] - whether or not modify visible slot number (true/false, true is default)
var setFileSlotNum = function(newFileSlot, newFileSlotNum, oldFileSlotNum, setSlotGraphics) {
	if (oldFileSlotNum == undefined) {
		oldFileSlotNum = 0;
	}
	if (newFileSlotNum == oldFileSlotNum) {
		return newFileSlot;
	}
	if (setSlotGraphics == undefined) {
		setSlotGraphics = true;
	}
	// unique number for status elements
	var newFileSlotNumUnique = newFileSlotNum == 0 ? '' : '_'+newFileSlotNum;
	var oldFileSlotNumUnique = oldFileSlotNum == 0 ? '' : '_'+oldFileSlotNum;
	var newFileSourceForm = newFileSlot.find('form.form-filesource');
	// file slot
	newFileSlot.attr('id','upload_slot_'+newFileSlotNum);
	// file source form
	newFileSourceForm.attr({
		'id': 'form_upload_'+newFileSlotNum,
		'name': 'form_upload_'+newFileSlotNum,
		'target': 'form_upload_'+newFileSlotNum+'_iframe'
	});
	
	var action = newFileSourceForm.attr('action');
	action = action.substr(0, (action.length-2)) + '0' + newFileSlotNum;
	newFileSourceForm.attr('action', action);
	
	// file source form variables
	newFileSourceForm.find(':input[name="this_file_num"]').val(newFileSlotNum);
	/*
	newFileSourceForm.find('#upload_file_'+oldFileSlotNum+'_folder').attr({
		'id': 'upload_file_'+newFileSlotNum+'_folder',
		'name': 'upload_file_folder_'+newFileSlotNum
	});
	newFileSourceForm.find('#upload_file_'+oldFileSlotNum+'_dealer').attr({
		'id': 'upload_file_'+newFileSlotNum+'_dealer',
		'name': 'updealer_id_'+newFileSlotNum
	});
	*/
	newFileSourceForm.find('#upload_file_'+oldFileSlotNum+'_folder').attr({
		'id': 'upload_file_'+newFileSlotNum+'_folder'
	});
	newFileSourceForm.find('#upload_file_'+oldFileSlotNum+'_dealer').attr({
		'id': 'upload_file_'+newFileSlotNum+'_dealer'
	});
	newFileSourceForm.find('#upfile_'+oldFileSlotNum).attr('id','upfile_'+newFileSlotNum);
	//newFileSourceForm.find('#upfile_'+newFileSlotNum).attr('name','upfile_'+newFileSlotNum);
	newFileSourceForm.find('#input_initinfo_description_'+oldFileSlotNum).attr('id','input_initinfo_description_'+newFileSlotNum);
	newFileSourceForm.find('#input_initinfo_private_file_'+oldFileSlotNum).attr('id','input_initinfo_private_file_'+newFileSlotNum);
	// file source form graphics
	newFileSlot.find('table.table-filesource').attr('id','table-filesource-'+newFileSlotNum);
	newFileSlot.find('.block-fileinitdata').attr('id','block-fileinitdata-'+newFileSlotNum);
	newFileSlot.find('label[for="input_initinfo_description_'+oldFileSlotNum+'"]').attr('for','input_initinfo_description_'+newFileSlotNum);
	newFileSlot.find('label[for="input_initinfo_private_file_'+oldFileSlotNum+'"]').attr('for','input_initinfo_private_file_'+newFileSlotNum);
	if (setSlotGraphics) {
		newFileSourceForm.find('span.this-file-num').text((newFileSlotNum+1)+'.');
	}
	var newInitBookmarksList = newFileSlot.find('ul.list-fileinitinfo-'+oldFileSlotNum).removeClass('list-fileinitinfo-'+oldFileSlotNum).addClass('list-fileinitinfo-'+newFileSlotNum);
	var newInitBookmarksContent = newFileSlot.find('.tab-fileinitinfo-'+oldFileSlotNum).removeClass('tab-fileinitinfo-'+oldFileSlotNum).addClass('tab-fileinitinfo-'+newFileSlotNum);
	newInitBookmarksContent.each(function(i) {
		$(this).attr('id','fileinitinfo-'+newFileSlotNum+'-'+i);
	});
	newInitBookmarksList.find('li').bookmarksFor(newInitBookmarksContent);
	// file data block
	var newFileData = newFileSlot.find('#upload_div_'+oldFileSlotNum).attr('id','upload_div_'+newFileSlotNum);
	newFileData.find('#form_upload_'+oldFileSlotNum+'_iframe').attr({
		'id': 'form_upload_'+newFileSlotNum+'_iframe',
		'name': 'form_upload_'+newFileSlotNum+'_iframe'
	});
	//newFileData.find('#form-fileinfo-'+oldFileSlotNum+'-2').attr('id','form-fileinfo-'+newFileSlotNum+'-2');
	newFileData.find('#form-fileinfo-'+oldFileSlotNum+'-3').attr({
		'id': 'form-fileinfo-'+newFileSlotNum+'-3',
		'target': 'iframe-fileinfo-'+newFileSlotNum+'-3'
	}).submit(validateFileCategory);	
	
	newFileData.find('#form-fileinfo-'+oldFileSlotNum+'-2').attr({
		'id': 'form-fileinfo-'+newFileSlotNum+'-2'
	}).submit(submitBasicInfo);
	
	newFileData.find('#iframe-fileinfo-'+oldFileSlotNum+'-3').attr({
		'id': 'iframe-fileinfo-'+newFileSlotNum+'-3',
		'name': 'iframe-fileinfo-'+newFileSlotNum+'-3'
	});
	newFileData.find('#fileinfo-fileid-'+oldFileSlotNum).attr("id", 'fileinfo-fileid-'+newFileSlotNum);
	// file data block variables
	newFileData.find('#input_info_description_'+oldFileSlotNum).attr('id','input_info_description_'+newFileSlotNum);
	newFileData.find('#input_info_private_file_'+oldFileSlotNum).attr('id','input_info_private_file_'+newFileSlotNum);
	newFileData.find('#input_category_id_'+oldFileSlotNum).attr('id','input_category_id_'+newFileSlotNum).change(changeFileType);
	newFileData.find('#input_audio_interpret_'+oldFileSlotNum).attr('id','input_audio_interpret_'+newFileSlotNum);
	newFileData.find('#input_audio_keywords_'+oldFileSlotNum).attr('id','input_audio_keywords_'+newFileSlotNum);
	newFileData.find('#input_audio_description_'+oldFileSlotNum).attr('id','input_audio_description_'+newFileSlotNum);
	newFileData.find('#input_audio_album_'+oldFileSlotNum).attr('id','input_audio_album_'+newFileSlotNum);
	newFileData.find('#input_audio_track_name_'+oldFileSlotNum).attr('id','input_audio_track_name_'+newFileSlotNum);
	newFileData.find('#input_audio_genre_'+oldFileSlotNum).attr('id','input_audio_genre_'+newFileSlotNum);
	newFileData.find('#input_audio_time_'+oldFileSlotNum).attr('id','input_audio_time_'+newFileSlotNum);
	newFileData.find('#input_video_title_'+oldFileSlotNum).attr('id','input_video_title_'+newFileSlotNum);
	newFileData.find('#input_video_keywords_'+oldFileSlotNum).attr('id','input_video_keywords_'+newFileSlotNum);
	newFileData.find('#input_video_description_'+oldFileSlotNum).attr('id','input_video_description_'+newFileSlotNum);
	newFileData.find('#input_video_genre_'+oldFileSlotNum).attr('id','input_video_genre_'+newFileSlotNum);
	newFileData.find('#input_video_source_'+oldFileSlotNum).attr('id','input_video_source_'+newFileSlotNum);
	newFileData.find('#input_video_producer_'+oldFileSlotNum).attr('id','input_video_producer_'+newFileSlotNum);
	newFileData.find('#input_video_actors_'+oldFileSlotNum).attr('id','input_video_actors_'+newFileSlotNum);
	newFileData.find('#input_video_language_'+oldFileSlotNum).attr('id','input_video_language_'+newFileSlotNum);
	newFileData.find('#input_game_title_'+oldFileSlotNum).attr('id','input_game_title_'+newFileSlotNum);
	newFileData.find('#input_game_keywords_'+oldFileSlotNum).attr('id','input_game_keywords_'+newFileSlotNum);
	newFileData.find('#input_game_description_'+oldFileSlotNum).attr('id','input_game_description_'+newFileSlotNum);
	newFileData.find('#input_game_genre_'+oldFileSlotNum).attr('id','input_game_genre_'+newFileSlotNum);
	newFileData.find('#input_doc_title_'+oldFileSlotNum).attr('id','input_doc_title_'+newFileSlotNum);
	newFileData.find('#input_doc_keywords_'+oldFileSlotNum).attr('id','input_doc_keywords_'+newFileSlotNum);
	newFileData.find('#input_doc_usage_'+oldFileSlotNum).attr('id','input_doc_usage_'+newFileSlotNum);
	// file data block graphics
	var newBookmarksList = newFileData.find('ul.list-fileinfo-'+oldFileSlotNum).removeClass('list-fileinfo-'+oldFileSlotNum).addClass('list-fileinfo-'+newFileSlotNum);
	var newBookmarksContent = newFileData.find('.tab-fileinfo-'+oldFileSlotNum).removeClass('tab-fileinfo-'+oldFileSlotNum).addClass('tab-fileinfo-'+newFileSlotNum);
	newBookmarksContent.each(function(i) {
		$(this).attr('id','fileinfo-'+newFileSlotNum+'-'+i);
	});
	newBookmarksList.find('li').bookmarksFor(newBookmarksContent);
	newFileData.find('#progress_info'+oldFileSlotNumUnique).attr('id','progress_info'+newFileSlotNumUnique);
	newFileData.find('#progress_bar'+oldFileSlotNumUnique).attr('id','progress_bar'+newFileSlotNumUnique);
	newFileData.find('#upload_status'+oldFileSlotNumUnique).attr('id','upload_status'+newFileSlotNumUnique);
	newFileData.find('#percent'+oldFileSlotNumUnique).attr('id','percent'+newFileSlotNumUnique);
	newFileData.find('#speed'+oldFileSlotNumUnique).attr('id','speed'+newFileSlotNumUnique);
	newFileData.find('#time'+oldFileSlotNumUnique).attr('id','time'+newFileSlotNumUnique);
	newFileData.find('#current'+oldFileSlotNumUnique).attr('id','current'+newFileSlotNumUnique);
	newFileData.find('#total_kbytes'+oldFileSlotNumUnique).attr('id','total_kbytes'+newFileSlotNumUnique);
	newFileData.find('#remain'+oldFileSlotNumUnique).attr('id','remain'+newFileSlotNumUnique);
	newFileData.find('label[for="input_file_linkdown_'+oldFileSlotNum+'"]').attr('for','input_file_linkdown_'+newFileSlotNum);
	newFileData.find('label[for="input_file_linkedit_'+oldFileSlotNum+'"]').attr('for','input_file_linkedit_'+newFileSlotNum);
	newFileData.find('label[for="input_info_description_'+oldFileSlotNum+'"]').attr('for','input_info_description_'+newFileSlotNum);
	newFileData.find('label[for="input_info_private_file_'+oldFileSlotNum+'"]').attr('for','input_info_private_file_'+newFileSlotNum);
	newFileData.find('#input_file_linkdown_'+oldFileSlotNum).attr({
		'id': 'input_file_linkdown_'+newFileSlotNum,
		'name': 'file_'+newFileSlotNum+'_linkdown'
	});
	newFileData.find('#input_file_linkedit_'+oldFileSlotNum).attr({
		'id': 'input_file_linkedit_'+newFileSlotNum,
		'name': 'file_'+newFileSlotNum+'_linkedit'
	});
	newFileData.find('#warning-fileinfo-'+oldFileSlotNum+'-3').attr('id','warning-fileinfo-'+newFileSlotNum+'-3');
	newFileData.find('#warning-fileinfo-'+oldFileSlotNum+'-2').attr('id','warning-fileinfo-'+newFileSlotNum+'-2');
	newFileData.find('.infoholder-form-fileinfo-'+oldFileSlotNum+'-3').removeClass('infoholder-form-fileinfo-'+oldFileSlotNum+'-3').addClass('infoholder-form-fileinfo-'+newFileSlotNum+'-3');
	newFileData.find('label[for="input_info_description_'+oldFileSlotNum+'"]').attr('for','input_info_description_'+newFileSlotNum);
	newFileData.find('label[for="input_info_private_file_'+oldFileSlotNum+'"]').attr('for','input_info_private_file_'+newFileSlotNum);
	newFileData.find('label[for="input_category_id_'+oldFileSlotNum+'"]').attr('for','input_category_id_'+newFileSlotNum);
	newFileData.find('label[for="input_audio_interpret_'+oldFileSlotNum+'"]').attr('for','input_audio_interpret_'+newFileSlotNum);
	newFileData.find('label[for="input_audio_keywords_'+oldFileSlotNum+'"]').attr('for','input_audio_keywords_'+newFileSlotNum);
	newFileData.find('label[for="input_audio_description_'+oldFileSlotNum+'"]').attr('for','input_audio_description_'+newFileSlotNum);
	newFileData.find('label[for="input_audio_album_'+oldFileSlotNum+'"]').attr('for','input_audio_album_'+newFileSlotNum);
	newFileData.find('label[for="input_audio_track_name_'+oldFileSlotNum+'"]').attr('for','input_audio_track_name_'+newFileSlotNum);
	newFileData.find('label[for="input_audio_genre_'+oldFileSlotNum+'"]').attr('for','input_audio_genre_'+newFileSlotNum);
	newFileData.find('label[for="input_audio_time_'+oldFileSlotNum+'"]').attr('for','input_audio_time_'+newFileSlotNum);
	newFileData.find('label[for="input_video_title_'+oldFileSlotNum+'"]').attr('for','input_video_title_'+newFileSlotNum);
	newFileData.find('label[for="input_video_keywords_'+oldFileSlotNum+'"]').attr('for','input_video_keywords_'+newFileSlotNum);
	newFileData.find('label[for="input_video_description_'+oldFileSlotNum+'"]').attr('for','input_video_description_'+newFileSlotNum);
	newFileData.find('label[for="input_video_genre_'+oldFileSlotNum+'"]').attr('for','input_video_genre_'+newFileSlotNum);
	newFileData.find('label[for="input_video_source_'+oldFileSlotNum+'"]').attr('for','input_video_source_'+newFileSlotNum);
	newFileData.find('label[for="input_video_producer_'+oldFileSlotNum+'"]').attr('for','input_video_producer_'+newFileSlotNum);
	newFileData.find('label[for="input_video_actors_'+oldFileSlotNum+'"]').attr('for','input_video_actors_'+newFileSlotNum);
	newFileData.find('label[for="input_video_language_'+oldFileSlotNum+'"]').attr('for','input_video_language_'+newFileSlotNum);
	newFileData.find('label[for="input_game_title_'+oldFileSlotNum+'"]').attr('for','input_game_title_'+newFileSlotNum);
	newFileData.find('label[for="input_game_keywords_'+oldFileSlotNum+'"]').attr('for','input_game_keywords_'+newFileSlotNum);
	newFileData.find('label[for="input_game_description_'+oldFileSlotNum+'"]').attr('for','input_game_description_'+newFileSlotNum);
	newFileData.find('label[for="input_game_genre_'+oldFileSlotNum+'"]').attr('for','input_game_genre_'+newFileSlotNum);
	newFileData.find('label[for="input_doc_title_'+oldFileSlotNum+'"]').attr('for','input_doc_title_'+newFileSlotNum);
	newFileData.find('label[for="input_doc_keywords_'+oldFileSlotNum+'"]').attr('for','input_doc_keywords_'+newFileSlotNum);
	newFileData.find('label[for="input_doc_usage_'+oldFileSlotNum+'"]').attr('for','input_doc_usage_'+newFileSlotNum);
	
	newFileData.find('#basic_edit_file_id_'+oldFileSlotNum).attr('id','basic_edit_file_id_'+newFileSlotNum);
	newFileData.find('#basicinfo_input_save_'+oldFileSlotNum).attr('id','basicinfo_input_save_'+newFileSlotNum);
	newFileData.find('#userinfo_input_save_'+oldFileSlotNum).attr('id','userinfo_input_save_'+newFileSlotNum);
//	$('#form-fileinfo-'+newFileSlotNum+'-2').submit(function(){alert('submituju klon')});

	return newFileSlot;
};
var refreshFileSlotsNums = function() {
	var nonEmptyFileSlots = $('div.block-fileslot').filter(function() {
		if ($(this).data('_emptySlot')) {
			return false;
		}
		return true;
	});
	var oldFileSlotNum;

	for (var i = 0; i < nonEmptyFileSlots.length; i++) {
		oldFileSlotNum = +$(nonEmptyFileSlots[i]).find(':input[name="this_file_num"]').val();
		setFileSlotNum($(nonEmptyFileSlots[i]), i, oldFileSlotNum, false);
	}
};
var startUpload = function() {
	//refreshFileSlotsNums();
	uploadFiles();
	//window.alert('upload!'); //@todo: delete
};
$(function() {
	// folder select
	$('#exfolder_0').change(function() {
		// new folder
		if (this.selectedIndex == 1) {
			$('.folder-new-name').show();
			$('.folder-new-desc').show();
			$(':input[name="upfolder_0"]').labelNodes();
			$(':input[name="description_0"]').labelNodes();
		// existing or none folder
		} else {
			$('.folder-new-name').hide();
			$('.folder-new-desc').hide();
			$(':input[name="upfolder_0"]').val('');
			$(':input[name="description_0"]').val('');
		}
	});
	$('.tooltip-folder-controller').click(
		function()
		{
			$('#tooltip-folder').toggle();
		}
	);
	$('.tooltip-folder-controller').hover(
		function(){return},
		function() {
			$('#tooltip-folder').hide();
		}
	);
	$('.tooltip-dealer-controller').click(
		function()
		{
			$('#tooltip-dealer').toggle();
		}
	);
	$('.tooltip-dealer-controller').hover(
		function(){},
		function()
		{
			$('#tooltip-dealer').hide();
		}
	);
	// file data switch availability
	var fileDataLogic = function() {
		var thisFileSlot = $(this).parents('div.block-fileslot').eq(0);
		var button = $(this).parents('table').eq(0).find('td.edit a');
		var thisFileData = thisFileSlot.find('div.block-filedata');
		if ($(this).val().length) {
			button.removeClass('nodisplay');
		} else {
			button.addClass('nodisplay');
			thisFileData.addClass('nodisplay');
		}
	};
	$('table.table-filesource input[type="file"]').each(fileDataLogic).change(fileDataLogic);
	// file data switch
	$('table.table-filesource td.edit a').click(function(e) {
		var thisFileSlot = $(this).parents('div.block-fileslot').eq(0);
		var infoHolder = thisFileSlot.find('div.infoholder');
		infoHolder.empty();
		var thisFileNum = thisFileSlot.find(':input[name="this_file_num"]').val();
		var thisFileData
		//if (thisFileNum <= uploaded_files_count-1) {
		if (inArray(thisFileNum, uploaded_files_array)){
			// show bookmarks with file data
			thisFileData = thisFileSlot.find('div.block-filedata');
		} else {
			// show different bookmarks with file data
			thisFileData = thisFileSlot.find('div.block-fileinitdata');
		}
		thisFileData.toggleClass('nodisplay');
		infoHolder.toggleClass('nodisplay');
		$(this).toggleClass('button-gray-1');
		e.preventDefault();
	});
	$('div.block-fileslot div.infoholder').click(function() {
		var thisFileSlot = $(this).parents('div.block-fileslot').eq(0);
		thisFileSlot.find('table.table-filesource td.edit a').click();
	});
	// add a new file slot button
	$('#button-newslot').click(function(e) {
		// stop if upload is in progress or finished
		if (uploadState() > 0) {
			return false;
		}
		// create empty file slot
		var newFileSlotNum = slots_count; // slot number after modification (starts with 0)
		var oldFileSlotNum = 0; // slot number before modification
		if (newFileSlotNum+1 >= max_upload_slots) {
			$(this).hide();
			if (newFileSlotNum+1 > max_upload_slots) { // stop duplication if max. slots count has been exceeded
				return false;
			}
		}
		// create empty file slot
		var newFileSlot = emptyFileSlot.clone(true);
		// modify file slot
		newFileSlot = setFileSlotNum(newFileSlot, newFileSlotNum, oldFileSlotNum);
		newFileSlot.find('table.table-filesource input[type="file"]').each(fileDataLogic);
		// append file slot
		newFileSlot.appendTo('.block-uploadslots');
		
		//IE hack pro dynamicky vytvorene iframy
		iFrameID = 'form_upload_'+newFileSlotNum+'_iframe';
		if(self.frames[iFrameID].name != iFrameID) { self.frames[iFrameID].name = iFrameID; }
		
		e.preventDefault();
		slots_count++;
		return false;
	});
	
	// create empty file form
	var emptyFileSlot = $('#upload_slot_0').clone(true);
	// start upload button
	$('#upload-button').click(function() {
		// check if upload is in progress
		if ($(this).data('state') == 1) {
			var stopUpload = window.confirm(txt_str.FileUpload.prerusit_upload.replace(/\[EOL\]/g,"\n"));
			if (stopUpload) {
				resetForm();
			}
			return false;
		// check if upload is finished
		} else if ($(this).data('state') == 2) {
			resetForm();
			return false;
		}
		// check dealer ID
		if ($(this).data('userUnlogged') && !$.trim($('#updealer_id').val()).length && !$(this).data('ignoreDealerUserID')) {
			$('#window-noDealerUserID-1').onTopWindowOpen();
			return false;
		}

		var infoHolder = $('div.infoholder-uploadform');
		infoHolder.empty();
		var errors = new Array();
		// check folder
		if ($('#exfolder_0').get(0).selectedIndex == 1 && ($('#upfolder_0').val() == $('#upfolder_0').data('_labelText') || !$.trim($('#upfolder_0').val()).length)) {
			errors.push(txt_str.FileUpload.zadejte_slozku);
		}
		// get all non-empty file fields
		var filesToUpload = $(':input[type="file"]').filter(function() {
			if (!$.trim($(this).val()).length) {
				return false;
			}
			return true;
		});
		// check files
		var forbiddenFiles = false;
		var fileNameFull;
		var fileName;
		for (var i=0; i < filesToUpload.length; i++) {
			fileNameFull = filesToUpload[i].value;
			if (fileNameFull.indexOf('/') > -1)
				fileName = fileNameFull.substring(fileNameFull.lastIndexOf('/')+1,fileNameFull.length);
			else
				fileName = fileNameFull.substring(fileNameFull.lastIndexOf('\\')+1,fileNameFull.length);
			if (fileName.match(/([^\/\\]+)\.(sh|php|php3|php4|php5|py|shtml|phtml|cgi|pl|plx|htaccess|htpasswd)$/i) ) {
				forbiddenFiles = true;
				break;
			}
		}

		if (!filesToUpload.length) {
			errors.push(txt_str.FileUpload.zadejte_soubor);
		} else if(forbiddenFiles) {
			errors.push(txt_str.FileUpload.zakazany_soubor);
		}
		// check terms
		if (!$(':input[name="agreement"]').is(':checked')) {
			errors.push(txt_str.FileUpload.accept_terms);
		}

		if (errors.length) {
			// don´t start upload
			var errorBox = new infobox('error');
			errorBox.addText(errors);
			infoHolder.append(errorBox.jquery);
			return false;
		} else {
			// start upload!
			/* filesToUpload.each(function() {
				this.disabled = true;
			})*/
			// hide unused file slots and mark them as empty
			var emptyFileSlots = $(':input[type="file"]').filter(function() {
				if (!$.trim($(this).val()).length) {
					return true;
				}
				return false;
			});
			//});
			emptyFileSlots.each(function() {
				$(this).parents('div.block-fileslot').eq(0).data('_emptySlot',true).fadeTo(300,0.05,function() {
					$(this).slideUp(200,function() {
						$(this).remove();
					});
				});
			});
			window.setTimeout(startUpload,1000);
			return false;
		}
	});
});

// Submit the upload form
function uploadFiles(number){
	//overeni souboru
	if (typeof(number)=='undefined') number=0;
	if(document.getElementById('form_upload_'+number) == null && number <= 10)
	{
		uploadFiles(number+1);
		return;
	}
	setCurrentUpload(number);
	if (typeof(max_upload_slots)=='undefined')
		var maxslots = 10;
	else
		var maxslots = max_upload_slots;	
	if (typeof(number)=='undefined' || number==0){
		var total_uploads = 0;
		for(var f = 0; f < maxslots; f++){
			if (document.getElementById('form_upload_'+f))
				for(var i = 0; i < upload_range; i++){
					if(document.getElementById('form_upload_'+f).elements['upfile_' + i])
						if(document.getElementById('form_upload_'+f).elements['upfile_' + i].value != ""){ total_uploads++; }
				}
		}
		if (!total_uploads){
			alert(txt_str.FileUpload.zadejte_soubor);
			return false;
		}  else {
			uploaded_files_count = 0;
			uploaded_files_array = new Array();
		}
	}
	if (typeof(number)=='undefined')
		if(document.getElementById('folder_upload'))
			var slozka = document.getElementById('exfolder_0').selectedIndex;
			if (document.getElementById('exfolder_0').selectedIndex==1){
				//vytvoreni slozky
				if(document.getElementById('folder_upload').upfolder_0.value==""){
					alert(txt_str.FileUpload.zadejte_slozku);
					return false;
				}else{
					for (ex=0;ex<document.getElementById('exfolder_0').options.length;ex++){
						if (document.getElementById('folder_upload').upfolder_0.value==document.getElementById('exfolder_0').options[ex].text){
							alert(txt_str.FileUpload.slozka_jiz_existuje);
							document.getElementById('exfolder_0').selectedIndex = ex;
							//document.getElementById('exfolder_0').onchange();
							$('#exfolder_0').change();
							return false;
						}
					}
					//nahrani slozky
					if(document.getElementById('progress_info')){
						document.getElementById('progress_info').innerHTML = txt_str.FileUpload.vytvarim_slozku;
						document.getElementById('progress_bar').style.display="none";
					}
					if(document.getElementById('upload_folder_div')){
						document.getElementById('upload_folder_div').style.display = "";
					}
					document.getElementById('folder_upload').submit();
					document.getElementById('block-folderdata').style.display = "block";
					
					
					return false; 
				}
			}
	if (typeof(number)=='undefined')
		number = '0';
	if(checkFileNameFormat(number)){ return false; }
	if(checkAllowFileExtensions(number)){ return false; }
	
	if (document.getElementById('upload_file_'+number+'_folder')){
			if (document.getElementById('exfolder_0')){
			document.getElementById('upload_file_'+number+'_folder').value = document.getElementById('exfolder_0').options[document.getElementById('exfolder_0').selectedIndex].value;
			document.getElementById('upload_file_'+number+'_dealer').value = document.getElementById('updealer_id').value;

		}
	}
	uploaded_files_array.push(number);
	uploaded_files_count++;
	
	document.getElementById('form_upload_'+number).submit();
	
	var button = $('#table-filesource-'+number+' td.edit a');
	var thisFileSlot = button.parents('div.block-fileslot').eq(0);
	var infoHolder = thisFileSlot.find('div.infoholder');
	infoHolder.empty();
	thisFileSlot.find('div.block-fileinitdata').addClass('nodisplay');
	var thisFileData = thisFileSlot.find('div.block-filedata');
	if(thisFileData.hasClass('nodisplay'))
	{
		thisFileData.toggleClass('nodisplay');
		infoHolder.toggleClass('nodisplay');
		button.toggleClass('button-gray-1');
	}
	uploadState(1);

	iniProgressRequest(number);
}


var disallow_extensions = /(sh|php|php3|php4|php5|py|shtml|phtml|cgi|pl|plx|htaccess|htpasswd)$/i;
var allow_extensions = /(jpg|jpeg|gif|bmp)$/i;
var check_file_name_format = 0;
var check_disallow_extensions = 1;
var check_allow_extensions = 0;
var check_null_file_count = 1;
var check_duplicate_file_count = 1;
var max_upload_slots = 10;
var progress_bar_width = 720;
var tmp_sid;
var file_upload_action_path = '';
var status_action_path = '';

var uploaded_files_count = 0;
var uploaded_files_array = new Array();

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

var showLinks = function(number){
	$('ul.list-fileinfo-'+number+' li').showBookmark(1);
};

var upload_range = 1;
var get_status_speed;
var get_status_url;
var get_data_loop = false;
var seconds = 0;
var minutes = 0;
var hours = 0;
var info_width = 0;
var info_bytes = 0;
var info_time_width = 500;
var info_time_bytes = 15;
var cedric_progress_bar = 0;
var cedric_hold = true;
var total_upload_size = 0;

// Check the file format before uploading
function checkFileNameFormat(){
	if(!check_file_name_format){ return false; }
	
	for(var i = 0; i < upload_range; i++){
		if(document.getElementById('form_upload_'+number).elements['upfile_' + i].value != ""){
			var string = document.getElementById('form_upload_'+number).elements['upfile_' + i].value;
			var num_of_last_slash = string.lastIndexOf("\\");

			if(num_of_last_slash < 1){ num_of_last_slash = string.lastIndexOf("/"); }

			var file_name = string.slice(num_of_last_slash + 1, string.length);
			var re = /^[\w][\w\.\-]{1,32}$/i;
				
			if(!re.test(file_name)){	
				alert(txt_str.FileUpload.nespravny_format_souboru + "\n\n" + txt_str.FileUpload.format_podminka_1 + "\n" + txt_str.FileUpload.format_podminka_2 + "\n" + txt_str.FileUpload.format_podminka_3 + "\n");
				return true;
			}
		}
	}
	return false;
}

// Check for legal file extentions
function checkAllowFileExtensions(number){
	if(!check_allow_extensions){ return false; }
	
	for(var i = 0; i < upload_range; i++){
		if(document.getElementById('form_upload_'+number).elements['upfile_' + i].value != ""){
			if(!document.getElementById('form_upload_'+number).elements['upfile_' + i].value.match(allow_extensions)){
				var string = document.getElementById('form_upload_'+number).elements['upfile_' + i].value;
				var num_of_last_slash = string.lastIndexOf("\\");

				if(num_of_last_slash < 1){ num_of_last_slash = string.lastIndexOf("/"); }

				var file_name = string.slice(num_of_last_slash + 1, string.length);
				var file_extension = file_name.slice(file_name.indexOf(".")).toLowerCase();
				
				alert(txt_str.FileUpload.zakazany_soubor_s_priponou.replace('[extension]', file_extension));
				return true;
			}
		}
	}
	return false;
}

// Make sure the user selected at least one file
function checkNullFileCount(number){
	if(!check_null_file_count){ return false; }
  	
	var null_file_count = 0;
  	
	for(var i = 0; i < upload_range; i++){
		if(!document.getElementById('form_upload_'+number)) continue;
		if(document.getElementById('form_upload_'+number).elements['upfile_' + i].value == ""){ null_file_count++; }
	}
  	
	if(null_file_count == upload_range){
		//alert("Please Choose A File To Upload.");
		return true;
	}
	else{ return false; }
}


// Handle user pressing 'Enter' in the upload slots
function handleKey(event){
        if(document.all){ if(window.event.keyCode == 13){ return false; } }
        else{ if(event && event.which == 13){ return false; } }
}



function showCurrentUploadProgress(number)
{
	button = $('#table-filesource-'+number+' td.edit a');
	thisFileSlot = button.parents('div.block-fileslot').eq(0);
	infoHolder = thisFileSlot.find('div.infoholder');
	infoHolder.empty();
	thisFileNum = thisFileSlot.find(':input[name="this_file_num"]').val();
	
	thisFileData = thisFileSlot.find('div.block-fileinitdata');
	alert(thisFileData.style);
	thisFileData.toggleClass('nodisplay');
	
	thisFileData = thisFileSlot.find('div.block-filedata');
	thisFileData.toggleClass('nodisplay');
	infoHolder.toggleClass('nodisplay');
	button.toggleClass('button-gray-1');
}

// Reset the file upload page 
function resetForm(){ 
	location.href = self.location; 
}

// Hide the progress bar
function hideProgressBar(){ document.getElementById('progress_bar').style.display = "none"; }

// Initialize the file upload page
function iniFilePage(number){
	if (typeof(number)=='undefined')
		number = '0';
	resetProgressBar();
	
	for(var i = 0; i < upload_range; i++){
		document.getElementById('form_upload_'+number).elements['upfile_' + i].disabled = false;
		document.getElementById('form_upload_'+number).elements['upfile_' + i].value = "";
	}
	
	document.getElementById('progress_info').innerHTML = "";
	document.getElementById('upload_button').disabled = false;
	document.getElementById('progress_bar').style.display = "none";
	document.getElementById('form_upload_'+number).reset();
}

// Reset the progress bar
function resetProgressBar(){
	get_status_url = "";
	get_data_loop = false;
	seconds = 0;
	minutes = 0;
	hours = 0;
	info_width = 0;
	info_bytes = 0;
	cedric_hold = true;
	total_upload_size = 0;
	
	document.getElementById('upload_status').style.width = '0px';
	document.getElementById('percent').innerHTML = '0%';
	document.getElementById('current').innerHTML = 0;
	document.getElementById('total_kbytes').innerHTML = '';
	document.getElementById('time').innerHTML = 0;
	document.getElementById('remain').innerHTML = 0;
	document.getElementById('speed').innerHTML = 0;
}

// Stop the upload
function stopUpload(){
	try{ window.stop(); }
	catch(e){
		try{ document.execCommand('Stop'); }
		catch(e){} 
	}
}

// Make the progress bar smooth
function smoothCedricStatus(){
	if(info_width < progress_bar_width && !cedric_hold){
		info_width++;
		if(document.getElementById('upload_status')) document.getElementById('upload_status').style.width = info_width + 'px';
	}
	
	if(get_data_loop){ self.setTimeout("smoothCedricStatus()", info_time_width); }
}

// Make the bytes uploaded smooth
function smoothCedricBytes(){
	if(info_bytes < total_upload_size && !cedric_hold){
		info_bytes++;
		if(document.getElementById('current')) document.getElementById('current').innerHTML = info_bytes;
	}
	
	if(get_data_loop){ self.setTimeout("smoothCedricBytes()", info_time_bytes); }
}

// Get the progress of the upload
function getProgressStatus(){
	var jsel = document.createElement('SCRIPT');
	
	jsel.type = 'text/javascript';
	jsel.src = get_status_url + "&rnd_id=" + Math.random();
	
	document.body.appendChild(jsel);
	
	if(get_data_loop){ self.setTimeout("getProgressStatus()", get_status_speed); }
}

// Calculate and display upload stats
function setProgressStatus(bytes_read, lapsed_time, uploaded_files){
	var byte_speed = 0;
	var time_remaining = 0;
	
	if(lapsed_time > 0){ byte_speed = bytes_read / lapsed_time; }
	if(byte_speed > 0){ time_remaining = Math.round((total_upload_size - bytes_read) / byte_speed); }
	
	if(cedric_progress_bar == 1){
		if(byte_speed != 0){
			info_time_width = Math.round(total_upload_size * 1000 / (byte_speed * progress_bar_width));
			info_time_bytes = Math.round(1024000 / byte_speed);
			if (info_time_width<66)
				info_time_width=66;
			if (info_time_bytes<66)
				info_time_bytes=66;
		}
		else{
			info_time_width = 200;
			info_time_bytes = 15;
		}
	}
	
	// Calculate percent finished
	var percent_float = bytes_read / total_upload_size;
	var percent = Math.round(percent_float * 100);
	var progress_bar_status = Math.round(percent_float * progress_bar_width);
	
	// Calculate time remaining
	var remaining_sec = (time_remaining % 60); 
	var remaining_min = (((time_remaining - remaining_sec) % 3600) / 60);
	var remaining_hours = ((((time_remaining - remaining_sec) - (remaining_min * 60)) % 86400) / 3600);

	if(remaining_sec < 10){ remaining_sec = '0' + remaining_sec; }
	if(remaining_min < 10){ remaining_min = '0' + remaining_min; }
	if(remaining_hours < 10){ remaining_hours = '0' + remaining_hours; }

	var time_remaining_f = remaining_hours + ':' + remaining_min + ':' + remaining_sec; 
	
	byte_speed = Math.round(byte_speed / 1024);
	bytes_read = Math.round(bytes_read / 1024);
	
	if(cedric_progress_bar == 1){
		cedric_hold = false;
		info_width = progress_bar_status;
		info_bytes = bytes_read;
	}
	else{
		document.getElementById('upload_status').style.width = progress_bar_status + 'px';
		document.getElementById('current').innerHTML = bytes_read;
	}
	
	if(document.getElementById('percent')) document.getElementById('percent').innerHTML = percent + '%';
	if(document.getElementById('remain')) document.getElementById('remain').innerHTML = time_remaining_f;
	if(document.getElementById('speed')) document.getElementById('speed').innerHTML = byte_speed;
}


// Calculate the time spent uploading
function getElapsedTime(){
	seconds++;
    	
	if(seconds == 60){
		seconds = 0;
		minutes++;
	}
    	
	if(minutes == 60){
		minutes = 0;
		hours++;
	}
    	
	var hr = "" + ((hours < 10) ? "0" : "") + hours;
	var min = "" + ((minutes < 10) ? "0" : "") + minutes;
	var sec = "" + ((seconds < 10) ? "0" : "") + seconds;
    	
	if(document.getElementById('time')) document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
    	
	if(get_data_loop){ self.setTimeout("getElapsedTime()", 1000); }
}

// Create the AJAX request
function createRequestObject(){
	//var req = false;
  	
	if(window.XMLHttpRequest){
		req = new XMLHttpRequest();
		
		if(req.overrideMimeType){ req.overrideMimeType('text/xml'); }
	}
	else if(window.ActiveXObject){
		try{ req = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch(e){
			try{ req = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch(e){}
		}
	}
	
	if(!req){
		document.getElementById('progress_info').innerHTML = txt_str.FileUpload.ajax_nepodporovan;
		return false;
	}
	else{ return req; }
}

// Initialize the progress bar
function iniProgressRequest(number){
	var req = false;
	req = createRequestObject();
	
	number_str = new String(number);
	while (number_str.length<2){
		number_str = '0'+number_str;
	}
	file_number = number;
	file_number++;
	if(req){
		document.getElementById('progress_info').innerHTML = "Inicializuji upload souboru "+file_number+"...";
		req.open("GET", path_to_ini_status_script + number_str + "&rnd_id=" + Math.random(), true);
		req.onreadystatechange = function(){ iniProgressResponse(req, file_number); };
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(null);
	} else
		document.getElementById('progress_info').innerHTML += "<br />Upload souboru "+file_number;
	if(document.getElementById('upload_div_'+number)){
		document.getElementById('upload_div_'+number).style.display = "";
	}	
}

// Initialize the progress bar
function iniProgressResponse(req, file_number){
	if(req.readyState == 4){
		if(req.status == 200){
			var xml = req.responseXML;
			
			if(xml.getElementsByTagName('error_status').item(0).firstChild.nodeValue == 1){
				if (document.forms['form_upload_'+(file_number-1)]){
					if (document.forms['form_upload_'+(file_number-1)]['upfile_0']){
						
						document.getElementById('progress_info').innerHTML = xml.getElementsByTagName('error_msg').item(0).firstChild.nodeValue;
						
						if(xml.getElementsByTagName('stop_upload').item(0)){
							if(xml.getElementsByTagName('stop_upload').item(0).firstChild.nodeValue == 1){ stopUpload(); }
						}
					}
				}
			}
			else{
				//get_status_speed = xml.getElementsByTagName('get_data_speed').item(0).firstChild.nodeValue;
				get_status_speed = 3000;
				cedric_progress_bar = xml.getElementsByTagName('cedric_progress_bar').item(0).firstChild.nodeValue;
				total_upload_size = xml.getElementsByTagName('total_bytes').item(0).firstChild.nodeValue;
				get_status_url = status_action_path+"?temp_dir_sid=" + xml.getElementsByTagName('temp_dir_sid').item(0).firstChild.nodeValue + "&start_time=" + xml.				getElementsByTagName('start_time').item(0).firstChild.nodeValue + "&total_upload_size=" + xml.getElementsByTagName('total_bytes').item(0).firstChild.nodeValue;
                get_data_loop = true;
				if(document.getElementById('progress_bar')) document.getElementById('progress_bar').style.display = "";
				if(document.getElementById('total_kbytes')) document.getElementById('total_kbytes').innerHTML = Math.round(Number(xml.getElementsByTagName('total_bytes').item(0).firstChild.nodeValue / 1024)) + " ";
				if(document.getElementById('progress_info')) document.getElementById('progress_info').innerHTML = "Probíhá upload souboru "+file_number;
				
				getElapsedTime();
				getProgressStatus();
				
				if(xml.getElementsByTagName('cedric_progress_bar').item(0).firstChild.nodeValue == 1){
					smoothCedricBytes();
					smoothCedricStatus();
				}
			}
		}
		else{
			//document.getElementById('progress_info').innerHTML = "Error: " + req.status + " " + req.statusText;
			
			//stopUpload();
		}
	}
}

function resetProgressbar(){
	
}
function fillProgressbar(){
	
}
