// WinSaaS (http://www.winsaas.com) and HotelASP (http://www.hotelasp.com). Licensing apply to this source code. Please read and comply with source license available at site.
// Copyright (C) 2009 by Miguel Angelo Canaria Ribeiro (miguel.ribeiro@netcabo.pt). All rights reserved.
var FTB_API;
function LookupManager(view, operationPostData) 
{
    this.view = view;     
    this.tables = new Array(); 
        
    this.lookupInProgress = false;
    this.operationPostData = operationPostData;
    this.closeLookupControlArray = new Array();
    this.cleanLookupControlArray = new Array();
    this.isLookupTableActive = new Array();    
}

function LookupTable(id, sourceId, regionID, copyData, lookupManager)
{
	this.id = id;
	this.sourceId = sourceId;
	this.regionID = regionID;
	this.copyData = copyData;	
	this.columns = null;
	this.rows = null;	
	this.html = null;	
	this.lookupManager = lookupManager;
}

function LookupTableRow(id, index, childNodes, table)
{
    this.id = id;
    this.index = index;
    this.childNodes = childNodes;	        			
	this.cells = new Array();	
	this.table = table;	
}

function LookupTableCell(id, value, text, row)
{
	this.id = id;
	this.value = value;
	this.text = text;
    this.row = row;	
    this.controlID = this.row.table.lookupManager.view.viewControlPrefix + this.row.table.regionID.toUpperCase() + "_" + id.toUpperCase();	    
}

function LookupTableColumn(id, index, type, style, css, align, text, table)
{
	this.id = id;
	this.index = index;
	this.type = type;
	this.style = style;
	this.css = css;
	this.align = align;
	this.text = text;	
	this.table = table;
}

LookupManager.prototype.Lookup2 = function (sourceObjectID)
{
    var ctrID = sourceObjectID.substring(0, sourceObjectID.length - 1);
    var ctrl = document.getElementById(ctrID);
    if (ctrl!=null)
    {
	    if (this.isLookupTableActive[ctrID]==null)
	    {
	        this.isLookupTableActive[ctrID] = ctrID;
            var call = ctrl.attributes["onkeyup"].value;
            call = call.replace("this.id,true", "'" + ctrl.id + "',false");
            call = call.replace(",event)", ",null)");
            eval(call);
        }
        else
        {
		    delete this.isLookupTableActive[ctrID]; 
            this.CloseLookupControl(ctrID);
        }
    }
}

LookupManager.prototype.Lookup = function (sourceObjectID, filter, threshold, formData, copyData, imageUpUrl, imageDownUrl, regionID, evt)
{
	evt = (evt) ? evt : ((window.event) ? window.event : null);
	var charCode = 0;
	if (evt!=null)
	{
	    charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
	}
	
	var sourceObject = document.getElementById(sourceObjectID);
 	if (((sourceObject.value.length >= threshold) && (!this.lookupInProgress) && ((charCode >= 48) || (charCode==8))) || !filter)
	{
		var callBackData = sourceObject.id + ";" + encodeURIComponent(copyData) + ";" + regionID + ";" + imageUpUrl + ";" + imageDownUrl;
		var callBack =
		{
			success: this.LookupResponse,
			failure: this.LookupResponseException,
			argument: callBackData,
			scope: this
		}
				
		var data = this.view.GetFormData("", false, true, true);			
		data = decodeURIComponent(this.operationPostData) + "&" + decodeURIComponent(formData) + "&" + data;
		
		var image = document.getElementById(sourceObjectID + "_");
		if (image!=null)
		{
		    image.src = imageDownUrl;
		}
		var callBackObject = YAHOO.util.Connect.asyncRequest('POST', _$ServiceServerURL, callBack, data);
		
		this.lookupInProgress = true;
		sourceObject.onblur = this.CloseLookupControlEvent.bind(this);
	}
}

LookupManager.prototype.LookupResponse = function (response)
{
	var tld = response.tld;
	var status = response.status;
	var statusText = response.statusText;
	var allResponseHeaders = response.allResponseHeaders;
	var responseText = response.responseText;
	var responseXML = response.responseXML;
	if (responseText!=null)
	{
		window.status = "Transferred " + responseText.length + " Bytes";
	}
	
	try
	{
		var callBackData = response.argument.split(";");
		var sourceObjectID = callBackData[0];
		var copyData = decodeURIComponent(callBackData[1]);
	    var regionID = callBackData[2];
	    var imageUpUrl = callBackData[3];
	    var imageDownUrl = callBackData[4];
	    
		this.CreateLookup(sourceObjectID, regionID, copyData, responseText);
		
	}
	catch (e)
	{
		alert ("Error in Processing Lookup. " + e.message);
	}
	
	var image = document.getElementById(sourceObjectID + "_");
    if (image!=null)
    {
        image.src = imageUpUrl;
    }
        
	this.lookupInProgress = false;	
}

LookupManager.prototype.CreateLookup = function (sourceObjectID, regionID, copyData, xmlData) 
{
	var tableID = sourceObjectID + "_lkp";
    var elem = document.getElementById(tableID);
    if (!elem) 
    {    
        elem = document.createElement("div");
        elem.id = tableID;
        elem.className = "XW_DIV";
        elem.style.position = "absolute";
        elem.style.visibility = "visible";
        elem.style.zIndex = 100;
        document.body.insertBefore(elem, document.body.firstChild);
    }
    YAHOO.util.Dom.setStyle(elem.id, "opacity", 1);
    
    var table = this.CreateTable(tableID, sourceObjectID, regionID, copyData ,xmlData);    
    elem.innerHTML = table.html;
       
    var obj = document.getElementById(sourceObjectID);
    if (obj!=null)
    {
		var xy = YAHOO.util.Dom.getXY(obj);
		xy[0] += 2;
		xy[1] += 15;
		YAHOO.util.Dom.setXY(elem, xy);
		if (isIE) // only for ie and because of dropdowns
		{
			var elem2 = document.getElementById(tableID + "_iframe");
			if (!elem2) 
			{            
				elem2 = document.createElement("iframe");
				elem2.id = tableID + "_iframe";
				elem2.style.position = "absolute";
				elem2.style.visibility = "visible";
				elem2.src = "about:blank";
				elem2.frameBorder = "0";
				elem2.scrolling = "no";
				document.body.insertBefore(elem2, document.body.firstChild);
			}
			elem2.style.width = elem.offsetWidth;
			elem2.style.height = elem.offsetHeight;
			YAHOO.util.Dom.setStyle(elem2.id, "opacity", 1);
			YAHOO.util.Dom.setXY(elem2, xy); 
		}
	}
}

LookupManager.prototype.CreateTable = function (tableID, sourceObjectID, regionID, copyData, xmlData)  
{    	    
    var docRoot = GetXmlDom(xmlData);    	
	var tag = docRoot.documentElement.selectNodes("HasExceptions")[0];	
	var hasExceptions = tag.firstChild.nodeValue.toLowerCase();

	tag = docRoot.documentElement.selectNodes("XmlDataRowsCount")[0];	
	var rowsCount = parseInt(tag.firstChild.nodeValue);
	
	var html = "";
	
	if (this.tables[tableID]!=null)
	{
		delete this.tables[tableID]; 
	}
				
	this.tables[tableID] = new LookupTable(tableID, sourceObjectID, regionID, copyData, this);
	
	if ((hasExceptions=="true") || (rowsCount == 0))
	{ 
	    var message = docRoot.documentElement.selectNodes("Message")[0];
		html = "<TABLE class='XW_TABLE'><TR class='XDV_GR'><TD align=left>" + message.firstChild.nodeValue + "</TD></TR></TABLE>";
	    this.tables[tableID].html = html;	
	    return this.tables[tableID];
	}
	
	var tableColumns =  new Array();	
	var tableRows = new Array();
	
	html = "<TABLE id=" + tableID + " class='XW_TABLE' cellspacing=1 cellpadding=2 >";	
	html += "<TR onclick='" + this.view.selfID + ".lookupManager.CloseLookupControl(\"" + sourceObjectID + "\")'>";
	var data = docRoot.documentElement.selectNodes("XmlData")[0];	
	var docData = GetXmlDom(data.firstChild.nodeValue);
	var lookupData = docData.documentElement.selectNodes("Lookup/Column");	
	for(var i = 0; i < lookupData.length; i++)
	{
		var headerColumn = lookupData[i];
		var id = headerColumn.getAttribute("ID");
		var type = headerColumn.getAttribute("Type");		
		var style = headerColumn.getAttribute("Style");
		var css = headerColumn.getAttribute("Css");
		var align = headerColumn.getAttribute("Align");
		var text = headerColumn.getAttribute("Text");		
		if (text!="")
		{
			html += "<TD class='XDV_LKH' nowrap>" + text + "</TD>";
		}
		else
		{
			html += "<TD class='XDV_LKH' nowrap>" + id + "</TD>";
		}
		
		tableColumns[tableColumns.length] = new LookupTableColumn(id, i, type, style, css, align, text, this.tables[tableID]);
	}
	html += "</TR>";
	
    this.tables[tableID].columns = tableColumns;
		
    var list = docData.documentElement.selectNodes("/ServiceData/RowData/*");    
	if (list==null) return "no data";	
	for(var i = 0; i < list.length; i++)
	{
		var row = list[i];
		if (row!=null)
		{
			var rowId = tableID + "_r_" + (i+1);			
			var tableRow = new LookupTableRow(rowId, i, row.childNodes, this.tables[tableID]);			
			html += tableRow.GetHtml(sourceObjectID);			
			tableRows[tableRows.length] = tableRow;
		}
	}
	html += "</TABLE>";

	this.tables[tableID].rows = tableRows;			
	this.tables[tableID].html = html;
	return this.tables[tableID];	
}

LookupTableRow.prototype.GetHtml = function(sourceObjectID) 
{
	var cellsScript = "";
	for(var i = 0; i < this.table.columns.length; i++)
	{
		var cellId = this.table.columns[i].id;
		var cellType = this.table.columns[i].type;
		var cellStyle = this.table.columns[i].style;
		var cellCss = this.table.columns[i].css;
		var cellAlign = this.table.columns[i].align;
		
		var cellValue = this.GetCellValueById(this.childNodes, cellId, cellType);
		if (cellValue!="")
		{
			cellText = cellValue;
		}
		else
		{
			cellText = "&nbsp;";
		}
		
		this.cells[this.cells.length] = new LookupTableCell(cellId, cellValue, cellText, this);
		    
		cellsScript += "<TD nowrap";
		if ((cellCss!="") && (cellCss!=null))
		{
		    cellsScript += " class='" + cellCss + "'" ;
		}
		
		if ((cellStyle!="")  && (cellStyle!=null))
		{
		    cellsScript += " style='" + cellStyle + "'" ;
		}
		else
		{
		    cellsScript += " style='WIDTH:60px'" ;
		}
		
		if ((cellAlign!="") && (cellAlign!=null))
		{
		    cellsScript += " align='" + cellAlign + "'" ;
		}
		else
		{
		    cellsScript += " align=right" ;
		}
				
		cellsScript += " >";
		cellsScript += cellText;
		cellsScript += "</TD>";
	}

	var html = "<TR id=" + this.id + " class=\"XDV_LKR\" style=\"HEIGHT: 20px\" onmouseover=\"this.className='XDV_LKRS'\"";
	html = html + " onmouseout=\"this.className='XDV_LKR'\" onclick=\"";
	html = html + this.table.lookupManager.view.selfID + ".lookupManager.LookupTableClick(this,'";
	html = html + this.table.id + "','" + this.index + "', event)\"";

	html = html + " onDblClick=\"";
	html = html + this.table.lookupManager.view.selfID + ".lookupManager.LookupTableDblClick('";
	html = html + sourceObjectID + "')\">";

	html = html + cellsScript + "</TR>";

	return html;
}

LookupTableRow.prototype.GetCellValueById = function(cells, id, cellType) 
{
	var result = "";
	for(var i = 0; i < cells.length; i++)
	{
		var cell = cells.item(i);
		var cellId = cell.nodeName;
		if (cellId == id)
		{
			var aux = cell.firstChild;
			if (aux!=null)
			{
				result = aux.nodeValue;
				switch(cellType)
				{
					case "shortdate":
					case "longdate":
						result = result.substring(0, 10);
						break;
					default:
						break;
				}
			}
			break;
		}
	}
	return result;
}

LookupTableRow.prototype.GetCellByControlID = function(controlID) 
{
	var result = null;
	for(var i = 0; i < this.cells.length; i++)
	{
		var cell = this.cells[i];
		if (cell.controlID == controlID)
		{
			result = cell;
			break;
		}
	}
	return result;
}

LookupManager.prototype.LookupTableClick = function(source, tableID, rowIndex, evt) 
{
	var table = this.tables[tableID];
	if (table!=null)
	{
		var copyDataArray = decodeURIComponent(table.copyData).split(";");
		var row = table.rows[rowIndex];
		for(var i = 0; i < copyDataArray.length; i++)
		{
			var aux = copyDataArray[i].split("#");
			
			var from = this.view.controlID + "_" + aux[0].toUpperCase();
			var to = this.view.controlID + "_" + aux[1].toUpperCase();
			
			var cell = row.GetCellByControlID(from);
			if (cell!=null)
			{
	            var target = document.getElementById(to);
	            if (target!=null)
	            {
		            target.value = cell.value;
	            }
			}
		}
	}
}

LookupManager.prototype.LookupTableDblClick = function(sourceObjectID) 
{
    this.CloseLookupControl(sourceObjectID);
}

LookupManager.prototype.LookupResponseException = function (response)
{
	var tld = response.tld;
	var status = response.status;
	var statusText = response.statusText;
	var allResponseHeaders = response.allResponseHeaders;
	var responseText = response.responseText;
	var responseXML = response.responseXML;
	
	var callBackData = response.argument.split(";");
	var sourceObjectID = callBackData[0];
	var copyData = decodeURIComponent(callBackData[1]);
    var regionID = callBackData[2];
    var imageUpUrl = callBackData[3];
    var imageDownUrl = callBackData[4];
	    
    var image = document.getElementById(sourceObjectID + "_");
    if (image!=null)
    {
        image.src = imageUpUrl;
    }
        
	this.lookupInProgress = false;
	
	ShowHTML("LookupResponseException", responseText);
}


LookupManager.prototype.CloseLookupControlEvent = function (evt) 
{
	evt = (evt) ? evt : ((window.event) ? window.event : null);
	var target = (evt.target) ? evt.target : evt.srcElement;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
	this.CloseLookupControl(target.id);
}

LookupManager.prototype.CloseLookupControl = function (targetId) 
{
	try
	{
		if (this.lookupInProgress)
		{
			if (this.closeLookupControlArray[targetId]==null) 
			{
				this.closeLookupControlArray[targetId] = window.setInterval((this.view.selfID + ".lookupManager.CloseLookupControl('" + targetId + "')"), 250);
			}
		}
		else
		{
			if (this.closeLookupControlArray[targetId]!=null) 
			{
				window.clearInterval(this.closeLookupControlArray[targetId]);
				delete this.closeLookupControlArray[targetId];
			}
			var tableID = targetId + "_lkp";
			var div = document.getElementById(tableID);
			if (div!=null) 
			{
				if (this.cleanLookupControlArray[targetId]==null) 
				{
					this.cleanLookupControlArray[targetId] = window.setInterval((this.view.selfID + ".lookupManager.CleanLookupControl('" + targetId + "')"), 500);
					YAHOO.util.Dom.setStyle(div.id, "opacity", .5);
					if (isIE) // only for ie
					{
						var iframe = document.getElementById(tableID + "_iframe");
						if (iframe!=null) 
						{
							YAHOO.util.Dom.setStyle(iframe.id, "opacity", .5);
						}
					}
				}
			}
		}
    }
    catch(e)
    {
		alert("CloseLookupControl:" + e.message);
    }
}

LookupManager.prototype.CleanLookupControl = function (targetId) 
{
	if (this.cleanLookupControlArray[targetId]!=null) 
	{
		window.clearInterval(this.cleanLookupControlArray[targetId]);
		delete this.cleanLookupControlArray[targetId];
	}
	var tableID = targetId + "_lkp";
	var div = document.getElementById(tableID);
	if (div!=null) 
	{
		div.innerHTML = "";
	}
	
	if (isIE)
	{
		RemoveElement(tableID + "_iframe");
	}
}