/* v 1.3

	v1.3 - template - egyszerű user keresés
	v1.2 - title
	v1.1 - értelmesebb id és class kezelés (2008.01.02)
	v1.0
	v0.1 - belső keresés
*/
/*

	- template használata egyszerű user kereséshez

		- title-el, kereső mező nélkül
		{include file="`$smarty.const.COMMON_TEMPLATE_DIR`usersbox.tpl" box_object="UserSearch" name="akarmi[akarmi]"}

		- title-el, kereső mezővel
		{include file="`$smarty.const.COMMON_TEMPLATE_DIR`usersboxsearch.tpl" box_object="UserSearch" name="akarmi[akarmi]"}

		- user kiválasztásánál létrehoz egy input type=hidden tag-et a name attr felhasználásával
			<input type=hidden name="***akarmi[akarmi]***" value="***cust_base_id***">

		- következő fejlesztés, ha ebben az input hidden -ben már van egy id, akkor megy egy lekérdezés az id-ra

	- keresés
	<span>Keresés: <input type="text" class="searchInput" box_object = "SearchUsers" role = "student"></span>

	- title
	<div id = "LeftList_title" class = "box_title">
		<TABLE class="box_title_table">
		<TR>
			<TD class="box_title_left"></TD>
			<TD class="box_title_right"></TD>
		</TR>
		</TABLE>
	</div>

	- html kód
	<div id = "LeftList" class="box" style="">
		<span style="position:absolute;display:none" id = "box-loading"><img src="{$smarty.const.WEB_IMG_DIR}../images/loading.gif"></span>
		<div class = "item">
			<div>
				<div class = "u_name"></div>
			</div>
		</div>
	</div>


	- javascript kód
	Param = new BoxParam('LeftList',{"fields":['u_name'],"key":"u_id",search_field:"u_name"});
	LeftList = new Box('LeftList',Param);
	LeftList.data = [{u_id:1,u_name:'x'},{u_id:1,u_name:'y'}];
	LeftList.draw();



	- ez benne van a default css-ben
	- ha felül kell írni, akkor #LeftList * -ra hivatkozva felülírható gondolom :) (vagy a box-ot átírni)

	.box {		text-align:left;		width:200px;		height:150px;		border: 2px solid #0096d6;		overflow: auto;		background: InactiveBorder;	position:relative; }	
	.box .box_item, .box .box_item_active {		font-size: 10pt; 		border-bottom: 1px solid black;		min-height: 40px;		padding: 3px 0px 3px 8px;	}	
	.box .box_item {		color: #666666;		background: white;	}	
	.box .box_active {		background: #00c6f6;		color: white;	}

*/


function Key () {
	this.ENTER = 13;
	this.UP = 38;
	this.DOWN = 40;
	this.DELETE = 46;
	this.TAB = 9;
	this.RETURN = 13;
	this.ESCAPE = 27;
}
Key = new Key();
var Key = {
	ENTER:13,
	UP:38,
	DOWN:40,
	DELETE:46,
	TAB:9,
	RETURN:13,
	ESCAPE:27
}


function BoxParam (id,_params) {
	this.id = id;
	this.item_tag = 'div';
	this.item_class = 'item';
	this.parent_id = 'box';
	this.keyDown = true;
	this.dblclick = false;
	this.title = false;
	this.search_field;
	for (var i in _params) {
		//console.log(typeof _params.prototype);
		eval('this.' + i + ' = _params[\'' + i + '\'];');
	}
}
function Box(_name,_config,_params) {

	this.utils = Utils;
	this.config = _config;
	this.objectName = _name;
	this.data = [];
	this.items = [];
	this.fields = [];
	this.item_count = 0;
	this.query_id = null;
	this.item_id = null;
	this.parent = this.utils.ge(this.config.id);
	this.modify = this.utils.ge(this.config.id+'Modify');
	this.search = null;
	this.activeData = null;
	this.keyPressed = new Date();
	this.keyPressTolerance = 1000; // 1 másodperc
	this.keyPressData = [
		{"keyNum":Key.DOWN,"action":"this.nextItem()"},
		{"keyNum":Key.UP,"action":"this.previousItem()"}
	];
	this.click = true;
	this.loading = function () {
		this.container.innerHTML = '';
		this.item_count = 0;
		this.items = [];
	
		this.query_id = null;
		
		this.item_id = null;
		this.utils.showObj(this.loading_el);
	}
	this.loaded = function () {
		this.utils.hideObj(this.loading_el);
	}
	this.constructor = function() {
		if (!this.parent) {
			Common.error('Nincs parent! ('+this.config.id+')');
			return false;
		}
		this.loading_el = this.utils.getElementByAttribute(this.parent,'span',['id'],['box-loading']);
		if (!this.loading_el) {
			this.loading_el = this.utils.getElementByAttribute(this.parent,'span',['id'],['box_loading']);
		}
		if (!this.loading_el) {
			this.loading_el = this.utils.getElementByAttribute(this.parent,'span',['id'],['loading']);
		}
		this.node = this.utils.getElementByClassName(this.parent,this.config.item_tag,this.config.item_class);
		if (!this.node) {
			Common.error('Nincs item deklarálva!');
			return false;
		}
		Utils.hide(this.node);

		this.container = this.utils.addElement(this.parent,'div',['class'],[this.config.parent_id + '_container']);

		// a box-on belüli bill leütés
		if (this.config.keyDown) {
			this.searchEl = document.createElement('input');
			this.searchEl.className = 'hide_element_input';
			//this.container.parentNode.parentNode.insertBefore(this.searchEl,this.container.parentNode);
			this.container.parentNode.parentNode.appendChild(this.searchEl);
			this.utils.addEvent(this.parent,'click',this.generateFunction(this.objectName,'parentClick'));
			this.utils.addEvent(this.searchEl,'keydown',this.generateFunctionEvent(this.objectName,'keyDown'))
		}

		// title / címsor 
		this.title = this.utils.ge(this.config.id+'_title');
		if (this.config.title)	{
			this.title_left = this.utils.getElementByClassName(this.title,'td',this.config.parent_id+'_title_left');
			this.title_right = this.utils.getElementByClassName(this.title,'td',this.config.parent_id+'_title_right');
			/*
			this.title = document.createElement('div');
			this.title.id = this.config.parent_id + '_title';
			this.title_left = document.createElement('div');
			this.title_left.style.cssFloat = 'left';
			this.title_right = document.createElement('div');
			this.title_right.style.cssFloat = 'right';
			this.title.appendChild(this.title_left)
			this.title.appendChild(this.title_right);
			this.container.parentNode.parentNode.insertBefore(this.title,this.container.parentNode);
			*/
		} else {
			// ha van title és még sem kell akkor tüntessük el
			if (this.title) {
				this.utils.hideObj(this.title);
			}
		}

		var clear = document.createElement('div');
		clear.style.cssText = 'clear:both;';
		this.container.parentNode.parentNode.insertBefore(clear,this.container.parentNode);

	}

	this.keyDownEvent = function (keyNum) {
		for (var i in this.keyPressData) {
			var key = this.keyPressData[i];
			if (key.keyNum == keyNum) {
				eval(key.action);
				return true;
			}
		}
	};
	this.keyDown = function (keyChar,keyNum) {
		if (!/^[a-zA-Z]$/.test(keyChar)) {
			this.keyDownEvent(keyNum);
			return true;
		}
		if (typeof this.config.search_field == 'undefined') {
			// nincs keresési mező
			Common.error('Ismeretlen hiba: Nincs kereső mező megadva!');
			return false
		}

		var d = new Date();

		var diff = d - this.keyPressed;
		// ha pl 1 másodperce nem volt key leütés
		if (diff > this.keyPressTolerance) {
			// a search input-ot lenullázzuk
			this.searchEl.value = '';
		}
		this.keyPressed = d;

		var search = this.searchEl.value+keyChar;

		var scroll = 0;
		var scrollTop = this.parent.scrollTop;
		// this.parent.scrollTop += oldItem.offsetHeight;
		for (var i = 0; i < this.data.length ; i++) {
			var text = eval("this.data[i]."+this.config.search_field);
			if (search.toUpperCase() == text.substr(0,search.length).toUpperCase()) {
				this.activeChange(this.items[this.item_id],this.items[i]);			
				// scrollbar beállítása
				this.parent.scrollTop = scroll;
				// az első találat után lépjen ki
				return true;
			}
			scroll += this.items[i].offsetHeight;
		}
		// nincs találat, rakjuk vissza az eredeti poziciójára
		// elvileg ez nem nagyon kell, mert ha nem találta akkor nem mozdul a scroll
		this.parent.scrollTop = scrollTop;
	}
	this.parentClick = function () {
		this.searchEl.focus();
//		this.parent.scrollTop = scrollTop;
	}

	this.getItem = function () {
		return this.items[this.item_id];
	}
	this.getData = function () {
		return this.data[this.item_id];
	}
	this.setRows = function () {
		this.container.innerHTML = '';
		this.item_count = 0;
		this.items = [];
		this.query_id = null;
		this.item_id = null;
		this.loaded();
		if (this.utils.isFunction(this._setRows)) {
			this._setRows();
		}
		if (!this.data.length) return null;
		for (var i = 0;i<this.data.length ; i++) {
			var data = this.data[i];
			var el = document.createElement(this.config.item_tag);
			this.utils.addEvent(el,'click',this.generateFunction(this.objectName,'_onClick'));
			if (this.config.dblclick) {
				this.utils.addEvent(el,'dblclick',this.generateFunction(this.objectName,'_onDblClick'));
			}
			el.innerHTML = this.node.innerHTML;
			//el.className = this.config.parent_id + '_item';
			el.style.cursor = 'pointer';
			el.setAttribute('depth',"1");
			this._setData(el,data);
			this.setInactive(el);
			var item = this.container.appendChild(el);
			this.items.push(item);
		}
		if (this.config.title){
			this.title_left.innerHTML = '';
			this.utils.addText(this.title_left,this.data.length + ' darab találat');
		}
	};
	this.smartDraw = function (data) {
		this.loaded();
		this.data = data;
		this.draw();
	}
	this.draw = this.setRows;
	this.clear = function () {
		this.smartDraw([]);
	}

	this._setData = function (el,data) {
		el.id = this.config.id + "_" + this.item_count;
		el.setAttribute('_id',this.item_count);
		for (var i in this.config.fields) {
			//console.log(this.config.fields[i],data[this.config.fields[i]]);
			//console.log(data);
			var tag = this.utils.getElementByClassName(el,'*',this.config.fields[i]);
			
			if (typeof tag == 'undefined') {
				Common.error(this.config.fields[i]);
			}
			//this.utils.setValue(tag,data[this.config.fields[i]],this.config.fields[i]);
			this.utils.setValue(tag,eval('data.'+this.config.fields[i]),this.config.fields[i]);
		}
		this.item_count++;
		if (this.utils.isFunction(this.setData)) {
			this.setData(el,data);
		}
	}
	this.setActive = function (el) {
		// ez nagyon kérdéses
		el.className = this.config.parent_id + '_item_active'+ ' SearchItemActive';

	}
	this.setInactive = function (el) {
		//this.items[this.item_id]
		el.className = this.config.parent_id + '_item' + ' SearchItem';
	}
	this.activeChange = function (oldItem,newItem) {
		this.setInactive(oldItem);
		this.query_id = null;
		this.setActive(newItem);
		this._onClick(newItem);
	}
	this.previousItem = function () {
		var oldItem = this.items[this.item_id];
		var newItem = this.items[this.item_id-1];
		if (typeof newItem == 'undefined') {
			return true;
		}
		this.activeChange(oldItem,newItem);
		//ha a legutolsó elemnél állunk, akkor ne scrollozza, mert zavaró
		this.parent.scrollTop = (this.items.length-2==this.item_id) ? this.parent.scrollTop : this.parent.scrollTop - oldItem.offsetHeight;
	}
	this.nextItem = function () {
		var oldItem = this.items[this.item_id];
		var newItem = this.items[this.item_id+1];
		if (typeof newItem == 'undefined') {
			return true;
		}
		this.activeChange(oldItem,newItem);
		//ha a legelső elemnél állunk, akkor ne scrollozza, mert zavaró
		this.parent.scrollTop = (this.parent.scrollTop == 0) ? 1 : this.parent.scrollTop + oldItem.offsetHeight;
	}
	this._onClick = function (obj) {
		/*
		if (this.click == true) {
			var object = this;
			this.click = false;
			setTimeout(function () { object.click = true; },400);
		} else {
			return true;
		}
		*/

		if (obj.getAttribute('depth') != "1") {
			obj = this.utils.getParentNode(obj,this.config.item_tag,'depth','1');
		}

		if (this.utils.getElementByClassNameSmart(this.parent,this.config.item_tag,this.config.parent_id + '_item_active')) {
			this.setInactive(this.utils.getElementByClassNameSmart(this.parent,this.config.item_tag,this.config.parent_id + '_item_active'));
		}
		this.setActive(obj);
		this.query_id = eval("this.data[obj.getAttribute('_id')]."+this.config.key);

		this.item_id = parseInt(obj.getAttribute('_id'));
		
		// ha van title beírjuk hányadik van kiválasztva
		if (this.config.title) {
			this.title_right.innerHTML = '';
			this.utils.addText(this.title_right,this.item_id+1+' / '+this.item_count);
		}

		if (this.utils.isFunction(this.config.afterOnClick)) {
			this.config.afterOnClick(this,obj);
		}
		if (this.utils.isFunction(this.onClick)) {
			this.onClick(obj);
		}
		if (this.utils.isFunction(this.smartOnClick)) {
			this.smartOnClick(this.getData());
		}
	}
	this._onDblClick = function (obj) {
		if (obj.getAttribute('depth') != "1") {
			obj = this.utils.getParentNode(obj,this.config.item_tag,'depth','1');
		}
		if (Utils.isFunction(this.onDblClick))	{
			this.onDblClick(obj);
		}
	}
	this._delItem = function (id) {
		this.utils.destroy(this.items[this.item_id]);
		this.items = Utils.removeArray2(this.items,this.item_id)
		this.data = Utils.removeArray2(this.data,this.item_id)
		this.setRows();
	}

	this.generateFunction = function(objName,method) {
		return function (ev) {
		  ev || (ev = window.event);

		  // mely objektum váltotta ki az eseményt?
		  var source;
		  if (typeof ev.target != 'undefined') {
			source = ev.target;
		  } else if (typeof ev.srcElement != 'undefined') {
			source = ev.srcElement;
		  } else { return(true); }
		  eval(objName+"."+method+"(source)");
		};
	}
	this.generateFunctionEvent = function(objName,method) {
		return function (e) {
			var keynum;
			var keychar;
			if(window.event) // IE
			{
			keynum = e.keyCode
			}
			else if(e.which) // Netscape/Firefox/Opera
			{
			keynum = e.which
			}
			keychar = String.fromCharCode(keynum);
			eval(objName+"."+method+"(keychar,keynum)");
		};
	}
	this.getAll = function (keys,values) {
		this.data = [{u_id:1,u_name:"Födémesi Csaba"},{u_id:1,u_name:"Erdélyi István"},{u_id:1,u_name:"Makai Lajos"},{u_id:1,u_name:"Födémesi Csaba"},{u_id:1,u_name:"Erdélyi István"},{u_id:1,u_name:"Makai Lajos"}];
		this.setRows();
		return true;

		var thisAll = new Json(this.objectName);
		thisAll.object = this;
		thisAll.addParam('type',SQL_SELECT_ALL);
		if (typeof keys != 'undefined' && typeof values != 'undefined') {
			thisAll.addParam(keys,values);
		} else {
			if (typeof this.config.foreign != 'undefined' && this.config.foreign == true) {
				// ha külső objektum paraméterét kell átadni
				if (eval("typeof "+this.config.foreign_object+".query_id") == 'undefined' || eval(this.config.foreign_object+".query_id") == null) {
					Common.Error(this.objectName);
					Common.Error('Nincs paraméter, vagy nincs külső kulcs!');
					console.trace();
					return false;
				} 
				thisAll.addParam(this.config.foreign_key,eval(this.config.foreign_object+".query_id"));
			}
		}
		thisAll.successMethod = function (object,json) {
			object.data = json.data;
			object.setRows();
		}
		thisAll.send();	
	}

	this.selectFirstItem = function () {
		this._onClick(this.items[0]);
	}

	for (var i in _params) {
		eval('this.' + i + ' = _params[\'' + i + '\'];');
	}

	this.constructor();
}

