var xmlUtil = new XMLUtil();
var bd = new BrowserDetection();
var http;
var winRet = /\r\n$/;
var unxRet = /\n$/;
//var domainRe = /http:\/\/(.+?)\//;
//var domain = domainRe.exec(document.location)[1];
var currentRow = -1;
var resultArray = new Array();
var currentTerm = null;
var key;
var obj_text;

function handleKeyPress(e, obj, tipo)
{
	// Objecto
	obj_text = $(obj);
	obj_text.onblur = function() {
		var tdiv = $("suggestion");
		tdiv.style.visibility = "hidden";
	}
		
	// IE
	if(window.event)
	{
		key = e.keyCode;
	}
	// Moz
	else
	{
		key = e.which;
	}
	
	// Scrolling
	if ((key == 38 || key == 40) && resultArray.length > 0)
	{					
		if (key == 38)
		{
			if (currentRow != 0)
			{
				inRow(currentRow - 1);
			}
		}
		else
		{
			if (currentRow != (resultArray.length - 1))
			{
				inRow(currentRow + 1);
			}					
		}
		return;
	}
	
	if (key == 8 || (key >= 48 && key <= 90))
	{
		try {
			var searchTerm = obj_text.value;	
		} catch (e) {
			var searchTerm = document.getElementById(obj).value;
		}
		
		if ( searchTerm != "" )
		{
			obtemSugestoes( searchTerm , tipo );
		}
		else
		{
			EscondeSugestoes();
		}
	}

	if ( key == 13 ) {
		EscondeSugestoes();
	}
	
	// Escape
	if (key == 27)
	{
		close();
		return;
	}
}

function obtemSugestoes(hint, tipo)
{
    http = xmlUtil.getXMLHTTPObject();
    http.open('GET', 'ajax/sugere.aspx?tipo='+tipo+'&texto='+escape(hint), false);
    http.send(null);
    processaSugestoes();
}

function processaSugestoes()
{
	if (http.readyState == xmlUtil.COMPLETE && http.status == 200)
    {
    	var res = http.responseText;
    	resultArray = new Array();
    	
   		if (res.search(winRet) != -1)
   		{
       		res = res.substring(0, res.length - 2);
   		}
   		else if (res.search(unxRet) != -1)
   		{
   			res = res.substring(0, res.length - 1);	
   		}
   		
   		
		var html = new String();
    	if (res.length > 0)
    	{
			resultArray = res.split('\n');
			html += '<div id="suggestion_table">';
			for (var i = 0; i < resultArray.length; ++i)
			{
				html += '<div class="suggestion_row" id="row_'+i+'" onMouseOver="inRow('+i+')" >'+resultArray[i]+'</div>';
			}
			html += '</div>';
			
			mostraResultados(html);
			inRow(0);
    	}
    }
}

function mostraResultados(val)
{
	replaceHTML('suggestion', val);
	try {
		_obj = $("suggestion");
		_obj.style.left = findPosX(obj_text) + 2;
		_obj.style.top = findPosY(obj_text) + 5;
		_obj.style.visibility = "visible";
	} catch(e) {
		alert("erro");
	}
}

function close()
{
	replaceHTML('suggestion', '');	
}

function changeRowColor(id, fgColor, bgColor)
{
	document.getElementById('row_'+id).style.backgroundColor = bgColor;
}

function inRow(id)
{
	if (currentRow != -1)
	{
		changeRowColor(currentRow, 'green', '#fff');
	}
	currentRow = id;
	currentTerm = resultArray[currentRow];
	changeRowColor(currentRow, '#fff', '#90ACC8');
	if (key != 8)
	{
		autoComplete();
	}
}

function autoComplete()
{
	if (bd.isSafari)
	{
		return;	
	}
	
	try {
		var textInput = obj_text;	
	} catch (e) {
		var textInput = document.getElementById(obj_text);
	}
				
	var startVal = textInput.value;
	textInput.value = currentTerm;


	if (!bd.isIE)
	{
		textInput.setSelectionRange(startVal.length, currentTerm.length);
	}
	else
	{
		var range = textInput.createTextRange();
        range.moveStart("character", startVal.length);
        range.moveEnd("character", currentTerm.length);
        range.select();	
	}
}


function EscondeSugestoes() {
	_obj = $("suggestion");
	_obj.style.visibility = "hidden";
}

// DIV offset's
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			if ( obj.id != "" ) 	
				curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft - 48;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop + 5;
}

function sss_limitaTamanho( obj, maxT, maxA ) {

	oldT = obj.width;
	oldA = obj.height;

	if ( obj.width > maxT ) {
		obj.width = maxT;
		obj.height = parseInt ( ( maxT * oldA ) / oldT );

		oldT = obj.width;
		oldA = obj.height;
	}

	if ( obj.height > maxA ) {
		obj.height = maxA;
		obj.width = parseInt ( ( maxA * oldT ) / oldA );
	}
}

// XML
function XMLUtil()
{
    this.UNINITIALIZED = 0;
    this.LOADING       = 1;
    this.LOADED        = 2;
    this.INTERACTIVE   = 3;
    this.COMPLETE      = 4;
    this.isIE = (document.implementation.createDocument) ? false : true;
}

XMLUtil.prototype.getXMLHTTPObject = function()
{
    if(this.isIE)
    {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        return new XMLHttpRequest();
    }
}

XMLUtil.prototype.getDOM = function()
{
    if (this.isIE)
    {
        return new ActiveXObject("Microsoft.XMLDOM");
    }
    else
    {
        return new DOMParser();
    }
}

XMLUtil.prototype.getDOMFromString = function(xmlStr)
{
    var xmlDom = this.getDOM();
    if (this.isIE)
    {
        xmlDom.async = 'false';
        xmlDom.loadXML(xmlStr);
        return xmlDom;
    }
    else
    {
        return xmlDom.parseFromString(xmlStr, 'text/xml');
    }
}

XMLUtil.prototype.getText = function(elem)
{
    if (this.isIE)
    {
        return elem.text;
    }
    else
    {
        return elem.textContent;
    }
}


// BROWSER DETECTION
function BrowserDetection()
{
	var isIE, isMozilla, isSafari, isOpera = false;
	if (navigator.userAgent.indexOf('MSIE') != -1)
		this.isIE = true;
	else if (navigator.userAgent.indexOf('Safari') != -1)
		this.isSafari = true;
	else if (navigator.userAgent.indexOf('Opera') != -1)
		this.isOpera = true;
	else
		this.isMozilla = true;
}

