
function addEvent(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);
	} 
}

function setSelectionRange(obj) {
	if(obj && typeof(obj) == "object" && (obj.type == "text" || obj.type == "textarea")) {
		if(obj.createTextRange) {
			var range = obj.createTextRange();
			range.moveStart("character", 0);
			range.moveEnd("character", obj.value.lengh-1);
			range.select();
		} else { 
			if(obj.setSelectionRange) {
				obj.setSelectionRange(0,obj.value.length);
			}
		}
		obj.focus();
	}
	if(obj && typeof(obj) == "object" && obj.options) { obj.focus(); }
}
	
var AjaxSearchItems;
function AjaxSearch(div,displayNone) {
	
	//fields
	
	this.parentDIV = div;        //pole w ktorym zawiera sie pole wyszukiwania
	this.div;                    //pole glowne wyszukiwania
	this.inputSearch;            //input wyszukiwania
	this.timeout;                //wskaznik zwracany przez setTimeout przy wcisnieciu klawisza
	this.searchDelay = 800;      //opoznienie wyszukiwania
	this.divList;                //pole w ktorym wyswietlana bedzie lista znalezionnych elementow
	this.ajaxSearchItem;         //unikalny identyfikator;
	this.module = 'EcmQuotes';
	this.inputCode;
	
	this.positionSelected;
	
	//functions
	this.setInputCode = function(input) {
		this.inputCode = input;
		this.inputCode.previousCode = this.inputCode.value;
	}
	
	this.inputSearchOnKeyDown = function(e,other) {
		var keynum;
		if(typeof(e) == "number") 
			keynum = e;
		else {
			if(window.event) //IE
				keynum = e.keyCode;
			else
				keynum = e.which;
		}
		
			if(keynum == 38) { this.selectPreviousPosition(); return false; }
			if(keynum == 40) { this.selectNextPosition(); return false; }		
			if(keynum == 13 || keynum == 9) { this.inputSearchEnterPressed(other); return false; }	
			if(keynum == 27) { this.div.style.display = 'none'; }

			if(this.timeout) { clearTimeout(this.timeout); this.timeout = null; }
			this.timeout = setTimeout("document.getElementById('"+this.div.id+"').AjaxSearch.search();", 500);
	}
	
	this.inputSearchEnterPressed = function(other) {
		if(this.positionSelected) {
			var row;
			if(N.selectedRow) {
				N.selectedRow.setData(this.positionSelected.positionData);
				row = N.selectedRow;
			}
			else {
				row = N.addRow().setData(this.positionSelected.positionData);
			}
			row.calculateTotal();
			if((other && other == "clear") || OPT['quick_product_item_adding']==0) { 
				this.clearList();
				this.div.style.display = 'none';
				if(OPT['quick_product_item_adding'] == 0) if(N.selectedCell && N.selectedCell.index == 1) N.selectedCell.selectNext();	
			} else { 
				row.noHideASP = true;
				if(N.selectedRow) row = row.myTable.addRow(row.index+1);
				row.select();
				row.cells.item(0).select();
				setSelectionRange(this.inputSearch);
			}
		} 
			else if(N.selectedRow) {
			if(this.inputSearch.value != this.inputCode.previousCode || this.inputCode.previousCode == '') {
				var data = new Object();
				N.selectedRow.setData(data);
				N.selectedRow.cells.item(1).select();
			}
			
			
		}
		//N.addRow();	
	}
	
	this.selectNextPosition = function() {
		if(this.positionSelected) {
			if(this.positionSelected.nextSibling) {
				this.positionSelect(this.positionSelected.nextSibling);
				return;
			}
		}
		this.positionSelect(this.divList.lastChild);
	}
	
	this.selectPreviousPosition = function() {
		if(this.positionSelected) {
			if(this.positionSelected.previousSibling) {
				this.positionSelect(this.positionSelected.previousSibling);
				return;
			}
		}
		this.positionSelect(this.divList.firstChild);
	}
	
	this.search = function() {
		
		if(this.inputSearch.value == '') { this.clearList(); return; }
		var _ajax_search_process_search_ = this;
		this.Display = function(result) { _ajax_search_process_search_.processSearch(result.responseText); }
		this.Fail = function(result) { alert(result.responseText); }
		YAHOO.util.Connect.asyncRequest('POST','index.php',{success:this.Display,failure:this.Fail},'module='+this.module+'&action=AjaxSearchQuery&to_pdf=1&as_inputSearch='+this.inputSearch.value); //+'&ecmlanguage='+document.forms.EditView.ecmlanguage.value);
	
	}
	
	this.processSearch = function(result) {
		this.clearList();
		var list = eval(result);
		if(typeof(list) != "object") return;
		this.fillList(list);
	}
	
	this.clearList = function() {
		this.divList.innerHTML = '';
		this.divList.style.height = '';
		this.positionDeselect();
	}
	
	this.fillList = function(list) {
		for(x in list) {
			this.addPosition(list[x]);	
		}
		this.positionSelect();
		this.setScrolls();
	}
	
	this.setScrolls = function() {
		var clientH = -1;
        if(window.innerHeight && window.innerHeight > 0) clientH = window.innerHeight;
		else if(document.documentElement && document.documentElement.clientHeight > 0) clientH = document.documentElement.clientHeight;
		else if(document.body && document.body.clientHeight > 0) clientH = document.body.clientHeight;
		var XY = YAHOO.util.Dom.getXY(this.div);
		var divTop = (XY[1]+this.div.offsetHeight);
		if((divTop - (clientH+document.body.scrollTop)) > 0) {
			var newPos = divTop-clientH;
			document.body.scrollTop = newPos;
		}
	}
	
	this.positionSelect = function(div,noScroll) {
		if(!div) {
			if(!this.positionSelected) {
				if(this.divList.firstChild) this.positionSelect(this.divList.firstChild);
			}
			return;
		}
		this.positionDeselect();
		div.className = 'AjaxSearchPositionDivSelected';
		this.positionSelected = div;
		if(!noScroll) this.divList.scrollTop = div.offsetTop;
	}
	
	this.positionDeselect = function() {
		if(this.positionSelected) {
			this.positionSelected.className = '';
			this.positionSelected = null;
		}
	}
	
	this.addPosition = function(list) {
		if(typeof(list.code) == "undefined") return;
		var position = document.createElement('div');
			position.positionData = list;
			position.onclick = function() { this.parentNode.AjaxSearch.inputSearchEnterPressed(this); }
			position.onmouseover = function() { this.parentNode.AjaxSearch.positionSelect(this,true); };
			position.innerHTML = '<table width="100%" class="AjaxSearchPositionTable"><tr><td class="AjaxSearchPositionTableCode">'+this.markElement(list['code'])+'</td><td align="right" class="AjaxSearchPositionTablePrice">'+list['purchase_price']+' '+list['currency_symbol']+'<span style="color:black">  -  </span><b>'+list['selling_price']+' '+list['currency_symbol']+'</b></td></tr><tr><td colspan="2" class="AjaxSearchPositionTableName">'+this.markElement(list['name'])+'</td></tr></table>';
		this.divList.appendChild(position);
		if((position.offsetTop+position.offsetHeight) > 300) this.divList.style.height = '300px'; else this.divList.style.height = '';
	}
	
	this.markElement = function(str) {
		var s = "("+this.inputSearch.value+")";
		var regExp = new RegExp(s,'gi');
		return str.replace(regExp,"<b>$1</b>");
	}
	
	this.AjaxSearchFrozen = false;
	this.AjaxSearchGetSettings = function () {
		var AjaxSearchToReq = this;
		YAHOO.util.Connect.asyncRequest(
			'POST',
			'index.php',
			{
				success: function(response) {
					if(response.responseText) {
						var str = response.responseText;
						var obj = eval(str);
						if(obj && obj[0]) {
							obj = obj[0];
							//if(obj.frozen) {
								AjaxSearchToReq.div.style.left = obj.pos_left;
								AjaxSearchToReq.div.style.top = obj.pos_top;
								AjaxSearchToReq.AjaxSearchFrozen = !(obj.frozen == "true" ? true : false);
								AjaxSearchToReq.AjaxSearchFreezePosition(true);
							//}
						}
					}
				},
				failure: function(response) {}
			},
			'module=Home&action=EcmAjaxSearchSettings&function=GetSettings&to_pdf=1&from_module='+this.module
		);
	}
	this.AjaxSearchSaveSettings = function () {
		YAHOO.util.Connect.asyncRequest(
			'POST',
			'index.php',
			{
				success: function(response) {},
				failure: function(response) {}
			},
			'module=Home&action=EcmAjaxSearchSettings&function=SaveSettings&to_pdf=1&from_module='+this.module+'&pos_top='+this.div.style.top+'&pos_left='+this.div.style.left+'&frozen='+this.AjaxSearchFrozen
		);
	}
	this.AjaxSearchFreezePosition = function (dontSave) {
		var img = document.getElementById('AjaxSearchPin');
		if(this.AjaxSearchFrozen) {
			img.src='modules/'+this.module+'/AjaxSearch/AjaxSearchPinOff.gif';
			this.AjaxSearchFrozen = false;
		} else {
			img.src='modules/'+this.module+'/AjaxSearch/AjaxSearchPinOn.gif';
			this.AjaxSearchFrozen = true;			
		}
		if(!dontSave) this.AjaxSearchSaveSettings();
	}
	
	this.createForm = function() {
		/*
		var div = document.createElement('div');
			div.className = 'AjaxSearch';
			div.AjaxSearch = this;
		*/
		var tmp = document.createElement('div');
		var div = "<div></div>";
			tmp.innerHTML = div;
			div = tmp.firstChild;
			
			div.className = 'AjaxSearch';
			div.AjaxSearch = this;			
			div.onMouseMoveEvent = function(ev) {
				if(!this.isOnMouseDown) return;
				ev = ev || window.event;
				var x = 0; var y = 0;
				if(ev.pageX || ev.pageY) {
					x = ev.pageX;
					y = ev.pageY;
				} else {
					x = ev.clientX + document.body.scrollLeft - document.body.clientLeft,
					y = ev.clientY + document.body.scrollTop  - document.body.clientTop
				}
				this.style.left = x-this.MouseX;
				this.style.top = y-this.MouseY;
			}
			div.onMouseDownEvent = function(ev) {
				if(this.noDrag) { this.noDrag = false; return; }
				ev = ev || window.event;
				var x = 0; var y = 0;
				if(ev.pageX || ev.pageY) {
					x = ev.pageX;
					y = ev.pageY;
				} else {
					x = ev.clientX + document.body.scrollLeft - document.body.clientLeft,
					y = ev.clientY + document.body.scrollTop  - document.body.clientTop
				}
				this.MouseX = x-this.offsetLeft;
				this.MouseY = y-this.offsetTop;
				this.isOnMouseDown = true;
				this.style.cursor = 'move';	
			}
			div.onmouseup = function() {
				this.isOnMouseDown = false;
				this.style.cursor = '';
				//this.AjaxSearch.AjaxSearchSaveSettings();
			}
			//div.onmouseout = function() { this.onmouseup(); }
			ddiv = document.createElement('div');
			ddiv.id = 'AjaxSearch_ddiv';
			ddiv.className = 'AjaxSearch_ddiv';
			ddiv.appendChild(document.createTextNode('Search Product:'));
			ddiv.appendChild(document.createElement('br'));
			div.appendChild(ddiv);
		/*
		var inputSearch = document.createElement('input');
			inputSearch.type = 'text';
			inputSearch.id = 'as_inputSearch';
			inputSearch.className = 'AjaxSearchInputSearch';
			inputSearch.AjaxSearch = this;
			inputSearch.onkeydown = this.inputSearchOnKeyDown; 
			this.inputSearch = inputSearch;
			div.appendChild(inputSearch);
		*/
		var img = '<img src="modules/'+this.module+'/AjaxSearch/AjaxSearchPinOff.gif" id="AjaxSearchPin" class="AjaxSearchPin" onclick="this.parentNode.AjaxSearch.AjaxSearchFreezePosition();" />';
		    img += '<img src="modules/'+this.module+'/AjaxSearch/AjaxSearchCloseIcon.gif" class="AjaxSearchCloseIcon" onclick="this.parentNode.AjaxSearch.inputSearchOnKeyDown(27);" />';
			div.innerHTML += img;
			
			
		var inputSearch = '<input type="text" id="as_inputSearch" class="AjaxSearchInputSearch" onKeyDown="return this.AjaxSearch.inputSearchOnKeyDown(event);">'; 
			div.innerHTML = div.innerHTML + inputSearch;
			this.inputSearch = div.lastChild;
			this.inputSearch.AjaxSearch = this;
			this.inputSearch.onmousedown = function() { this.parentNode.noDrag = true; }

			div.appendChild(document.createElement('br'));
			div.appendChild(document.createElement('br'));
			
		/*
			div.appendChild(document.createTextNode('List:'));
		
		var separator = document.createElement('hr');
			separator.className = 'AjaxSearchSeparator';
			div.appendChild(separator);
		*/
		
		var divList = document.createElement('div');
			
			divList.id = 'as_divList';
			divList.className = 'AjaxSearchDivList';
			divList.AjaxSearch = this;
			this.divList = divList;
			divList.onmousedown = function() { this.parentNode.noDrag = true; }
			div.appendChild(divList);
		
		var tmpDiv = document.createElement('div');
			tmpDiv.style.height = '10px';
			div.appendChild(tmpDiv);
		
		this.parentDIV.appendChild(div);
		this.div = div;
		
	}

	this.KeyDown = function(e) {
		
		var keynum;
		if(window.event) //IE
			keynum = e.keyCode;
		else
			keynum = e.which;
			

		
	}
	
	
	//constructor
	
	if(AjaxSearchItems) { 
		if(typeof(AjaxSearchItems) == "number") 
			AjaxSearchItem++;
		else
			AjaxSearchItem = 0;
		this.ajaxSearchItem = AjaxSearchItem;
	}
	
	this.createForm();
	
	this.div.AjaxSearch = this;
	this.div.id = 'AjaxSearch_'+this.AjaxSearchItem;
	var AjaxSearch_draganddrop = new YAHOO.util.DD(this.div.id);   
		AjaxSearch_draganddrop.AjaxSearch = this;
	AjaxSearch_draganddrop.endDrag = function(e) {
		this.AjaxSearch.AjaxSearchSaveSettings();
	};
	AjaxSearch_draganddrop.setHandleElId("AjaxSearch_ddiv");  
	this.div.style.left = (screen.availWidth - this.div.offsetWidth) / 2;
	this.div.style.top = (screen.availHeight - this.div.offsetHeight) / 2;
	if(displayNone == true) this.div.style.display = 'none';
	this.AjaxSearchGetSettings();

	
};
