/**********************************************/
/* Author     : Fabiano Tsuneo Maurer Ozahata */
/* Description: Generic Functions             */
/**********************************************/

/* Browse detect */
var isBrowserIE7 = (document.all && !window.opera && window.XMLHttpRequest);
var isBrowserIE = (navigator.appName == "Microsoft Internet Explorer");
var isBrowserNS = (navigator.appName == "Netscape")

var oDivMessage = null;
var top = 0;
var left = 0;
var width = 100;
var height = 30;

var POS4_TOP = 0, POS4_LEFT = 1, POS4_WIDTH = 2, POS4_HEIGHT = 3;
var POS2_WIDTH = 0, POS2_HEIGHT = 1;
var POS2_TOP = 0, POS2_LEFT = 1;
var oDivIcon = null;
var oDivIconSetTimeOut = null;

/**
 * Descricao : Inicializa as variaveis
 * Data : 2007/07/25
 */
 function initVariable()
 {
	top = (typeof(window.innerHeight) == 'number')?window.innerHeight:document.body.clientHeight;
	left = (typeof(window.innerWidth) == 'number')?window.innerWidth:document.body.clientWidth;
 }

/**
 * Descricao : Mostra um gif que informa que esta processando a informacao
 * Autor : Fabiano Tsuneo Maurer Ozahata
 * Data : 2007/03/24
 */
function waitImage(image, milliseconds)
{
	windowSize = getWindowSize();
	
	if (milliseconds == null || milliseconds == "")
		milliseconds = 60000;

	/* Cria uma tag div e coloca o texto */
	if (oDivIcon == null)
	{
		oDivIcon = document.createElement("div");
		oDivIcon.innerHTML = '<img src="' + image + '" style="z-index:10000" />';
		
		/* Adiciona o objeto na pagina */
		document.body.appendChild(oDivIcon);
	}
	oDivSize = getDivSize(oDivIcon.firstChild);
	oDivIconSty = getObjSty(oDivIcon);
	if (isNS4)
	{
		oDivIcon.position = "absolute";
		oDivIcon.top = Math.round((windowSize[POS2_HEIGHT]/2) - (oDivSize[POS4_HEIGHT]/2)) + 'px';
		oDivIcon.left = Math.round((windowSize[POS2_WIDTH]/2) - (oDivSize[POS4_WIDTH]/2)) + 'px';
	}
	if (isDOM)
	{
		oDivIconSty.position = "absolute";
		oDivIconSty.top = Math.round((windowSize[POS2_HEIGHT]/2) - (oDivSize[POS4_HEIGHT]/2)) + 'px';
		oDivIconSty.left = Math.round((windowSize[POS2_WIDTH]/2) - (oDivSize[POS4_WIDTH]/2)) + 'px';
	}
	oDivIconSty.display = '';
	oDivIconSetTimeOut = setTimeout(expiredWait, milliseconds);
}

function expiredWait()
{
	if (oDivIcon != null && getObjSty(oDivIcon).display != 'none')
	{
		alertTimeOut = "The process can't be finish, please try again.";

		if (typeof(waitTimeOutExpiredMessage) != 'undefined')
			alertTimeOut = waitTimeOutExpiredMessage;
			
		getObjSty(oDivIcon).display = 'none';
		alert(alertTimeOut);
	}
}

/**
 * Descricao : Esconde o um gif que informa que esta processando a informacao
 * Autor : Fabiano Tsuneo Maurer Ozahata
 * Data : 2007/03/24
 */
function hideWaitImage()
{
	clearTimeout(oDivIconSetTimeOut);
	if (oDivIcon != null)
		getObjSty(oDivIcon).display = 'none';
}

/**
 * Descricao : Adiciona os itens selecionados em uma tabela para outra
 * Data : 2007/10/15
 */
function addItemInList(originList, destinationList, isAllItens, isRepeatItem, disableSelect, removeElement)
{
	var selectedArray = new Array()
	var countArray = 0;
	for (var count = 0; count < originList.options.length; count++)
	{
		if (originList.options[count].selected || isAllItens == true)
		{
			selected = originList.options[count];
			newItem = document.createElement('option');
			canCopy = true;
			newItem.text=selected.text;
			newItem.value=selected.value;
			
			if (isRepeatItem == false)
				for (destCount = 0; destCount < destinationList.options.length; destCount++)
					if (newItem.value == destinationList.options[destCount].value)
						canCopy = false;
						
			if (canCopy == true)
			{
				try
				{
					destinationList.add(newItem, null); // standards compliant
				}
				catch (exception)
				{
					destinationList.add(newItem); // IE Only
				}
			}
			originList.options[count].selected = !(disableSelect==true);
			selectedArray[countArray++] = count;
		}
	}
	if (removeElement==true)
	{
		for (var regCount = (countArray-1); regCount >= 0; regCount--)
			originList.remove(selectedArray[regCount]);
	}
}

/**
 * Descricao : Deleta os itens selecionados de uma tabela
 * Data : 2007/10/15
 */
function delItemInList(list, removeAllItens, insertInThisForm)
{
	if (typeof(insertInThisForm) != 'undefined')
	{
		for (var regCount = (list.options.length-1); regCount >= 0; regCount--)
		{
			if (list.options[regCount].selected || removeAllItens)
			{
				try
				{
					insertInThisForm.add(list.options[regCount], null); // standards compliant
				}
				catch (exception)
				{
					insertInThisForm.add(list.options[regCount]); // IE Only
				}
			}
		}
	}
	
	if (removeAllItens)
	{
		while (list.options.length > 0)
			list.remove(0);
	}
	else
	{
		while (list.selectedIndex > -1)
			list.remove(list.selectedIndex);
	}
}

/**
 * Descricao : Faz o submit da tabela, selecionando todos os valores para que ele possa postar o que estiver no combobox
 * Data : 2007/10/22
 */
function submitFormAllList(formName, selectName)
{
	for (var count = 0; count < selectName.options.length; count++)
		selectName.options[count].selected = true;
	formName.submit();
}

/**
 * Descricao : Seta o browser para redirecionar se o tempo se esgotar
 * Data : 2007/11/13
 */
function setOnTimeOut(url, minutes)
{
	// Tira 10 segundos, caso haja um lag na com o servidor.
	setTimeout(url, (minutes * 60000)-10000);
}

/**
 * Descricao : Remove os caracteres de acordo com a posicao e o caracter
 *             0 - Esquerda / 1 - Direita
 * Data : 2008/01/07
 */
function removeCaracter(text, side, character)
{
	if (character == null || character.length > 1 || character.length <=0 || text == null || side < 0 || side > 1)
		return;
		
	count = (side == 0) ? 1 : -1;
	pos = (side == 0) ? 0 : (text.length-1);
	
	while (true)
	{	
		if (text.charAt(pos) != character || pos < 0 || pos > text.length)
			break;
		pos+=count;
	}
	
	return (side == 0) ? text.substr(pos) : text.substr(pos+1, text.length-pos);
}


/**
 * Descricao : Insere dentro de um select os options (Por causa do Bug do IE)
 * Data : 2008/05/26
 */
function putOptionsInSelect(objSelect, sOptions)
{
	var re = new RegExp("(\<select(.*?)\>)(.*?)(\<\/select\>)", "i");

	objSelect.innerHTML = sOptions;

	if(objSelect.outerHTML)
		objSelect.outerHTML = objSelect.outerHTML.replace(re, "$1" + sOptions + "$4");
}

/**
 * Descricao : Retorna em um array a posicao superior e da esquerda [top, left] de um objeto
 * Data : 2008/02/21
 */
function getObjSize(object)
{
	var oNode = object;

	var top = 0;
	var left = 0;

	while (oNode != null)
	{
		left += oNode.offsetLeft;
		top += oNode.offsetTop;
		oNode = oNode.offsetParent;
	}

	return [top, left, object.offsetWidth, object.offsetHeight];
}

/**
 * Descricao : Verifica se o objeto esta escondido (Pressupondo que se o pai estiver escundido ele tambem esta)
 * Data : 2008/03/10
 */
function isHidden(object)
{
	var oNode = object;

	while (oNode != null && oNode.tagName != null && oNode.tagName != "BODY" && oNode.tagName != "HTML")
	{
		oNode = oNode.offsetParent;

		if (getObjSty(oNode).display == 'none') 
			return true;
	}
	
	return false;
}

/**
 * Descricao : Retorna a posicao do mouse
 * Data : 2008/02/29
 */
function getMousePos(eventMouse)
{
	var x = (isNS4 ? eventMouse.pageX : eventMouse.clientX);
	var y = (isNS4 ? eventMouse.pageY : eventMouse.clientY);
	
	return [x, y];
}

function converPtToPx(value)
{
	value = eval(value.replace('pt', ''));
	
	return value > 0 ? value/72 : value;
}

/**
 * Descricao : Retorna a posicao e o tamanho do div (lembrando que so sera retornado se estiver mostrando)
 * Data : 2008/02/29
 */
function getDivSize(object)
{
	objSty = getObjSty(object);

	var top = converPtToPx(objSty.top.replace('px', ''));
	var left = converPtToPx(objSty.left.replace('px', ''));
	var width = object.offsetWidth;
	var height = object.offsetHeight;

	if (top == '') top = 0;
	if (left == '') left = 0;
	

	return [eval(top), eval(left), eval(width), eval(height)];
}

function getRefInside(object, id)
{
	if (object == null) return;
	if (isDOM) return object.getElementById(id);
	if (isIE4) return object.all[id];
	if (isNS4) return object.layers[id];
}

function getObjSty(object)
{
	return (isNS4 ? object : object.style);
}

function getFrameObj(id)
{
	if (isIE4) return document.frames[id].document || document.frames[id].contentWindow.document;
	if (isDOM || isNS4) return window.frames[id].document;
}

/**
 * Descricao : Retorna em um array a posicao superior e da esquerda [top, left] da janela
 * Data : 2008/02/21
 */
function getWindowSize()
{
	var height = (typeof(window.innerHeight) == 'number')?window.innerHeight:document.body.clientHeight;
	var width = (typeof(window.innerWidth) == 'number')?window.innerWidth:document.body.clientWidth;

	return [width, height];
}

/**
 * Descricao : Retorna o objeto pelo idexador dele (sourceIndex)
 * Data : 2008/03/04
 */
function getRefByIndex(sourceIndex)
{
	// Now work/test in IE
	return document.all[sourceIndex];
}

/**
 * Descricao : Adiciona o texto e duplicar se quiser
 * Data : 2008/03/07
 */
function addComplementInText(originalText, addText, duplicate)
{
	duplicate = ((typeof duplicate != 'undefined') && duplicate == true);

	if (originalText == null || addText == null || (typeof originalText == 'undefined') || (typeof addText == 'undefined'))
		return '';

	if ((originalText == null || typeof originalText == 'undefined') && (addText != null && typeof addText != 'undefined'))
		return addText;

	if ((addText == null || typeof addText == 'undefined') && (originalText != null && typeof originalText != 'undefined'))
		return originalText;

	if (originalText.indexOf(addText) < 0 || duplicate)
		return originalText + addText;
	
	return originalText;
}

function removeExternalBracket(text)
{
	return text.substr(text.indexOf('{')+1, text.lastIndexOf('}') - text.indexOf('{') - 1);
}

/**
 * Descricao : Adiciona scripts dentro de um evento, podendo duplicar caso queira
 * Data : 2008/03/07
 */
function addComplementInEvent(eventObject, textOrFunction, duplicate)
{
	if (textOrFunction == null || typeof textOrFunction == 'undefined')
		return eventObject;

	textToInsert = (typeof textOrFunction == 'undefined') ? '' : textOrFunction.toString();

	if (typeof textOrFunction == 'function')
		textToInsert = removeExternalBracket(textToInsert);

	complement = (eventObject == null || typeof eventObject == 'undefined') ? '' : (typeof eventObject == 'function') ? removeExternalBracket(eventObject.toString()) : eventObject.toString();

	sResult = addComplementInText(complement, textToInsert, duplicate);

	return new Function(sResult);
}

/**
 * Descricao : Retorna o evento
 * Data : 2008/06/06
 */
function getEvent()
{
      return window.event ? window.event : event;
}

/**
 * Descricao : Retorna a chave passada
 * Data : 2008/06/06
 */
function getEventKeyCode(e)
{
	if (e == null)
		e = getEvent();
	
	return e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
}

/**
 * Descricao : Retorna o alvo
 * Data : 2008/06/06
 */
function getEventTarget(e)
{
	if (e == null)
		e = getEvent();
	
	return e.target || e.srcElement;
}

/**
 * Descricao : Verify if the characters was basic
 * Data : 2009/01/05
 */
function inASCIIRange(oText)
{
	for (var i=0; i<oText.length; i++)
		if (oText.charCodeAt(i)<256)
			return true;
	return false;
}

/**
 * Descricao : As you know the getElementById is new method in modern browsers. Long time ago old browsers did not 
 *             support this cool method. So this function was invented for accessing DOM objects in all browsers.
 * Site : javascript-array.com
 * Data : 2008/01/23
 */
var dom = (document.getElementById) ? true : false; 
var ns5 = ((navigator.userAgent.indexOf("Gecko")>-1) && dom) ? true: false; 
var ie5 = ((navigator.userAgent.indexOf("MSIE")>-1) && dom) ? true : false; 
var ns4 = (document.layers && !dom) ? true : false; 
var ie4 = (document.all && !dom) ? true : false; 

function getObj(id) 
{ 
	if (dom)
		return document.getElementById(id);
	return (ns4) ? document.layers[id] : (ie4) ? document.all[id] : (ie5||ns5) ? document.getElementById(id) : null; 
}

/**
 * Site : http://www.twinhelix.com (Angus Turnbull)
 * Data : 2008/01/31
 */
var isDOM = (document.getElementById ? true : false);
var isIE4 = ((document.all && !isDOM) ? true : false);
var isNS4 = (document.layers ? true : false);

function getRef(id)
{
	if (isDOM) return document.getElementById(id);
	if (isIE4) return document.all[id];
	if (isNS4) return document.layers[id];
}

function getSty(id)
{
	return (isNS4 ? getRef(id) : getRef(id).style);
}

/**
 * Site : http://www.thewatchmakerproject.com (Matthew Pennell)
 * Data : 2008/02/07
 */
function addLoadEvent(func)
{
	if (window.addEventListener)
		window.addEventListener("load", func, false);
	else
		if (document.addEventListener)
			document.addEventListener("load", func, false);
		else
			if (window.attachEvent)
				window.attachEvent("onload", func);
			else
				if (document.attachEvent)
					document.attachEvent("onload", func);
}

function addGenericEvent(source, trigger, func)
{
	if (source.addEventListener)
		source.addEventListener(trigger, func, false);
	else
		if (source.attachEvent)
			source.attachEvent("on" + trigger, func);
}






/********************************************************************************/
/* DEPRECATED DEPRECATED DEPRECATED DEPRECATED DEPRECATED DEPRECATED DEPRECATED */
/********************************************************************************/

/**
 * Descricao : Script que cria a mensagem
 * Data : 2007/03/24
 */
function showMessage(mensagem, ptop, pleft, estilo, pwidth, pheight)
{
	waitImage('/GenericFiles/Images/Buttons/intranet-load.gif');
}

/**
 * Descricao : Esconde a tela que cria a mensagem
 * Data : 2007/03/24
 */
function hideMessage()
{
	hideWaitImage();
}

