var rowNumber = 0;
var rowNumber2 = 0;
var check_form_ = check_form;

$(document).ready(function () {
	// parent Edit list
	InitializeAssignedWith();
	// tabelka z vatami
	InitializeVatTable();
	// Przypisani uzytkownicy
	InitializeUserList();
	
	InitializeTableCost();

	$('#value').change(function (event) {
		if ($('#value').val() == 'NaN,NaN') {
			$('#value').val('0,00');
		}
	});
	$('#document_number').click(function(){
		$('#document_number').val($('#document_name').val());
	});
	
	// Przy zapisie usuwa puste pola z user accepted
	$("#EditView").submit(function (event) {
		var pola = $("input[id^='user_name_']")
		$.each(pola, function (idx,obj){
			if (obj.value=='') {
				$(this).closest('tr').remove();
			}
		});
		pola = $("input[id^='user_id_']");
		$.each(pola, function (idx,obj){
			if (obj.value=='') {
				$(this).closest('tr').remove();
			}
		});
	//	event.preventDefault();
	});
	$("#document_date").on('change', function(){
		if($('input[name="record"]').val()==''){
			if($("#register_date").val()==''){
				
				var options =  { 
				onComplete: function(cep) {
					if(isDate(cep))
						$('#register_date').css("color", "");
					else
						$('#register_date').css("color", "red");
					return;
					},
				'translation': {
					A: {pattern: /[0-3]/}, 
					B: {pattern: /[0-9]/}, 
					C: {pattern: /[0-1]/},  
					D: {pattern: /[0-9]/}, 
					Y: {pattern: /[0-9]/}
				},
				selectOnFocus: true
				};
				var tmp = $('<input></input>');
				tmp.val($(this).val());
				$(tmp).mask('AB.CD.YYYY', options);
				$('#register_date').val($(tmp).val())

			}
		}
	});
});

check_form = function (formname) {
	window.onbeforeunload = null;
	var tmp = $("input[name='escaped_document_name']").val() == '';
	var tmp2 = $("input[name='uploadfile']").val() == '';
	if (tmp) {
		if (tmp2) {
			alert('Nie podano pliku');
			return false;
		}
	}
	$("#document_name").val($.trim($("#document_name").val()));
	if ($("#document_name").val() == '') {
		alert('Nie podano nazwy dokumentu');
		$("#document_name").focus();
		return false;
	}
	if ($('#active_date').val().length < 10) {
		var txt = 'Nie podano ';
		if ($('#active_date').val().length > 0) {
			txt += 'pełnej daty publikacji.';
		} else {
			txt += 'daty publikacji';
		}
		alert(txt);
		$("#active_date").focus();
		return false;
	} 
	if ($("#left_paid").val() != '') {
		//int = $("#left_paid").val(UnformatNumber($("#left_paid").val()));
		if ($('#payment_date').val() == '') {
			if ($('#left_paid').val() != '0,00') {
			alert('Wpisałeś kwotę do zapłaty, podaj termin płatności!');
			return false;
			}
		}
	}
	// unformat vat table positions before save
	var count = $('#tblAppendGrid').appendGrid('getRowCount');
	for (var i = 0; i < count; i++) {
		var data2 = $('#tblAppendGrid').appendGrid('getRowValue', i);
		$('#tblAppendGrid').appendGrid('setCtrlValue', 'vat', i, UnformatNumber(data2.vat));
		$('#tblAppendGrid').appendGrid('setCtrlValue', 'netto', i, UnformatNumber(data2.netto));
	}

	if ($("#value").val() != '')
		$("#value").val(UnformatNumber($("#value").val()));
	var int;


};

function InitializeUserList(){
	var user_list = $.parseJSON($("input[name='user_list']").val());
	if (user_list.length == 0){
		addUserAcceptanceField();
	} else{
		$.each(user_list, function (idx, obj) {
			addUserAcceptanceField(
				obj.user_id,
				obj.user_name,
				obj.accepted,
				obj.accepted_description,
				obj.date_accepted
			);
		});
	}
}

function addUserAcceptanceField(user_id, user_name, accepted, accepted_description, date) {
	user_id = user_id || null;
	user_name = user_name || null;
	accepted = accepted || null;
	accepted_description = accepted_description || null;
	date = date || null;
	rowNumber++;
	//Tworzenie wiersza
	var tabela = document.getElementById('user_acceptance_table');
	var tbRow = document.createElement('tr');
	tabela.appendChild(tbRow);
	var tbCellInput = document.createElement('td');
	var tbCellButtons = document.createElement('td');
	tbRow.appendChild(tbCellInput);
	tbRow.appendChild(tbCellButtons);

	//Tworzenie input'ow
	var inputUserId = document.createElement('input');
	inputUserId.id = 'user_id_' + rowNumber;
	inputUserId.name = 'user_id[]';
	inputUserId.type = 'hidden';
	tbCellInput.appendChild(inputUserId);

	var inputUserAcceptedDescription = document.createElement('input');
	inputUserAcceptedDescription.id = 'accepted_description_' + rowNumber;
	inputUserAcceptedDescription.name = 'accepted_description[]';
	inputUserAcceptedDescription.type = 'hidden';
	tbCellInput.appendChild(inputUserAcceptedDescription);

	var inputUserAccepted = document.createElement('input');
	inputUserAccepted.id = 'accepted_' + rowNumber;
	inputUserAccepted.name = 'accepted[]';
	inputUserAccepted.type = 'hidden';
	tbCellInput.appendChild(inputUserAccepted);

	var inputUserDateAccepted = document.createElement('input');
	inputUserDateAccepted.id = 'date_accepted_' + rowNumber;
	inputUserDateAccepted.name = 'date_accepted[]';
	inputUserDateAccepted.type = 'hidden';
	tbCellInput.appendChild(inputUserDateAccepted);

	var inputUserName = document.createElement('input');
	inputUserName.id = 'user_name_' + rowNumber;
	inputUserName.name = 'user_name[]';
	inputUserName.size = 30;
	inputUserName.maxlength = 50;
	tbCellInput.appendChild(inputUserName);

	//Tworzenie guzikow
	var buttonChooseUser = document.createElement('button');
	var buttonimg = document.createElement('img');
	buttonimg.src = 'index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png';
	buttonChooseUser.appendChild(buttonimg);
	buttonChooseUser.onclick = function (event) {
		var tmp = $(this).closest("tr").find('input[id^=user_id]').attr('id');
		var tmp2 = $(this).closest("tr").find('input[id^=user_name_]').attr('id');
		open_popup('Users', 600, 400, '', true, false,
				{'call_back_function': 'set_return', 'form_name': 'EditView', 'field_to_name_array':
							{'id': tmp, 'name': tmp2}}, 'single', true);
	}
	buttonChooseUser.type = "button";

	buttonChooseUser.title = SUGAR.language.get('Documents', 'HELP_LBL_USERACCEPT_CHOOSE_BUTTON');
	tbCellButtons.appendChild(buttonChooseUser);

	var buttonDel = document.createElement('button');
	var buttonDelimg = document.createElement('img');
	buttonDelimg.src ='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png';
	buttonDel.appendChild(buttonDelimg);
	buttonDel.onclick = function (e) {
		if (document.getElementById('user_acceptance_table').rows.length > 1) {
			$(this).closest('tr').remove();
		}
	};
	buttonDel.type = 'button';
	buttonDel.accessKey = 'C';
	buttonDel.className = 'removerow';
	buttonDel.title = SUGAR.language.get('Documents', 'HELP_LBL_USERACCEPT_BUTTONDEL');
	tbCellButtons.appendChild(buttonDel);
	//Ustawianie wartosci jesli sa
	if(user_id!=null){
		inputUserId.value = user_id;
		inputUserName.value = user_name;
		inputUserAccepted.value = accepted;
		inputUserAcceptedDescription.value = accepted_description;
		inputUserDateAccepted.value = date;
	}
}

function InitializeAssignedWith(){
	 var parent_list = $.parseJSON($("input[name='parent_list']").val());
	 if (parent_list.length == 0){
		addAssociatedWithField();
	} else{
		$.each(parent_list, function (idx, obj) {
			addAssociatedWithField(obj.id, obj.parent_type, htmlspecialchars_decode(obj.parent_name), obj.parent_id);
		});
	}
}

function addAssociatedWithField(list_id, parent_type, parent_name, parent_id){
	list_id = list_id || null;
	parent_type = parent_type + 's' || null;
	parent_name = parent_name || null;
	parent_id = parent_id || null;
	rowNumber2++;
	var tabela = document.getElementById('associated_with');
	var tbRow = document.createElement('tr');
	tabela.appendChild(tbRow);
	var tbCellInput = document.createElement('td');
	var tbCellButtons = document.createElement('td');
	tbRow.appendChild(tbCellInput);
	tbRow.appendChild(tbCellButtons);

	//Tworzenie input'ow
	var inputParentType = document.createElement('select');
	inputParentType.id = 'parent_type_' + rowNumber2;
	inputParentType.name = 'parent_type[]';
	var option= null;
	var parent_type_list = $.parseJSON($("input[name='parent_type_list']").val());
	$.each(parent_type_list, function (idx2, obj2) {
		option = document.createElement("option");
		option.text = obj2;
		option.value = idx2;
		if(parent_type==idx2){
			option.selected = true;
		}
		inputParentType.add(option);
	});
	tbCellInput.appendChild(inputParentType);

	var inputParentId = document.createElement('input');
	inputParentId.id = 'parent_id_' + rowNumber2;
	inputParentId.name = 'parent_id[]';
	inputParentId.type = 'hidden';
	tbCellInput.appendChild(inputParentId);

	var inputParentName = document.createElement('input');
	inputParentName.id = 'parent_name_' + rowNumber2;
	inputParentName.name = 'parent_name[]';
	inputParentName.size = 30;
	inputParentName.autocomplete='off';
	inputParentName.tabIndex=60;
	inputParentName.maxlength = 50;
	tbCellInput.appendChild(inputParentName);


	var inputList = document.createElement('input');
	inputList.id = 'list_id_' + rowNumber2;
	inputList.name = 'list_id[]';
	inputList.type = 'hidden';
	tbCellInput.appendChild(inputList);

	//Tworzenie guzikow
	var buttonChooseUser = document.createElement('button');
	var buttonimg = document.createElement('img');
	buttonimg.src = 'index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png';
	buttonChooseUser.appendChild(buttonimg);
	buttonChooseUser.onclick = function (event) {
		var window = $(this).closest("tr").find('select[id^=parent_type_]').find(":selected").val();
		var tmp = $(this).closest("tr").find('input[id^=parent_id_]').attr('id');
		var tmp2 = $(this).closest("tr").find('input[id^=parent_name_]').attr('id');
		if(window=='Accounts'){
			open_popup(window, 600, 400, '', true, false,{'call_back_function': 'set_return', 'form_name': 'EditView', 'field_to_name_array':{'id': tmp, 'name': tmp2}}, 'single', true);
		}else if(window=='Contacts'){
			open_popup(window, 600, 400, '', true, false,{'call_back_function': 'set_return', 'form_name': 'EditView', 'field_to_name_array':{'id': tmp, 'name': tmp2}}, 'single', true);
		}else if(window=='EcmInvoiceOuts'){
			open_popup(window, 600, 400, '', true, false,{'call_back_function': 'set_return', 'form_name': 'EditView', 'field_to_name_array':{'id': tmp, 'document_no': tmp2}}, 'single', true);
		}else if(window=='EcmSales'){
			open_popup(window, 600, 400, '', true, false,{'call_back_function': 'set_return', 'form_name': 'EditView', 'field_to_name_array':{'id': tmp, 'document_no': tmp2}}, 'single', true);
		}else if(window=='EcmStockDocIns'){
			open_popup(window, 600, 400, '', true, false,{'call_back_function': 'set_return', 'form_name': 'EditView', 'field_to_name_array':{'id': tmp, 'document_no': tmp2}}, 'single', true);
		}else if(window=='EcmProducts'){
			open_popup(window, 600, 400, '', true, false,{'call_back_function': 'set_return', 'form_name': 'EditView', 'field_to_name_array':{'id': tmp, 'name': tmp2}}, 'single', true);
		}
	}
	buttonChooseUser.type = "button";
	buttonChooseUser.accessKey='l';
	buttonChooseUser.title = SUGAR.language.get('Documents', 'HELP_LBL_USERACCEPT_CHOOSE_BUTTON');
	tbCellButtons.appendChild(buttonChooseUser);

	var buttonDel = document.createElement('button');
	var buttonDelimg = document.createElement('img');
	buttonDelimg.src ='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png';
	buttonDel.appendChild(buttonDelimg);
	buttonDel.onclick = function (e) {
		if (document.getElementById('associated_with').rows.length > 1) {
			$(this).closest('tr').remove();
		}
	};
	buttonDel.type = 'button';
	buttonDel.accessKey = 'C';
	buttonDel.className = 'removerow';
	buttonDel.title = SUGAR.language.get('Documents', 'HELP_LBL_USERACCEPT_BUTTONDEL');
	tbCellButtons.appendChild(buttonDel);
	

		inputList.value = list_id;
		inputParentName.value = parent_name;
		inputParentId.value = parent_id;

	$('select[id^=parent_type_]').change(function (event){
		$(this).closest('tr').find('input[id^=parent_id]').val('');
		$(this).closest('tr').find('input[id^=parent_name]').val('');
		$(this).closest('tr').find('input[id^=list_id]').val('');
	});
}