function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document;if(d.images){if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){d.MM_p[j]=new Image;d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;if(!d) d=document;if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n];for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;document.MM_sr=new Array;for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;if(!x.oSrc) x.oSrc=x.src;x.src=a[i+2];}
}

function getElementsByClassName(strTagName, strClassName)
{
	var currentElements = (strTagName == "*" && document.all)? document.all : document.getElementsByTagName(strTagName);
	var findedElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<currentElements.length; i++)
	{
	    oElement = currentElements[i];
        if(oRegExp.test(oElement.className)) {
            findedElements.push(oElement);
        }
    }

	return findedElements;
}

function focusMessagesSystem()
{
    //Qualquer alteraÃ§Ã£o no modelo de apresentaÃ§Ã£o das mensagens de retorno do framework,
    //devem ser analisadas e motidicado a classe e a tag HTML utilizada.
    var d = getElementsByClassName("span","rich-messages-label");
    for(var i=0; i<d.length; i++) {
        var element = d[i];
        var x = findPosX(element);
        var y = findPosY(element);
        if(x!=-1 && y!=-1 && x!=0 && y!=0) {
            //alert("Indice: "+ i + "\n" + "Final: "+"\n"+ "X: " + x + "\n" + "Y: " + y);
            window.scrollTo(x, y-5);
            break;
        }
    }
}

function findPosX(obj)
{
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}

function showModalPanel(id) {
    Richfaces.showModalPanel(id);
}

/**
 * Aceita somente nÃºmeros e letras
 */
function acceptNumbersAndLetters(field)
{
    field.value = field.value.replace(/[^a-zA-Z0-9]/,"");
}

function isPopupBlockerActive()
{
    var pop = window.open("#","Mercatus", "width=1, height=1, top=0, left=0, scrollbars=no, status=no, resizable=no, directories=no, location=no, menubar=no, titlebar=no, toolbar=no");
    if (pop == null && (navigator.userAgent.indexOf('Chrome') == -1) ) {
        return true;
    }

//	if(navigator.userAgent.indexOf('Chrome') != -1)
//	{

//		if(!pop || pop.closed || typeof pop.closed=='undefined' || pop.location=='about:blank')	
  //      	{
//	            return true;
  //      	}
//	}

    pop.close();

    return false;
}

/**
 * Ajusta o posicionamento dos modais do template-client-modal
 */
function adjustPositionModal(item)
{
    var widthVisibility, leftModal, eleModal;
    widthVisibility = getWidthVisibilityArea();
    eleModal = document.getElementById(item);
    
    eleModal.style.width = "648px";
    eleModal.style.height = document.getElementById(item).clientHeight;
    
    leftModal = (widthVisibility-648)/2;
    eleModal.style.left = leftModal + "px";

    if(is.IE){
        if(getDiffScroll()>0){
            eleModal.style.top = getPositionHeightScroll() + ((getHeightVisibilityArea() - getPositionHeightScroll())/2) - (eleModal.height/2) + "px";
        }

        else {
            eleModal.style.top = getHeightVisibilityArea() - (getHeightVisibilityArea()/2) + (eleModal.height/2) + "px";
        }
    }
    else {
        if(getDiffScroll()>0){

                eleModal.style.top = getPositionHeightScroll() + ((getHeightVisibilityArea() - getPositionHeightScroll())/2) - (eleModal.height/2) + "px";
        }
        else {
                eleModal.style.top = getHeightVisibilityArea() - (getHeightVisibilityArea()/2) + (eleModal.height/2) + "px";
        }
    }
    if(is.NS || is.IE){
    	document.documentElement.scrollTop = 0;
    }else {
    	 document.body.scrollTop = 0;
    }    
}
/**
 * Ajusta o posicionamento dos modais internos (modais de confirmaÃ§Ã£o)
 */
function adjustPositionInternModal(item)
{

    var widthVisibility, leftModal, eleModal;
    widthVisibility = getWidthVisibilityArea();
    eleModal = document.getElementById(item);
    eleModal.width = "326px";
    if(is.NS3_6)
	    eleModal.style.width = "326px";
    
    leftModal = (widthVisibility-326)/2;
    eleModal.style.left = leftModal + "px";
    if(is.IE) {
        if(getDiffScroll()>0) {
            eleModal.style.top = (getPositionHeightScroll()+10) + "px";
        } else {
            eleModal.style.top = "10px";
        }
    } else {
        if(getDiffScroll()>0) {
            eleModal.style.top = (getPositionHeightScroll()+10) + "px";
        } else {
            eleModal.style.top = "10px";
        }
    }
}

/**
 * 
 *  Ajustar somente a posiÃ§Ã£o da modal, sem definar width fixo 
 */
function adjustPositionInternModal2(item)
{

    var  eleModal;
    eleModal = document.getElementById(item);

    if(is.IE) {
        if(getDiffScroll()>0) {
            eleModal.style.top = (getPositionHeightScroll()+10) + "px";
        } else {
            eleModal.style.top = "10px";
        }
    }else {
        if(getDiffScroll()>0) {
            eleModal.style.top = (getPositionHeightScroll()+10) + "px";
        }else {
            eleModal.style.top = "10px";
        }
    }
}

/**
 * Retorna a Ã¡rea visÃ­vel da horizontal
 */
function getWidthVisibilityArea() {
    return parseInt(getVisibilityArea("width"));
}

/**
 * Retorna a Ã¡rea visivel de acordo com o type
 * @type pode ser width ou height
 */
function getVisibilityArea(type)
{
    var myWidth = 0;
    var myHeight = 0;

    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;

        if(is.NS)// firefox area visivel + diferenÃ§a do scroll "window.scrollMaxX"
        {
            myWidth = myWidth + window.scrollMaxX;
        }

    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;

    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    if(type == 'width') {
        return myWidth;
    }

    if(type == 'height') {
        return myHeight;
    }

    return null;
}

/**
 * Retorna a diferenÃ§a entre a altura total da pÃ¡gina e a posiÃ§Ã£o do scroll
 */
function getDiffScroll() {
    var diff, heightBody, scroll;
	heightBody = document.body.clientHeight;
	if(is.IE) {
		heightBody = getPageHeight();
        scroll = document.documentElement.clientHeight;
        if(heightBody <= scroll)
            diff = 0;
        else
            diff = heightBody - scroll;
	}
	else {
        heightBody = getPageHeight();
        scroll = window.innerHeight;
        if(heightBody <= scroll)
            diff = 0;
        else
            diff = heightBody - scroll;
	} 
    return diff;
}

/**
 * Retorna a altura total da pÃ¡gina (incluindo o scroll)
 */
function getPageHeight(){
    var yScroll;
    var pageHeight;
    if (window.innerHeight && window.scrollMaxY) {
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        yScroll = document.body.offsetHeight;
    }
    var windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }
    return pageHeight;
}

/**
 * Retorna a posiÃ§Ã£o do scroll vertical do navegador
 */
function getPositionHeightScroll() {
    //var hscroll = (document.all ? document.scrollLeft : window.pageXOffset); // pega a posiÃ§Ã£o da scroll horizontal no FF
    var positionHeightScroll;
    
    if(is.IE) {
        positionHeightScroll = document.documentElement.scrollTop; // pega a posiÃ§Ã£o da scroll vertical no IE
    } else {
        positionHeightScroll = (document.all ? document.scrollTop : window.pageYOffset); // pega a posiÃ§Ã£o da scroll vertical no FF
    } 

    return positionHeightScroll;
}

function BrowserCheck() {
    var b = navigator.userAgent;
    if (b.indexOf('Firefox')>0) this.b = "NS";
    else if (b.indexOf('MSIE')>0) this.b = "IE";
    else if (b == "Chrome") this.b = "CH";
    else this.b = b;
    this.v = parseInt(navigator.appVersion);
    this.NS = (this.b == "NS" && this.v>=4);
    this.NS4 = (this.b == "NS" && this.v == 4);
    this.NS5 = (this.b == "NS" && this.v == 5);
    this.IE = (this.b == "IE" && this.v>=4);
    this.IE7 = (navigator.userAgent.indexOf('MSIE 7')>0);
    this.IE8 = (navigator.userAgent.indexOf('MSIE 8')>0);
    this.IE9 = (navigator.userAgent.indexOf('MSIE 9')>0);
    this.NS6 = (navigator.userAgent.indexOf('Firefox/6')>0);
    this.NS7 = (navigator.userAgent.indexOf('Firefox/7')>0);
    this.NS8 = (navigator.userAgent.indexOf('Firefox/8')>0);
    this.NS9 = (navigator.userAgent.indexOf('Firefox/9')>0);
    this.CH12 =(navigator.userAgent.indexOf('Chrome/12')> -1);
    this.CH13 =(navigator.userAgent.indexOf('Chrome/13')> -1);
    this.CH14 =(navigator.userAgent.indexOf('Chrome/14')> -1);
    this.CH15 =(navigator.userAgent.indexOf('Chrome/15')> -1);
    this.CH16 =(navigator.userAgent.indexOf('Chrome/16')> -1);

    if (this.IE5 || this.NS5) this.VER5 = true;
    if (this.IE4 || this.NS4) this.VER4 = true;
    this.OLD = (! this.VER5 && ! this.VER4) ? true : false;
    this.min = (this.NS||this.IE);
}
var is = new BrowserCheck();

function pageLoad() {
    // Adiciona a funÃ§Ã£o no evento onfocus() de todos os input type text
    gwaHTMLEventManager.addEventByTag("input", "text", "focus", "setFocus(this);");

    // Adiciona a funÃ§Ã£o no evento onblur() de todos os input type text
    gwaHTMLEventManager.addEventByTag("input", "text", "blur", "setBlur(this);");

    // Adiciona a funÃ§Ã£o no evento onfocus() de todos os input type password
    gwaHTMLEventManager.addEventByTag("input", "password", "focus", "setFocus(this);");

    // Adiciona a funÃ§Ã£o no evento onblur() de todos os input type password
    gwaHTMLEventManager.addEventByTag("input", "password", "blur", "setBlur(this);");

    // Adiciona a funÃ§Ã£o no evento onblur() de todos os textArea
    gwaHTMLEventManager.addEventByTag("textarea", "textarea", "focus", "setFocus(this);");

    // Adiciona a funÃ§Ã£o no evento onblur() de todos os textArea
    gwaHTMLEventManager.addEventByTag("textarea", "textarea", "blur", "setBlur(this);");


    // Encaminha para uma pÃ¡gina de erro quando o browser nÃ£o for suportado
    if(!is.IE7 && !is.IE8 && !is.IE9 && !is.NS6 && !is.NS7 && !is.NS8 && !is.NS9 && !is.CH12 && !is.CH13 && !is.CH14 && !is.CH15 && !is.CH16) {
        if(location.href.indexOf("error_browserNotSupported")==-1 && typeof(requestContextPath) != "undefined")
            location.href = requestContextPath + "/resources/errors/error_browserNotSupported.jsf";
    }
}

function setFocus(element) {
	element.className = element.className + " sdg_inputFocus";
}

function setBlur(element) {
    var className = element.className;
    var index = className.indexOf(" sdg_inputFocus");
    element.className = className.substring(0, index);
}

function removeModalPanelTopFixedForIE6(obj) {
    // Se for IE6
    if(jQuery.browser.msie && jQuery.browser.version < 7) {
        var id = obj.id.substring(0, obj.id.indexOf("Container"));
        jQuery(obj).find("#" + id + "CDiv")[0].style.removeExpression("top");  
    }
}

function setInstitutionFocus() {
    elem = document.getElementById('rootForm:legalEntitySendMailInput');
    var timeout = 100;
    if(elem==null) {
        elem = document.getElementById('rootModal1:includePanel1:legalEntitySendMailInput');
    }
    if(elem!=null) {
        if(is.IE6) {
            timeout = 1000;
        } else if(is.IE7) {
            timeout = 900;
        }
        setTimeout('elem.focus();', timeout);
    }
}

function setResponsibleFocus() {
    elem = document.getElementById('rootForm:responsibleUserSendMailInput');
    var timeout = 100;
    if(elem==null) {
        elem = document.getElementById('rootModal1:includePanel1:responsibleUserSendMailInput');
    }
    if(elem!=null) {
        if(is.IE6) {
            timeout = 1000;
        } else if(is.IE7) {
            timeout = 900;
        }
        setTimeout('elem.focus();', timeout);
    }
}

 function ignoreDupResponses4Link(objectFather, contentTemp, styleClass)
 {
        if(objectFather)
        {
            objectFather.className = styleClass;
            objectFather.innerHTML = contentTemp;
        }
 }


function setScrollTopPosition()
{
    scroll(0, 0);
}

function onClickIncludeSymbolPecentual(object) {        
    object.value = "";
}

function onBlurIncludeSymbolPecentual(object) {
    var discountValue = new String(object.value);
    if (discountValue.indexOf("%") == -1)
        discountValue = discountValue + "%";
    object.value = discountValue;
}

/**
 * Cancela a tecla enter quando Ã© prencionada e o objeto esta com foco
 */
function cancelEnterkey(evt){
    
    var key_code = evt.keyCode  ? evt.keyCode  :
                       evt.charCode ? evt.charCode :
                       evt.which    ? evt.which    : void 0;
    if (key_code == 13)
    {
        return false;
    }
    return true;
}

var showMessagesBlock = false;

function setShowMessagesBlock(value) {
    showMessagesBlock = value;
}

function forceOnChange(elementId) {
	document.getElementById(elementId).onchange();
	return true;
}
function setCaretPositionToEnd(elem) {
	if(elem != null){
		elem.focus();
		if(elem.value && elem.value.length){
			setCaretPosition(elem,elem.value.length);
		}
	}
}
function setCaretPosition(elem, caretPos) {
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart >= 0) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
