window.onbeforeunload = function() {
	// removeDocumentReservations(document.getElementById("temp_id").value);
	// saveDocumentReservations(document.getElementById("temp_id").value);
	// alert("Wprowadzone zmiany nie zosta�y zapisane");
};

var selectGetValue = function(encoded, getElements) {
	if (typeof encoded == 'undefined') {
		encoded = false;
	}

	var data = [];
	var elements = [];

	for ( var i in this.children) {
		var tmp = this.children[i];

		if (typeof tmp == 'object') {
			if (true == tmp.selected) {
				elements.push(tmp);
				data.push(tmp.value);
			}
		}
	}

	if (getElements) {
		return elements;
	}

	// console.log(data);
	return encoded ? JSON.stringifyNoSecurity(data) : data;
};

var selectSetValue = function(data, disable) {

	if (typeof disable == 'undefined') {
		disable = false;
	}

	// if(typeof(data) == 'object') {
	// return;
	// }

	for ( var i in this.children) {
		var tmp = this.children[i];

		if (typeof tmp == 'object') {

			if (typeof data == 'object') {
				for ( var j in data) {
					var tmpj = data[j];

					if (tmp.value == tmpj) {
						tmp.selected = 'selected';
						tmp.disabled = '';
					} else {
						if (true == disable) {
							tmp.disabled = 'disabled';
						}
					}

				}
			} else {
				if (tmp.value == data) {
					tmp.selected = 'selected';
					tmp.disabled = '';
				} else {
					if (true == disable) {
						tmp.disabled = 'disabled';
					}
				}
			}
		}
	}

	return;
};
var NumberToUserFormatNumber = function(number, add) {
	if (!number) {
		number = 0;
	}

	number = parseFloat(number);

	var tmp = number.toFixed(OPT['dec_len']);

	var s1 = tmp.substring(0, tmp.length - 1 - OPT['dec_len']);
	var s2 = tmp.substring(tmp.length - OPT['dec_len'], tmp.length);

	var tmp = '';

	for ( var i = s1.length; i > 0; i -= 3) {
		tmp = ((i <= 3) ? "" : OPT['sep_1000']) + s1.substring(i - 3, i) + tmp;
	}

	s1 = tmp;

	return (s1 + OPT['dec_sep'] + s2).toString() + ((add) ? add : '');
};

var UserFormatNumberToNumber = function(ufn, add) {
	if (add) {
		var match = /add/g;
		ufn = ufn.replace(match, '');
	}

	var match = /Err/g;

	ufn = ufn.replace(match, '');

	if (!ufn) {
		return parseFloat(0);
	}

	var pos = ufn.indexOf(OPT['dec_sep']);

	var s1 = '';
	s2 = '';

	if (pos == -1) {
		s1 = ufn;
		s2 = '';
	}

	else {
		s1 = ufn.substring(0, pos);
		s2 = ufn.substring(pos + 1, ufn.length);
	}

	// if (OPT['sep_1000'] != "") {
	// for (var i = s1.length - 4; i >= 0; i -= 4)
	// if (s1.charAt(i) != OPT['sep_1000']) {
	// return -1;
	// }
	// }
	//
	// if (s1.charAt(0) == OPT['sep_1000']) {
	// return -1;
	// }

	var pos = -1;

	while ((pos = s1.indexOf(OPT['sep_1000'])) != -1) {
		s1 = s1.substring(0, pos) + s1.substring(pos + 1, s1.length);
	}

	return parseFloat(s1 + "." + s2);
};

var DateDiff = function(d1, d2) {
	return d1.getTime() - d2.getTime();
};

var DaysToMilliseconds = function(days) {
	return days * (1000 * 60 * 60 * 24);
};

var MillisecondsToDays = function(milliseconds) {
	return Math.round(milliseconds / (1000 * 60 * 60 * 24));
};

var changer = function() {
	this.list = new Object();

	this.add = function(object, type, do_function, start_value) {
		if (typeof (object) == "string") {
			object = document.getElementById(object);
		}

		if (!object) {
			return;
		}

		this.list[object.id] = new Object();
		this.list[object.id].object = object;
		this.list[object.id].type = type;
		this.list[object.id].do_function = do_function;
		this.list[object.id].start_value = start_value;
		this.list[object.id].value = '';
	};

	this.getValue = function(element) {
		var value = null;

		if (element.object) {
			if (element.type == "innerHTML") {
				value = element.object.innerHTML;
			}

			if (element.type == "value") {
				value = element.object.value;
			}

			if (element.type == "checked") {
				value = element.object.checked;
			}
		}

		return value;
	};

	this.interval = 1000;

	this.timer = null;

	this.startTimer = function() {
		var cc = this;

		this.timer = setInterval(function() {
			var list = cc.list;

			for (x in list) {
				if (list[x].start_value) {
					list[x].value = cc.getValue(list[x]);
					list[x].start_value = false;
				} else {
					var value = cc.getValue(list[x]);

					if (list[x].value !== value) {
						if (list[x].do_function) {
							list[x].do_function(list[x].object);
						}
					}

					list[x].value = value;
				}
			}
		}, this.interval);
	};

	this.stopTimer = function() {
		clearInterval(this.timer);
		this.timer = null;
	};
};

var updatePositions = function() {
	var update_button = document.getElementById('update_button');
	update_button.disabled = 'disabled';
	
	var data = {};

	for ( var i = 0, iC = N.rowCount(); i < iC; i++) {
		var tmp = N.row(i);
		var rowData = tmp.getData();

		if (false != rowData.i_code) {
			data[rowData.i_code] = rowData;
		}

		// tmp.parentNode.deleteRow();
		// tmp.deleteRow();
	}

	// console.clear();
	// console.log(data);
	clearData();
	// return true;

	var encoded = JSON.stringifyNoSecurity(data);

	// console.log(encoded);
	// return true;

	var types = document.getElementById('type').children;
	var type = '';

	for ( var i in types) {
		var tmp = types[i];

		// console.log(tmp);

		if (true == tmp.selected) {
			type = tmp.value;
			break;
		}
	}

	var dat_zap = document.getElementById('dat_zap').value;

	// url =
	// 'index.php?module=EcmFkVatRegisters&action=updatepositions&dat_zap=' +
	// dat_zap + '&type=' + type;// + '&data=' + encoded;
	url = 'module=EcmFkVatRegisters&action=updatepositions&dat_zap=' + dat_zap
			+ '&type=' + type + '&data=' + encoded;
	// console.log(url);

	doRequest('index.php', url, function(result) {
//		 console.log(result);
//		 return;

		var newValue = result.replace(/"/g, '\'');
		document.getElementById('items_list').value = newValue;

		fillData();
		update_button.disabled = '';
		
		return;
	});

	return;

	// YAHOO.util.Connect.asyncRequest(
	// 'POST',
	// url,
	// function() {
	// console.log(1);
	// },
	// encoded
	// );
	//
	// var req = mint.Request();
	//
	// req.OnSuccess = function() {
	// var newValue = this.responseText.replace(/"/g, '\'');
	//
	// console.log('responseText', this.responseText);
	// // console.log('newValue', newValue, newValue.length);
	//
	// // return;
	//
	// document.getElementById('items_list').value = newValue;
	//
	// fillData();
	//
	// return;
	// };
	//
	// req.Send(url);
};

var clearData = function() {
	while (N.rowCount() > 0) {
		N.row(0).deleteRow(true);
	}
};

var doRequest = function(where, post, doFunction, error) {
	this.Display = function(result) {
		doFunction(result.responseText);
	};

	this.Fail = function(result) {
		if (error) {
			alert(error);
		}
	};

	YAHOO.util.Connect.asyncRequest("POST", where, {
		success : this.Display,
		failure : this.Fail
	}, post);
};

var changeValidateRequired = function(formname, name, required) {
	for ( var i = 0; i < validate[formname].length; i++) {
		if (validate[formname][i][0] == name) {
			validate[formname][i][2] = required;
			break;
		}
	}
};

var set_focus = function() {
	var type = document.getElementById('type');
	type.getValue = selectGetValue;

	var value = type.getValue();
	var selectedType = value[0];

	switch (selectedType) {
	case 0: // Ogólny
	case 2: // Sprzedaży
	case 3: // Zakupu
		// document.getElementById('i_code').focus();
		break;
	case 1: // Płatniczy
		// document.getElementById('i_position').focus();
		break;
	default:
		break;
	}

	return;
};

function set_return_new(popup_reply_data) {
	// console.log(popup_reply_data);
	// return 1;

	var name_to_value_array = popup_reply_data.name_to_value_array;
	var selection_list = popup_reply_data.selection_list;

	var selectedRows = document.getElementsByClassName('selectedRow');
	// var currentRow = N.row(0);
	var currentRow = selectedRows[0];

	var data = currentRow.getData();
	// console.log(data);

	if (name_to_value_array) {
		var bar = foo(name_to_value_array);
		data.i_amount.push(bar);
	} else if (selection_list) {
		selection_list = eval(selection_list);
		// console.log(selection_list);

		for ( var i in selection_list) {
			var tmp = selection_list[i];

			var bar = foo(tmp);

			// ~

			// data.i_amount[tmp.id] = tmp;
			data.i_amount.push(bar);
		}
	} else {
		//
	}

	currentRow.setData(data);

	// console.log(unescape(JSON.parse(name_to_value_array)));
	// console.log(name_to_value_array);
	// return;

	return;
}

function foo(name_to_value_array) {
	console.log(name_to_value_array);

	var t = 'b';

	var reg_acc = document.getElementById('reg_acc');
	var reg_acc_code = document.getElementById('reg_acc_code');

	var i_acc_wn_code = document.getElementById('i_acc_wn_code');
	var i_acc_ma_code = document.getElementById('i_acc_ma_code');

	var i_acc_wn_kind = document.getElementById('i_acc_wn_kind');
	var i_acc_ma_kind = document.getElementById('i_acc_ma_kind');
	
	// console.log(i_acc_wn, i_acc_ma, name_to_value_array);

	if (i_acc_wn_code && i_acc_ma_code) {
		
		if(reg_acc) {
			
//			console.log('comp', reg_acc_code.value , i_acc_wn_code.value, i_acc_ma_code.value );

			var a = (reg_acc_code.value == i_acc_wn_code.value);
			var b = (reg_acc_code.value == i_acc_ma_code.value);
			
//			console.log('a', a);
//			console.log('b', b);
			
			if(a) {
				t = 'wn';
			} else if(b) {
				t = 'ma';
			} else {
//				t = 'b';
			}
			
		} else {
//			t = 'b';
			
			var a = (i_acc_wn_kind.value == 'Rozrachunkowe' || i_acc_wn_kind.value == '4' ) ;
			var b = (i_acc_ma_kind.value == 'Rozrachunkowe' || i_acc_ma_kind.value == '4' );

			console.log('a', a);
			console.log('b', b);
			
			if(a && $b) {
				t = 'b';
			} else if(a) {
				t = 'wn';
			} else if(a) {
				t = 'ma';
			} else {
				
			} 
			
			console.log('reg_acc not found');
			
//			if(true) {
//				
//			} else if(true) {
//				
//			} else {
//				
//			}
			
		}
		
		// console.log(name_to_value_array.acc_wn);
		// console.log(name_to_value_array.acc_ma);
		// console.log(i_acc_wn.value);
		// console.log(i_acc_ma.value);

		// var reg_acc_code = document.getElementById('reg_acc_code');
		/*
		if (name_to_value_array.acc_ma == i_acc_wn.value) {
			t = 'ma';
			// t = 'wn';
		}

		if (name_to_value_array.acc_wn == i_acc_ma.value) {
			t = 'wn';
			// t = 'ma';
		}
		*/

	}

	// ~

	var tmp = {};
	tmp.sys_par = name_to_value_array.id;
	tmp.book_number = name_to_value_array.book_number;
	tmp.type = t;
	tmp.book_symbol = name_to_value_array.book_symbol;
	tmp.book_name = name_to_value_array.book_name;
	tmp.book_amount = name_to_value_array.book_amount;

	 console.log('ret tmp', tmp);

	return tmp;

}

var my_popup = function(module, field_array, met, call_back_function,
		form_name, customurl) {
	if (!call_back_function) {
		call_back_function = "set_return";
	}

	if (!form_name) {
		form_name = "EditView";
	}

	// module_name,
	// width,
	// height,
	// initial_filter,
	// close_popup,
	// hide_clear_button,
	// popup_request_data,
	// popup_mode,
	// create,
	// metadata,
	// customurl
	return open_popup(module, 900, 700, met, true, false, {
		"call_back_function" : call_back_function,
		"form_name" : form_name,
		"field_to_name_array" : field_array
	}, false, false, false, customurl);
};

var addEvent = function(object, eventName, do_function) {
	if (typeof (object) == "string") {
		object = document.getElementById(object);
	}

	if (!object) {
		alert("No object in function addEvent!");
		return;
	}

	if (object.addEventListener) {
		object.addEventListener(eventName, do_function, false);
	} else {
		object.attachEvent("on" + eventName, do_function);
	}
};

var cursorEOT = function(isField) {
	isRange = isField.createTextRange();
	isRange.move("textedit");
	isRange.select();
	testOverflow = isField.scrollTop;

	if (testOverflow != 0) {
		return true;
	} else {
		return false;
	}
};

var adjustRows = function(isField) {
	while (cursorEOT(isField)) {
		isField.rows++;
	}
};

var insertText = function(isField, isText) {
	isField.value = testText;
	isField.focus();
};

var ERROR = false;

var ItemListSave = function(json) {
	return "";
};

var FkVatRegisterListSave = function(json) {
	return "";
};

var IncomeListSave = function(json) {
	return "";
};

var ShowLoadingView = function() {
	var slv = document.getElementById("ShowLoadingView");

	if (!slv) {
		slv = document.createElement("div");
		slv.id = "ShowLoadingView";
		slv.className = "transparent_class_loading";
		slv.style.width = "100%";
		slv.style.height = "500%";

		var sli = document.createElement("img");
		sli.className = "transparent_class_loading_image";
		sli.src = "themes/default/images/loading.gif";
		slv.appendChild(sli);

		document.body.appendChild(slv);
	}

	slv.style.display = "";
};

var HideLoadingView = function() {
	var slv = document.getElementById("ShowLoadingView");

	if (slv) {
		slv.style.display = "none";
	}
};

var ItemsList = function(json) {
	var data = '';

	for ( var i = 0; i < N.rowCount(); i++) {
		data = data + '||||' + JSON.stringifyNoSecurity(N.row(i).getData());
	}

	// console.log('listsave: ', data);

	return data;
};

var saveItems = function() {
	document.getElementById("items_list").value = ItemsList(true);
};

var saveFkVatRegisters = function() {
	document.getElementById("fkvatregisters_list").value = FkVatRegistersList(true);
};

var SaveForm = function() {
	ShowLoadingView();

	setTimeout(function() {
		if (OPT["checkbox_demo"] == 1
				&& document.forms.EditView.record.value == "") {
			alert(MOD.LBL_DEMO_VERSION_INFORMATION);
			return;
		}

		ERROR = false;

		// document.getElementById("position_list").value = ItemListSave(true);
		if (ERROR) {
			alert(MOD["LBL_SAVE_FORM_ERROR"]);
			HideLoadingView();
			return false;
		}

		document.forms.EditView.action.value = "Save";

		if (check_form("EditView")) {
			// var result = confirm(MOD.LBL_CONFIRM_QUESTION);
			// if(result) document.forms.EditView.status.value =
			// (OPT["auto_commiting"]?"s30":"s20");

			doRequest("index.php", getFormPost("Save"), function(result) {
				console.log(result);
				HideLoadingView();
				return;
				/*
				 */

				document.forms.EditView.record.value = result
						.substring(result.length - 36);

				if (OPT["setEmailTab"]) {
					setEMAIL(true);
				} else {
					window.location = "index.php?module="
							+ document.forms.EditView.module.value
							+ "&action=DetailView&record="
							+ document.forms.EditView.record.value;
				}
			}, MOD["LBL_NOT_SAVED"]);
		} else {
			alert(MOD["LBL_NOT_SAVED"]);
			HideLoadingView();
			return false;
		}

	}, 200);
};

var ItemListClear = function() {
	while (N.rowCount() > 0) {
		N.row(0).deleteRow();
	}

	return;
};

var getFormPost = function(action) {
	if (!action) {
		action = "previewPDF";
	}

	var pd = "to_pdf=1" + "&module=EcmFkVatRegisters&action=" + action
			+ "&record=" + document.forms.EditView.record.value;

	pd += "&cache=fromJava" + ItemListSave(true) + FkVatRegisterListSave(true)
			+ IncomeListSave(true);
	// pd += '&history=' + document.forms.EditView.history.value;

	var pd2 = new Object();

	pd2["module"] = "EcmFkVatRegisters";
	pd2["action"] = action;
	pd2["record"] = document.forms.EditView.record.value;
	pd2["to_pdf"] = "1";
	pd2["cache"] = "fromJava";

	// pd2['history'] = document.forms.EditView.history.value;

	// document.forms.EditView.position_list.value = "";
	document.forms["EditView"].action.value = action;

	var tmp;

	for ( var i = 0; i < document.forms["EditView"].elements.length; i++) {
		tmp = document.forms["EditView"].elements[i];

		if (tmp.name != "") {
			if (tmp.type == "checkbox") {
				pd2[document.forms["EditView"].elements[i].name] = (document.forms["EditView"].elements[i].checked ? "1"
						: "0");
			} else {
				pd2[document.forms["EditView"].elements[i].name] = document.forms["EditView"].elements[i].value;
			}
		}
	}

	pd += "&otherFormData=" + JSON.stringifyNoSecurity(pd2);

	return pd;
};

// var AjaxSearch1Items;
// var AjaxSearch2Items;
// var AjaxSearch3Items;
//
// var parentFL;
// var productFL;
// var contactFL;
