function logon() {
	$.post("index.php", { operation: 'logon', login: $('#login').val(), password: $('#password').val() },
		function(data) {
			if (data == '1')
				window.location.reload();
			else
				alert('Niepoprawne dane logowania');
		}
	);
}

function logoff() {
	$.post("index.php", { operation: 'logoff' },
		function(data) {
			if (data == '1')
				window.location.reload();
		}
	);
}

function itemClicked(inp) {
	$.post("index.php", { operation: 'markitem', id: inp.getAttribute('id').substring(4), type: (inp.checked ? 1 : 0)},
		function(data) {
		}
	);
}

$(document).ready(function() {
	$('#password').keypress(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if(code == 13) {
			logon();
		}
	});

	$('#login').keypress(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if(code == 13) {
			logon();
		}
	});

	$('#login').focus();

	$('.tip').tipTip();

	$('#date').datepicker($.datepicker.regional['pl']);

    uploader = new qq.FileUploader({
        element: document.getElementById('file-uploader'),
        action: 'index.php',
        debug: false,
        uploadButtonText: 'PrzeglÄ…daj',
        cancelButtonText: 'Anuluj',
        failUploadText: 'BĹ‚Ä…d',
        onSubmit: function(id, fileName) {
	        if (uploadParams['isr']) {
		        var ext = fileName.split('.');
		        ext = ext[ext.length-1].toLowerCase();
		        var tid = $('#resfiletype').val();
	        	uploadParams['tid'] = tid;
	        	if (tid == 1 && ext != 'xls') {
		        	showMessage('Niepoprawny format pliku. Dla wybranego rodzaju pliku dozwolone sÄ… jedynie pliki XLS');
		        	return false;
	        	}
	        	if (tid == 4 && ext != 'jpg' && ext != 'pdf' && ext != 'gif' && ext != 'bmp') {
		        	showMessage('Niepoprawny format pliku. Dla wybranego rodzaju pliku dozwolone sÄ… jedynie pliki JPG, PDF, GIF i BMP');
		        	return false;
	        	}
	        	if (tid == 5 && ext != 'ank') {
		        	showMessage('Niepoprawny format pliku. Dla wybranego rodzaju pliku dozwolone sÄ… jedynie pliki ANK');
		        	return false;
	        	}
        	}
	        else
	        	uploadParams['tid'] = $('#filetype').val();
	        uploader.setParams(uploadParams);
        },
        onComplete: function(id, fileName, responseJSON) {
	        if (responseJSON['success'])
				$('#showfiles_' + uploadParams['rid'] + '_' + uploadParams['isr']).show();
        }
        //extraDropzones: [qq.getByClass(document, 'qq-upload-extra-drop-area')[0]]*/
    });

});

var filesToDownload = [];

function downloadNext() {
	document.getElementById('dwnFrame').setAttribute('src', filesToDownload.shift());
}

function downloadFiles() {
	if (filesToDownload.length == 0)
		return;
	if (document.getElementById('dwnFrame') && document.getElementById('dwnFrame').readyState) {
		if (document.getElementById('dwnFrame').readyState == 'interactive' || document.getElementById('dwnFrame').readyState == 'complete') {
		//if (document.getElementById('dwnFrame').readyState == 'complete') {
			document.getElementById('dwnFrame').onreadystatechange = function() { downloadFiles(); };
	//		document.getElementById('dwnFrame').setAttribute('src', filesToDownload.shift());
			setTimeout('downloadNext();', 100);
		}
	}
	else {
		$('#iframeCnt').html('');

		while (filesToDownload.length) {
			$('<iframe></iframe>').attr('src', filesToDownload.shift()).appendTo('#iframeCnt');
		}
	}
}

function getTimeHash() {
	return new Date().getTime();
}

function downloadResearch(resid) {
	$.post("index.php", { operation: 'getResearchFiles', rid: resid },
		function(data) {
			var t = data.split('|');
			for (var i=0; i<t.length; i++)
				filesToDownload[filesToDownload.length] = '?o=dbp&bid=' + resid + '&fid=' + t[i] + '&t=' + getTimeHash();

			downloadFiles();
		}
	);
}

function downloadWave(resid) {
	$.post("index.php", { operation: 'getWaveFiles', rid: resid },
		function(data) {
			var t = data.split('|');
			for (var i=0; i<t.length; i++)
				filesToDownload[filesToDownload.length] = '?o=fbp&bid=' + resid + '&fid=' + t[i] + '&t=' + getTimeHash();

			downloadFiles();
		}
	);
}

function downloadSurvey(resid, sfid) {
	$.post("index.php", { operation: 'getSurveyFiles', rid: resid },
		function(data) {
			var t = data.split('|');
			for (var i=0; i<t.length; i++)
				filesToDownload[filesToDownload.length] = '?o=sbp&bid=' + resid + '&fid=' + t[i] + '&sfid=' + sfid + '&t=' + getTimeHash();

			downloadFiles();
		}
	);
}

function setDate(resid, blokada) {
	if (checkWaveBlockade(blokada)) {
		return;
	}

	$("#dialog-date input[name=date]").val($('#date_' + resid).html());
	$("#dialog-date").dialog({
		buttons: {
			"Zapisz": function() {
				var dialog = $(this);
				showPleaseWait();
				$.post("index.php", { operation: 'setdate', rid: resid, value: $(this).find('input[name=date]').val()},
					function(data) {
						hidePleaseWait();
						getEntranceInfo();
						dialog.dialog("close");
					}
				);
				$('#date_' + resid).html($(this).find('input[name=date]').val())
			},
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 330,
		width: 500,
		modal: true,
		draggable: false,
		resizable: false
	});
}

function setComment(resid, blokada) {
	if (checkWaveBlockade(blokada)) {
		return;
	}

	$("#dialog-comment textarea[name=comment]").val($('#comment_' + resid).html());
	$("#dialog-comment").dialog({
		buttons: {
			"Zapisz": function() {
				var dialog = $(this);
				showPleaseWait();
				$.post("index.php", { operation: 'setcomment', rid: resid, value: $(this).find('textarea[name=comment]').val()},
					function(data) {
						hidePleaseWait();
						dialog.dialog("close");
					}
				);
				setTrComment(resid, $(this).find('textarea[name=comment]').val());
				//$('#comment_' + resid).html($(this).find('textarea[name=comment]').val())
			},
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 500,
		modal: true,
		draggable: false,
		resizable: false
	});
}

function showPleaseWait() {
	$("#dialog-wait").dialog({
		height: 100,
		width: 100,
		modal: true,
		draggable: false,
		resizable: false,
		closeOnEscape: false,
		dialogClass: 'dialogWait'
	});
}

function hidePleaseWait() {
	$("#dialog-wait").dialog("close");
}

function setStatus(resid, status) {
	if (status == -1 || status == -2) {
//		var cstatus = $('#status_' + resid + ' input[name=statusid]').val();
//		var dialogid = (cstatus == 0 ? 'dialog-statusreject' : 'dialog-statuscancel');
		var dialogid = (status == -2 ? 'dialog-statusreject' : 'dialog-statuscancel');
		$("#" + dialogid + " select[name=reason]").val('');
		$("#" + dialogid + " textarea[name=comment]").val('');
		$("#" + dialogid).dialog({
			buttons: {
				"Zapisz": function() {
					if ($(this).find('select[name=reason]').val() == '') {
						showMessage('ProszÄ™ wybraÄ‡ powĂłd');
						return;
					}
					var dialog = $(this);
					showPleaseWait();
					$.post("index.php", { operation: 'setstatus', rid: resid, value: status, comment: $(this).find('textarea[name=comment]').val(), reason: $(this).find('select[name=reason]').val()},
						function(data) {
							hidePleaseWait();
							dialog.dialog("close");
							updateTrStatus(resid, status, data);
						}
					);
					//$('#comment_' + resid).html($(this).find('textarea[name=comment]').val())
					setTrComment(resid, $(this).find('textarea[name=comment]').val());
				},
				"Anuluj": function() { $(this).dialog("close"); }
			},
			height: 300,
			width: 720,
			modal: true,
			draggable: false,
			resizable: false
		});
	}
	else if (status == 4) {
		$("#dialog-statusfinish").dialog({
			buttons: {
				"Zapisz": function() {
					var dialog = $(this);
					showPleaseWait();
					$.post("index.php", { operation: 'setstatus', rid: resid, value: status},
						function(data) {
							hidePleaseWait();
							dialog.dialog("close");
							updateTrStatus(resid, status, data);
						}
					);
					$('#comment_' + resid).html($(this).find('textarea[name=comment]').val())
				},
				"Anuluj": function() { $(this).dialog("close"); }
			},
			height: 200,
			width: 500,
			modal: true,
			draggable: false,
			resizable: false
		});
	}
	else {
		if (status == 3 && $('#date_' + resid).html() == '') {
			showMessage('Przed oznaczeniem aniekty jako wykonanej trzeba uzupeĹ‚niÄ‡ datÄ™ wykonania');
			return;
		}
		showPleaseWait();
		$.post("index.php", { operation: 'setstatus', rid: resid, value: status},
			function(data) {
				hidePleaseWait();
				updateTrStatus(resid, status, data);
			}
		);
	}
}

function updateTrStatus(resid, status, data) {
	$('#status_' + resid).html(data);
	if (status < 0)
		$('#tr_' + resid).addClass('disabled');
	else
		$('#tr_' + resid).removeClass('disabled');

	if (status < 0)
		$('#tr_' + resid).addClass('unknown');
	else
		$('#tr_' + resid).removeClass('unknown');

	if (status == 4)
		$('#tr_' + resid).addClass('finished');
	else
		$('#tr_' + resid).removeClass('finished');
}

uploadParams = {};

function uploadResFile(resid, blokada) {
	if (checkWaveBlockade(blokada)) {
		return;
	}
	uploader.clearStoredFiles();
	uploadParams['rid'] = resid;
	uploadParams['isr'] = 1;
	$("#dialog-upload div.research").show();
	$("#dialog-upload select[name=resfiletype]").val(1);
	$("#dialog-upload div.otherfiles").hide();
	$("#dialog-upload").dialog({
		buttons: {
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 700,
		modal: true,
		draggable: false,
		resizable: false
	});
}

function uploadOtherFile(resid, blokada) {
	if (checkWaveBlockade(blokada)) {
		return;
	}
	uploader.clearStoredFiles();
	uploadParams['rid'] = resid;
	uploadParams['isr'] = 0;
	$("#dialog-upload div.research").hide();
	$("#dialog-upload div.otherfiles").show();
	$("#dialog-upload").dialog({
		buttons: {
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 700,
		modal: true,
		draggable: false,
		resizable: false
	});
}

function setTrComment(resid, comment) {
	if (comment != '')
		$('#comment_' + resid).html(comment).next().show();
	else
		$('#comment_' + resid).html(comment).next().hide();
	$('#comment_' + resid).html(comment)
}

function showComment(resid) {
	$("#dialog-commentview div.commentviewdetails").html($('#comment_' + resid).html());
	$("#dialog-commentview").dialog({
		buttons: {
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 500,
		modal: true,
		draggable: false,
		resizable: false
	});
}

function showFiles(resid, isresearch) {
	if ($('#tr_' + resid).hasClass('finished'))
		$("#dialog-files div.cnt").addClass('disabled');
	else
		$("#dialog-files div.cnt").removeClass('disabled');
	$("#dialog-files div.cnt").html('');
	$("#dialog-files").dialog({
		buttons: {
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 500,
		modal: true,
		draggable: false,
		resizable: false
	});
	showPleaseWait();
	$.post("index.php", { operation: 'getUploadedFiles', rid: resid, isr: isresearch},
		function(data) {
			hidePleaseWait();
			$("#dialog-files div.cnt").html(data);
		}
	);
}

function removeFile(resid, fid, isresearch) {
	$("#dialog-filedeleteconfirm").dialog({
		buttons: {
			"UsuĹ„": function() {
				var dialog = $(this);
				showPleaseWait();
				$.post("index.php", { operation: 'deleteUploadedFile', rid: $("#dialog-filedeleteconfirm").get(0).resid, fid: $("#dialog-filedeleteconfirm").get(0).fid, isr: $("#dialog-filedeleteconfirm").get(0).isresearch},
					function(data) {
						hidePleaseWait();
						dialog.dialog("close");
						$("#dialog-files div.cnt").html(data);
						//alert('data=' + data + ' ' + '#showfiles_' + resid + '_' + isresearch);
						if (data == '')
							$('#showfiles_' + resid + '_' + $("#dialog-filedeleteconfirm").get(0).isresearch).hide();
						else
							$('#showfiles_' + resid + '_' + $("#dialog-filedeleteconfirm").get(0).isresearch).show();
//						updateTrStatus(resid, status, data);
					}
				);
			},
			"Anuluj": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 700,
		modal: true,
		draggable: false,
		resizable: false
	});

	$("#dialog-filedeleteconfirm").get(0).isresearch = isresearch;
	$("#dialog-filedeleteconfirm").get(0).resid = resid;
	$("#dialog-filedeleteconfirm").get(0).fid = fid;
}

function setTrSettlement(resid, settlement) {
	if (settlement != '')
		$('#settlement_' + resid).html(settlement).next().show();
	else
		$('#settlement_' + resid).html(settlement).next().hide();
	$('#settlement_' + resid).html(settlement)
}

function showSettlement(resid) {
	$("#dialog-settlement input").hide();
	$("#dialog-settlement .inputValue").show();
	var settlement = $('#settlement_' + resid).html().split('|');
	var names = ['koszt_sam_miasta', 'koszt_sam_kilometry', 'koszt_bilet_miasta', 'koszt_bilet_kw_brutto', 'koszt_z_pokwit_opis', 'koszt_z_pokwit_kw_brutto', 'koszt_bez_pokwit_opis', 'koszt_bez_pokwit_kw_netto'];
	for (var i=0; i<names.length; i++)
		$("#dialog-settlement").find('input[name=' + names[i] + ']').next().html(settlement[i]);
	$("#dialog-settlement").dialog({
		buttons: {
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 800,
		modal: true,
		draggable: false,
		resizable: false
	});
}

function setSettlement(resid, blokada) {
	if (checkWaveBlockade(blokada)) {
		return;
	}

	var settlement = $('#settlement_' + resid).html().split('|');
	var names = ['koszt_sam_miasta', 'koszt_sam_kilometry', 'koszt_bilet_miasta', 'koszt_bilet_kw_brutto', 'koszt_z_pokwit_opis', 'koszt_z_pokwit_kw_brutto', 'koszt_bez_pokwit_opis', 'koszt_bez_pokwit_kw_netto'];
	for (var i=0; i<names.length; i++)
		$("#dialog-settlement").find('input[name=' + names[i] + ']').val(settlement[i]);
	$("#dialog-settlement .inputValue").hide();
	$("#dialog-settlement input").show();

	$("#dialog-settlement").dialog({
		buttons: {
			"Zapisz": function() {
				var dialog = $(this);
//				dialog.dialog("close");
				showPleaseWait();
				$.post("index.php", { operation: 'setsettlement', rid: resid,
						koszt_sam_miasta: $(this).find('input[name=koszt_sam_miasta]').val(),
						koszt_sam_kilometry: $(this).find('input[name=koszt_sam_kilometry]').val(),
						koszt_bilet_miasta: $(this).find('input[name=koszt_bilet_miasta]').val(),
						koszt_bilet_kw_brutto: $(this).find('input[name=koszt_bilet_kw_brutto]').val(),
						koszt_z_pokwit_opis: $(this).find('input[name=koszt_z_pokwit_opis]').val(),
						koszt_z_pokwit_kw_brutto: $(this).find('input[name=koszt_z_pokwit_kw_brutto]').val(),
						koszt_bez_pokwit_opis: $(this).find('input[name=koszt_bez_pokwit_opis]').val(),
						koszt_bez_pokwit_kw_netto: $(this).find('input[name=koszt_bez_pokwit_kw_netto]').val()
					},
					function(data) {
						hidePleaseWait();
						if (data != '1') {
							showMessage('Nie udało się zapisać wprowadzonych danych. Sprawdź czy są poprawnie wpisane');
						}
						else {
							var s = [];
							for (var i=0; i<names.length; i++)
								s[s.length] = $("#dialog-settlement").find('input[name=' + names[i] + ']').val();

							setTrSettlement(resid, s.join('|'));
							dialog.dialog("close");
							window.location.reload();
						}
					}
				);
//				//$('#comment_' + resid).html($(this).find('textarea[name=comment]').val())
			},
			"Zamknij": function() { $(this).dialog("close"); }
		},
		height: 300,
		width: 800,
		modal: true,
		draggable: false,
		resizable: false
	});
}

function showMessage(text) {
	if ($("#dialog-message").length == 0)
		$('body').append('<div id="dialog-message" title="Informacja"></div>');

	$("#dialog-message").dialog({
//		height: 150,
		width: 400,
		modal: true,
		draggable: false,
		resizable: false,
		close: false,
		closeOnEscape: true,
		dialogClass: 'dialogMessage',
		buttons: {
			'Ok' : function() {
				$(this).dialog("close");
			}
		}
	});

	$("#dialog-message").html(text);
}

function getEntranceInfo() {
	$.post("index.php", { operation: 'getEntrance', wid: year + '_' + week},
		function(data) {
			$("#entranceInfo").html(data);
		}
	);
}


function setSort(col, order) {
	$.post("index.php", { operation: 'setsort', col: col, order: order},
		function(data) {
			window.location.reload();
		}
	);
}

function checkWaveBlockade(blokada) {
	if (blokada == 1) {
		showMessage('Badanie zostało zakończone, minął termin realizacji. Prosimy skontaktować się z koordynatorem odpowiedzialnym za badanie.');
		return true;
	}

	return false;
}