/******************************************************************************
	Fa felepitesere alkalmas objektumok
*/
function mNode(str, func) {
	this.children = new Array();
	this.name = str;
	this.func = func;
}

mNode.prototype.addChild = function(child) {
	this.children.push(child);
}

mNode.prototype.walk = function(indent) {
	var i = 0;
	if (indent == undefined) {
		indent = '';
	}
	while (i < this.children.length) {
		this.children[i++].walk(indent + '-');
	}
	debugStr += indent + this.name + '\n';
}

function printTree(tr) {
	debugStr = '';
	tr.root.walk();
	alert(debugStr);
}


function mTree() {
	this.root = new mNode('_ROOT');
	this.evalStr = '';
}

mTree.prototype.getNode = function(name, node) {
	var found = false;
	var cnode = node?node:this.root;
	var i = 0;
	while (i < cnode.children.length && !found) {
		if (cnode.children[i].name == name) {
			found = cnode.children[i];
		} else {
			found = this.getNode(name, cnode.children[i++]);
		}
	}
	return found;
}

mTree.prototype.addNode = function(child, parent) {
	if (!parent) {
		this.root.addChild(child);
		return true;
	} else {
		parent.addChild(child);
		return true;
	}
}

mTree.prototype.recGetEvalStr = function(node, depth) {
	var i = 0;
	if (depth == undefined) depth = 0;
	while (i < node.children.length) {
		this.recGetEvalStr(node.children[i++], depth + 1);
	}
	if (depth != 0) {
		this.evalStr += 'var ' + node.name + ' = document.getElementById("' + node.name + '_input");\n';
		if (node.func != undefined ) {
			this.evalStr += node.name + '.value = ' + node.func + ';\n';
		}
	}
}

mTree.prototype.getEvalStr = function() {
	this.evalStr = '';
	this.recGetEvalStr(this.root);
	return this.evalStr;
}

/******************************************************************************
	Relacio objektum. Elemeket lehet sorbarendezni, az elemek kozti kisebb relaciok hozzaadasaval
*/

function MRelation() {
	this.rel = new Array();
	this.varList = new Array();
}


function MVar(str, func) {
	this.name = str;
	this.func = func;
}

var mRelation = new MRelation();

MRelation.prototype.hasVar = function(x) {
	var found = false;
	for (var i=0; i<this.varList.length; i++) {
		if (this.varList[i].name == x) {
			found = true;
		}
	}
	return found;
}

MRelation.prototype.addFunc = function(v, f) {
	var found = false;
	for (var i=0; i<this.varList.length; i++) {
		if (this.varList[i].name == v) {
			this.varList[i].func = f;
			found = true;
		}
	}
	return found;
}

MRelation.prototype.addVar = function(x) {
	var found = false;
	for (var i=0; i<this.varList.length; i++) {
		if (this.varList[i].name == x.name) {
			found = true;
		}
	}
	if (!found) {
		this.varList.push(x);
	}
	return found;
}

// parameters: variable names
MRelation.prototype.add = function(x, y) {
	var insert = true;
	var len = this.rel.length;
	for (var i=0; i<len; i++) {
		if (this.rel[i].first == x && this.rel[i].second == y) {
			insert = false;
		}
	}
	if (insert) {
		this.rel[len] = new Object();
		this.rel[len].first = x;
		this.rel[len].second = y;
	}
}

MRelation.prototype.less = function(x, y) {
	var less = false;
	for (var i=0; i<this.rel.length && !less; i++) {
		if (this.rel[i].first == x && this.rel[i].second == y) {
			less = true;
		}
	}
	return less;
}

MRelation.prototype.sort = function() {
	var sorted = new Array();
	var len = this.varList.length;
	for (var j=0; j<len; j++) {
		var inserted = false;
		i=0;
		while (!inserted && i < sorted.length) {
			if (this.less(this.varList[j].name, sorted[i].name)) {
				sorted.push(1);
				for (var q=sorted.length - 1; q>i; q--) {
					sorted[q] = sorted[q-1];
				}
				sorted[i] = this.varList[j];
				inserted = true;
			}
			i++;
		}
		if (!inserted) {
			sorted.push(this.varList[j]);
		}
	}
	return sorted;
}

MRelation.prototype.toString = function() {
	var str = '';
	for (var i=0; i<this.rel.length; i++) {
		str += this.rel[i].first + ' < ' + this.rel[i].second + '\n';
	}
	str += 'varList:';
	for (var i=0; i<this.varList.length; i++) {
		str += this.varList[i].name + ' | ' + this.varList[i].func + '\n';
	}
	return str;
	
}

MRelation.prototype.getVars = function() {
	for (var i=0; i<this.rel.length; i++) {
		str += this.rel[i].first + ' < ' + this.rel[i].second + '\n';
	}
	return true;
}

MRelation.prototype.getEvalStr = function() {
	this.evalStr = '';
	var s = this.sort();
	for (var i=0; i<s.length; i++) {
		this.evalStr += 'var ' + s[i].name + ' = document.getElementById("' + s[i].name + '_input");\n';
		if (s[i].func != undefined ) {
			this.evalStr += s[i].name + '.value = ' + s[i].func + ';\n';
		}
	}
	return this.evalStr;
}

/**
	Pelda fa objektum hasznalatara
*/

function test1() {
	x = new mNode('x');
	y = new mNode('y');
	z = new mNode('z');
	t = new mTree();
	x.addChild(y);
	y.addChild(z);
	t.addNode(x);
	alert(t.getNode('z'));
	t.root.walk();
	alert(debugStr);
	return true;
}

/******************************************************************************
	Datumvalaszto objektum
*/

function DPicker() {
	this.init = false;
}

DPicker.prototype.initialize = function() {
	this.dates = new Array();
	this.names = new Array();
	this.init = true;
}

DPicker.prototype.add = function(element) {
	if (!this.init) {
		this.initialize();
	}
	var inp = element.getElementsByTagName('INPUT')[0];
	var min = element.getAttribute("minyear");
	var max = element.getAttribute("maxyear");
	this.dates.push(new Epoch('epoch_popup', 'popup', inp, min, max));
	this.names.push(inp.id);
}

DPicker.prototype.remove = function(element) {
	if (this.init) {
		var inp = element.getElementsByTagName('INPUT')[0];
		var ind = -1;
		for (var i=0; i<this.names.length; i++) {
			if (this.names[i] == inp.id) {
				ind = i;
        break;				
			}
		}
		if (ind>=0) {
			delete this.names[ind];
			delete this.dates[ind];
			for (var i=ind; i<this.names.length; i++) {
				this.names[i] = this.names[i+1];
				this.dates[i] = this.dates[i+1];
			}
			this.dates.pop();
			this.names.pop();
		}
	}
}

/******************************************************************************
	Tabok kezelese
*/
function TabHandler(form) {
	this.tabList = new Array();
	this.initTabs(form);
//	alert(this.tabList);
}

// not working, if multiple forms are present
TabHandler.prototype.initTabs = function(form) {
	var objects = form.getElementsByTagName('DIV');
	var panels = new Array();
	for (var i=0; i<objects.length; i++) {
		if (hasClassLabel(objects[i], 'fpanel')) {
			panels.push(objects[i]);
		}
	}
	if (panels.length > 0) {
		var ul = document.createElement('UL');
		ul.id = 'maintab';
		ul.className = 'shadetabs';
		for (var i=0; i<panels.length; i++) {
			this.tabList.push(panels[i]);
			var l = document.createElement('LI');
			l.innerHTML = '<a href="" rel="' + panels[i].id + '">' + panels[i].title + 
				'<span class="tab_warning" id="w_' + panels[i].id + '">*</span></a>';
			if (i==0) {
				l.className = 'selected';
			}
			panels[i].title = '';
			ul.appendChild(l);
		}
		var cont = document.getElementById("formcontainer");
		if (!cont) {
			alert('Insert the form into an element with "formcontainer" ID');
		} else {
			cont.insertBefore(ul,cont.firstChild);
		}
//		form.parentNode.insertBefore(ul, form);
		initializetabcontent('maintab');
	}
}

TabHandler.prototype.hideWarning = function() {
	for (var i=0; i<this.tabList.length; i++) {
		document.getElementById('w_' + this.tabList[i].id).style.visibility = 'hidden';
	}
}

TabHandler.prototype.showWarning = function(el) {
	var found = false;
	while (el && el.nodeName!='BODY') {
		if (el.className != '' && el.className!=undefined && hasClassLabel(el, 'fpanel')) {
			found = true;
			break;
		} 
		el = el.parentNode;
	}
	if (found) {
		document.getElementById('w_' + el.id).style.visibility = 'visible';
	}
}
/******************************************************************************
	Tooltip kezelese
*/

function showToolTip(event, tipId, imgObj, action) {
	var mouseX;
	var mouseY;
	var scrollX = scrollY = 0;
	var ie = document.all ? true : false;
	if (!event) event = window.event;
	
	if (document.documentElement && document.documentElement.scrollTop) {
		scrollX = document.documentElement.scrollLeft;
		scrollY = document.documentElement.scrollTop;
	} else if (document.body) {
		scrollX = document.body.scrollLeft;
		scrollY = document.body.scrollTop;
	}
	
	if (ie) { 
		mouseX = event.clientX + scrollX;
		mouseY = event.clientY + scrollY;
	} else { 
		mouseX = event.pageX;
		mouseY = event.pageY;
	}
	if (mouseX < 0) {
		mouseX = 0;
	}
	if (mouseY < 0) {
		mouseY = 0;
	}
	
	var tipObj = document.getElementById(tipId);
	if (action == 1) {
		tipObj.style.display = 'block';
		tipObj.style.left = mouseX + 10 + 'px';
		tipObj.style.top = mouseY + 'px';
	} else {
		tipObj.style.display = 'none';
	}
}

/******************************************************************************
	Comment kezelese
*/
  var comment_close = '[+]';
  var comment_open = '[-]';
  var comment_blank_text = 'Ide írhatja megjegyzését'

function showhideComment(switcher) {
  var opened = (switcher.innerHTML==comment_open);
  switcher.innerHTML = opened?comment_close:comment_open;
  var ts = switcher.parentNode.parentNode.getElementsByTagName('TEXTAREA');
  for(var i=0;i<ts.length;i++) if (ts[i].className=='comment') {
    ts[i].style.display = opened?'none':'block';
    if (!ts[i].value) ts[i].value = comment_blank_text;
    ts[i].onclick = function() {if (this.value==comment_blank_text) this.value='';}
  }
}



/******************************************************************************
	Formok kezelese
*/
	
var formElementTypes = new Array(
	'inputrow', 'datepicker', 'accountnumber', 
	'formselect', 'radiogroup', 'checkboxgroup', 
	'formtextarea', 'fileuploader', 'formaddress',
	'fidentifypanel','formhierarchy');

var formElementHandlers = new Array();
formElementHandlers['inputrow'] = FormInputRow;
formElementHandlers['datepicker'] = FormDatePicker;
formElementHandlers['accountnumber'] = FormAccountNumberRow;
formElementHandlers['formselect'] = FormSelectRow;
formElementHandlers['radiogroup'] = FormRadioGroupRow;
formElementHandlers['checkboxgroup'] = FormCheckBoxGroupRow;
formElementHandlers['formtextarea'] = FormTextarea;
formElementHandlers['fileuploader'] = FormFileUploaderRow;
formElementHandlers['formaddress'] = FormAddressRow;
formElementHandlers['fidentifypanel'] = FormIdentifyPanel;
formElementHandlers['formhierarchy'] = FormHierarchy;

if(FormFileUploader_insideRow) {
    formElementTypes.push('fileuploader_inside');
    formElementHandlers['fileuploader_inside'] = FormFileUploader_insideRow;
}

function findForms() {
  $('form').each(function(i) {
		var t = new TabHandler(this);
		multiplyDivs(this);
		setupValidator(this, t);
  });
}


function multiplyDivs(form) {
  //vegyuk vegig az osszes fdmultiplier classu divet es mindegyik ismetlodo elemhez keszitsuk el az elso elemet es a gombokat
  $('div.fdmultiplier').each(function(i) {
    //alapvaltozok beallitasa
		this._copies = 0; //hany ismetlodes van
		this._form = form; // 
    
    //az elso elem elkeszitese
    //copyGroup(this,false);
    
    var saved = $('div.saved',this);
    if (saved.length) {
      
      $(saved).each(function(i) {
        $('input[@savedchecked]',this).attr('checked','checked');
        copyGroup(this,false);
      }).remove();
    } else {
      var source = $('div.source',this);
      if(source.length) copyGroup(source[0],false);
    }
    
		// hozzaado-elvevo gombok hozzaillesztese
		$('<div class="multiplytext" style="text-align:right">Növelhető elem: <img style="vertical-align:middle" onclick="copyGroup($('+"'div.source'"+',this.parentNode.previousSibling)[0])" src="pics/plusz.gif" alt="+"><img style="vertical-align:middle" onclick="removeGroup(this.parentNode.previousSibling)" src="pics/minusz.gif" alt=""></div>').insertAfter(this);

    $('div.form',this).addClass('nemkellvalidalni');
  });
  
}

function copyGroup(el,kellvalidalni) {
  if(typeof el == 'undefined') return;

  if (kellvalidalni===undefined) kellvalidalni=true;
  
  var fdmultiplier = $(el).parents('div.fdmultiplier')[0];
  //vegyuk ki a masolando elem html-eljet es csereljuk le megfelelo nevuekre a id,name,for attributumokat
  var html = el.innerHTML;
  html=html.replace(/ id="?([^"> ]*)"?/g,' id="c_'+fdmultiplier._copies+'.$1.multiplied"');
  html=html.replace(/nemkellvalidalni/g,'');
  html=html.replace(/ for="?([^"> ]*)"?/g,' for="c_'+fdmultiplier._copies+'.$1.multiplied"');
  html=html.replace(/ name="?([^"> ]*)"?/g,' name="c_'+fdmultiplier._copies+'.$1.'+fdmultiplier.id+'.multiplied"');
  
  //csinaljunk egy keret divet es illeszuk be az atalakitott tartalmat
  var newdiv = document.createElement('DIV');
  newdiv.className = 'fdmultiplied';
  newdiv._parent = fdmultiplier;
  newdiv.innerHTML=html; 
  //uj elem beillesztese
	fdmultiplier.parentNode.insertBefore(newdiv, fdmultiplier);
  
	//futtassuk le az uj input elemekre is a validator init-et
	$('div.form',newdiv).each(function(i) {addNodeToValidator(fdmultiplier._form._validator, this,kellvalidalni);})

  //noveljuk a masolasok szamat tarolo countert
	fdmultiplier._copies++;
}

function removeGroup(el) {
  if(typeof el == 'undefined' || !el._copies) return;

  if (!confirm('Biztos, hogy törli a legutolsó ismétlődést?')) return false;
	if (el._copies>1 && el.previousSibling) {
		//torlendo elemben szereplo formelemekrol a validalast leszedni
		$('div.form',el.previousSibling).each(function(i) {removeNodeFromValidator(el._form._validator, this);})
		el.parentNode.removeChild(el.previousSibling);
		el._copies--;
	}
}

var parser = new EParser();

function handleFunctionNode(node, relation) {
	var tokens = parser.parse(node.getAttribute('function'));
	var str = '';
	for (var j=0; j<tokens.length; j++) {
		if (tokens[j].type == 'var') {
			str += 'parseFloat(' + tokens[j].value + '.value)';
		} else {
			str += tokens[j].value;
		}
	}

	var varNames = parser.getVarNames(node.getAttribute('function'));
	var n1 = node.getAttribute("ID");
	if (!relation.hasVar(n1)) {
		relation.addVar(new MVar(n1, str));
	}
	
	relation.addFunc(n1, str);
	
	for (var j=0; j<varNames.length; j++) {
		var n2 = varNames[j];
		if (!relation.hasVar(n2)) {
			relation.addVar(new MVar(n2));
		}
		relation.add(n2, n1);
	}
}

function hideWarning(el) {
	el.style.visibility = 'hidden';
}

function addNodeToValidator(validator, node, kellvalidalni) {
	if (kellvalidalni) {
  	var a = new Array();
  	a[0] = node.getAttribute("ID");
  
  	var sp = document.createElement("span");
  	sp.style.display='inline';
  	var id = "w_" + a[0];
  	sp.id = id;
  	sp.className = "warning";
  	sp.appendChild(document.createTextNode(mark));
  	sp.onmouseover = function onmouseover() { hideWarning(this); };
  	node.insertBefore(sp, node.childNodes[1]);
  
  	for (var q=0; q<formElementTypes.length; q++) {
  		if (hasClassLabel(node, formElementTypes[q])) {
  			node._type = formElementTypes[q];
  			a[1] = new formElementHandlers[formElementTypes[q]](node, 1);
  		}
  	}
  			
  	if (hasClassLabel(node, 'mandatory')) {
  		node._mandatory = 'mandatory';
  	}
  	if (hasClassLabel(node, 'fidentifypanel')) {
  		onIndetifyPanelClick(node.getElementsByTagName('INPUT')[0]);
  	}
  	if (hasClassLabel(node, 'datepicker')) {
  //			ce.getElementsByTagName('INPUT')[0].setAttribute('ID', ce.getAttribute('name'));
  		dates.add(node);
  	}
  	
  	if (hasClassLabel(node, 'formhierarchy')) {
  		var x = new _FormHierarchy(node);
  	}  

    if (node.getAttribute('function')!=null) {
  		handleFunctionNode(node, validator.varRelation);
  	}
  }	
	
	// set tooltip
	var Imgs = node.getElementsByTagName('IMG');
	for (var q=0; q<Imgs.length; q++) {
		if (Imgs[q].className == "tooltipimg") {
			if (node.title != '') {
				Imgs[q].src = "html/formviewer/help.gif";
				var toolTipDiv = document.createElement('DIV');
				toolTipDiv.className = 'tooltip';
				toolTipDiv.innerHTML = node.title;
				toolTipDiv.id = node.id + '_tooltip';
				node.title = "";
				Imgs[q].toolTipId = toolTipDiv.id;
				Imgs[q].onmouseover = function onmouseover(event) { showToolTip(event, this.toolTipId, this, 1); };
				Imgs[q].onmouseout = function onmouseout(event) { showToolTip(event, this.toolTipId, this, 0); };
				node.appendChild(toolTipDiv);
			} else {
				Imgs[q].parentNode.removeChild(Imgs[q]);
			}
		}
	}
  // set comment
  var divs = node.getElementsByTagName('DIV');
	for (var q=0; q<divs.length; q++) {
		if (divs[q].className == "commentSwitch") {
		  divs[q].innerHTML='<a href="#" onClick="showhideComment(this);return false;">[+]</a>';
		}
	}
	
	if (kellvalidalni) validator.addField(a[0], a);
}

function removeNodeFromValidator(validator, node) {
	var nodeName = node.getAttribute("ID");
	if (hasClassLabel(node, 'datepicker')) {
		dates.remove(node);
	}
	validator.removeField(nodeName);
}

var dates = new DPicker();

function setupValidator(form, tabh) {
	var val = new Validator();
	val.varRelation = new MRelation();
	val.form = form;
	if (tabh != undefined) val.tabhandler = tabh;
	var IDs = "";
	mark = "!Hiba!";
	
	$('div.form',form).each(function(i) {
	  addNodeToValidator(val, this, !hasClassLabel(this, 'nemkellvalidalni'));
	});

	form._validator = val;
	form._funceval = val.varRelation;
	return ;
}
	
function testStyle() {
	for (var i=0; i<document.forms.length; i++) {
		var str = document.forms[i]._funceval.getEvalStr();
//			alert(str);
		eval(str);
		if (document.forms[i]._validator.validate()) {
			//alert('OK!');
		}
//			if (document.forms[i]._validator)) {
//				document.forms[i].submit();
//			}
//			alert(str);
	}
}

function initFormProcessor() {
	var formnum = 0;
	if (typeof formsToCheck != 'undefined') {
		if (typeof formsToCheck == 'object') { 
			for (i=0; i<formsToCheck.length; i++) {
				formnum++;
				var el = document.getElementById(formsToCheck[i]);
				if (el) {
				  var t = new TabHandler(el);
				  multiplyDivs(el);
				  setupValidator(el, t);
				}
			}
		}
	} else {
		for (i=0; i<document.forms.length; i++) {
			formnum++;
			var t = new TabHandler(document.forms[i]);
			multiplyDivs(document.forms[i]);
			setupValidator(document.forms[i], t);
		}
	}
  var linked_input_elements = $('div.form.Linked');
  for(var i=0;i<linked_input_elements.length;i++) {
    linked_inputs_getdata(linked_input_elements[i]);	
    $('div.commentSwitch',linked_input_elements[i]).prepend("<a href=\"#\" onClick=\"linked_inputs_getdata($(this).parents('div.form.Linked')[0]);return false;\">Frissít</a>&nbsp;|&nbsp;");
  }
  
	if (formnum == 0) {
		alert('No forms found! :(');
	} else {
		formProcessorInitialized = true;
	}
}

function isFormItemLoading(form) {
  var formNode = document.getElementById(form);
  var formItemAr = $('div.form',formNode);

  for (var i=0; i<formItemAr.length;i++) {
    for (var v=0; v<formNode._validator.fields.length; v++) {
      if (formNode._validator.fields[v][0] == formItemAr[i].id) {
        if (formNode._validator.fields[v][1].isLoading != undefined) {
          if (formNode._validator.fields[v][1].isLoading()) return true;        
        }
      }      
    } // for validator
  } // for formitem

	return false;
}


function checkFormValidity(form) {
	if (!formProcessorInitialized) {
		alert('Form error!');
		return;
	}
	
	
	if (form == undefined || form == 'all') {
		for (var i=0; i<document.forms.length; i++) {
			var str = document.forms[i]._funceval.getEvalStr();
			
		  if (isFormItemLoading(document.forms[i])) return false;
			
			eval(str);
      if (document.forms[i]._validator.validate()) {
			
				//alert('OK!');
	  		//az ismetlodo mezo source elemeit nem postoljuk
  			$('div.fdmultiplier div.source',el).remove();

				document.forms[i].submit();
			}
			else {
				alert('Form kitöltési hiba.');
			}
		}
	} else {
		var el = document.getElementById(form);
		
		if (isFormItemLoading(form)) return false;
		
		var str = el._funceval.getEvalStr();
		eval(str);
		if (el._validator.validate()) {
			//alert('OK!');
			//az ismetlodo mezo source elemeit nem postoljuk
			$('div.fdmultiplier div.source',el).remove();

			el.submit();
		}
		else {
			alert('Form kitöltési hiba.');
		}
	}
}

function linked_inputs_getdata(input_div) {
  var form_id = input_div.getAttribute('form_id');
  var input_index = input_div.getAttribute('input_index');
  if (form_id.match(/\D/) && input_index.match(/\D/)) return false;

  $.get(CFG.get_from_saveddata,{nodeid:form_id},function(xml) {
    var inps = $('input,select,textarea',input_div);
    xml = xml.replace(/\n|\r/g,"");
    for(var i=0;i<inps.length;i++) {
      var re = new RegExp(".*<"+inps[i].name+">(.*)</"+inps[i].name+">.*","i");
      var value = xml.replace(re,"$1");
      if (value!=xml) inps[i].value = value;
    }
  },
  'text');
}


formProcessorInitialized = false;

/*var o_db_onload = document.onload;
onload = function() {
	initFormProcessor();
	if (o_db_onload!=undefined) {
		o_db_onload();	
	}
}*/
