
var alt;
var popup;


var elements = new Array();

function resetElements() {
  elements = new Array();
}
function getById(id) {
  if (elements[id] == null){
    elements[id] = document.getElementById(id);
  }
  return elements[id];
}

function abrepopup(pagina,opcoes,largura,altura) {
  window.open(pagina,'popup',opcoes+',width='+largura+',height='+altura+',top=130,left=120');
}



function getResolutionCookie() {
  return getCookieValue("screenResolution");
}

function setResolutionCookie(res) {
  setCookieValue("screenResolution", res);
}

function getDimension(resolution) {
	var opWidth = 0;
	var opHeight = 0;
	if (resolution == "2") {
		opWidth = 1110;
		opHeight = 895;
	} else if (resolution == "1") {
		opWidth = 1000;
		opHeight = 654;
	} else {
		resolution = "0";
		opWidth = 793;
		opHeight = 533;
	}
	return [resolution, opWidth, opHeight];
}



function openOperations() {
	var resolution = getResolutionCookie();
	var dim = getDimension(resolution);
	resolution = dim[0];
	var opWidth = dim[1];
	var opHeight = dim[2];
	setResolutionCookie(resolution);
	var url = 'opOperations.do?resolution=' + resolution;
	popup = window.open(url,'Operations','width=' + opWidth + 'px,height=' + opHeight + 'px,left=0,top=0,status=no');
}

function changeRes(resolution, pop, baseURL) {
	var oldRes = getResolutionCookie();
	var oldDim = getDimension(oldRes);

	var oldWidth = parseInt(oldDim[1]);
	var oldHeight = parseInt(oldDim[2]);

	setResolutionCookie(resolution);
	var dim = getDimension(resolution);
	resolution = dim[0];
	var opWidth = dim[1];
	var opHeight = dim[2];
	opHeight = parseInt(opHeight);
	opWidth = parseInt(opWidth);

	cH = pop.document.body.clientHeight;
	var left = pop.screenLeft;
	var top = pop.screenTop;
	pop.moveTo(0,0);
	pop.resizeBy(opWidth - oldWidth, opHeight - oldHeight);
	pop.moveTo(left,top);
	cH = pop.document.body.clientHeight - 4;

	pop.location = baseURL + 'opOperations.do?resolution=' + resolution;
}

function openAlert(){
 alt = window.open('alert.jsp','alert','width=300px,height=100px,left=300,top=300');
 alt.focus();
}
function openHelp(){
 help = window.open('./sheet/help.html','help','width=500px,height=400px,left=300,top=300');
 help.focus();

}
function openToolsBolsaNet(account){
  var param = "http://www.solidez.com.br/autentica.asp?id="+account;
  window.open(param,'tools','width=795px,height=600px,left=50,top=50');
}

function openOperationsLogin() {
	popup = window.open('','Operations','width=0px,height=0px,left=3600,top=3600');
	popup.blur();
	window.focus();

	return popup;
}

function closeOperations(){
  if(openOperationsLogin() != null){
   openOperationsLogin()
   openOperationsLogin().close();
     return true;
  }
  return false;
}
/*function 02 */
function openOperationsPortfolio(quoteName,type,qte,cv){
  //servlet encarregado de salvar configurações da planilha
	var saveTabs = {
			//t1:1
			url:baseURL+ "servlet/saveTabServlet",
			data:{t1:1,t4:quoteName,t5:cv},
			success:function(data){			
				param = "?type="+type+"&QtyTotal="+qte;				  
			//	  param = "?quoteName="+quoteName+"&type="+type+"&QtyTotal="+qte+"&cv="+cv;
	
				  var resolution = getResolutionCookie();
				  var dim = getDimension(resolution);
				  	  resolution = dim[0];
				  var opWidth    = dim[1];
				  var opHeight   = dim[2];
				  setResolutionCookie(resolution);
				  var url = baseURL + '/opOperations.do'+param+'&resolution=' + resolution;	 
				    popup = window.open(url,'Operations','width=' + opWidth + 'px,height=' + opHeight + 'px,left=50,top=50');
				    popup.focus();

			}
	};
  
	//jQuery
  	jQuery.ajax(saveTabs);

}

function openChart(ativo, market,typeserver) {

  html =                    "<h1>";
  html +=                    "  <APPLET id=\"CedroFullChartApplet\" name=\"CedroFullChartApplet\" archive=\"CedroFullChartApplet.jar\" CODE=\"br.com.cedro.visual.CedroChartsApplet\" WIDTH=\"110\" HEIGHT=\"26\" codebase=\".\" MAYSCRIPT=\"TRUE\">";
  html +=                        "<param name=\"cache_option\" value=\"Plugin\">";
  html +=                        "<param name=\"cache_archive\" value=\"CedroFullChartApplet.jar\">";
  html +=                        "<param name=\"quote\" value=\""+ativo+"\">";
  html +=                        "<param name=\"market\" value=\""+market+"\">";
  html +=                        "<param name=\"type\" value=\"candle\">";
  html +=                        " <param name=\"typeServer\" value=\""+typeserver+"\">";
  html +=                      "</APPLET>";
  html +=                    "</h1>";

  if (document.layers) {
    document.layers['chart'].innerHTML=html;
  }
  else{
  document.getElementById('chart').innerHTML=html;
  }

}

documentall = document.all;

/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function demaskvalue(valor, currency){
  /*
  * Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as
  * casas decimais
  */
  var val2 = '';
  var strCheck = '0123456789';
  var len = valor.length;
  if (len== 0){
          return 0.00;
  }

  if (currency ==true){
    /* Elimina os zeros à esquerda
    * a variável  <i> passa a ser a localização do primeiro caractere após os zeros e
    * val2 contém os caracteres (descontando os zeros à esquerda)
    */

    for(var i = 0; i < len; i++)
      if ((valor.charAt(i) != '0') && (valor.charAt(i) != ','))
        break;

    for(; i < len; i++){
      if (strCheck.indexOf(valor.charAt(i)) != -1)
        val2+= valor.charAt(i);
    }

    if(val2.length==0) return "0.00";
    if (val2.length==1)return "0.0" + val2;
    if (val2.length==2)return "0." + val2;

    var parte1 = val2.substring(0,val2.length-2);
    var parte2 = val2.substring(val2.length-2);
    var returnvalue = parte1 + "." + parte2;
    return returnvalue;
  }else{
    /* currency é false: retornamos os valores COM os zeros à esquerda,
    * sem considerar os últimos 2 algarismos como casas decimais
    */
    val3 ="";
    for(var k=0; k < len; k++){
            if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
    }
    return val3;
  }
}

function reais(obj,event){
    var whichCode = (window.Event) ? event.which : event.keyCode;
    /*
    Executa a formatação após o backspace nos navegadores !document.all
    */
    if (whichCode == 8 && !documentall) {
        /*
        Previne a ação padrão nos navegadores
        */
        if (event.preventDefault){ //standart browsers
            event.preventDefault();
        }else{ // internet explorer
            event.returnValue = false;
        }
        var valor = obj.value;
        var x = valor.substring(0,valor.length-1);
        obj.value= demaskvalue(x,true).formatCurrency();
        return false;
    }
    /*
    Executa o Formata Reais e faz o format currency novamente após o backspace
    */
    FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

  var whichCode = (window.Event) ? event.which : event.keyCode;
  if (whichCode == 8 && documentall) {
          var valor = obj.value;
          var x = valor.substring(0,valor.length-1);
          var y = demaskvalue(x,true).formatCurrency();

          obj.value =""; //necessário para o opera
          obj.value += y;

          if (event.preventDefault){ //standart browsers
                          event.preventDefault();
                  }else{ // internet explorer
                          event.returnValue = false;
          }
          return false;

  }// end if
}// end backspace



function FormataReais(fld, milSep, decSep, e) {
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;

  //if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
  if (whichCode == 0 ) return true;
  if (whichCode == 9 ) return true; //tecla tab
  if (whichCode == 13) return true; //tecla enter
  if (whichCode == 16) return true; //shift internet explorer
  if (whichCode == 17) return true; //control no internet explorer
  if (whichCode == 27 ) return true; //tecla esc
  if (whichCode == 34 ) return true; //tecla end
  if (whichCode == 35 ) return true;//tecla end
  if (whichCode == 36 ) return true; //tecla home

  /*
  O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
  */

    if (e.preventDefault){ //standart browsers
      e.preventDefault()
    }else{ // internet explorer
      e.returnValue = false
    }

  var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
  if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

  /*
  Concatenamos ao value o keycode de key, se esse for um número
  */
  fld.value += key;

  var len = fld.value.length;

  var bodeaux = demaskvalue(fld.value,true).formatCurrency();

  fld.value=bodeaux;

  /*
  Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
  */
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}


function checkAll(field1, field2) {
  if (field1 != null && field2 != null) {
    var len = field2.length;
    // trata quando o field2 for apenas 1
    if (len == undefined) {
      field2.checked = field1.checked;
    }
    // field2 é mais de 1
    else {
      for (i = 0; i < len; i++) {
        field2[i].checked = field1.checked;
      }
    }
  }

  return true;
}

function verifyCheckAll(field1, field2) {
  var checkeds = 0;
  var uncheckeds = 0;
  var len = field2.length;
  // trata quando o field2 for apenas 1
  if (len == undefined) {
    field1.checked = field2.checked;
  }
  // field2 é mais de 1
  else {
    for (i = 0; i < len; i++) {
      if (field2[i].checked == true) {
        checkeds++;
      }
      else {
        uncheckeds++;
      }
    }
    if (checkeds == len) {
      field1.checked = true;
    }
    if (uncheckeds > 0) {
      field1.checked = false;
    }
  }
  return true;
}


function selAllCheck(alCheckName, checksNames) {
  if(document.getElementById(alCheckName).checked == true) {
    var i = 0;
    while(document.getElementById(checksNames+i) != null) {
      document.getElementById(checksNames+i).checked = true;
      i++;
    }
  }
  else {
    var i = 0;
    while(document.getElementById(checksNames+i) != null) {
      document.getElementById(checksNames+i).checked = false;
      i++;
    }
  }
}

function verifyCheckBox(alCheckName, checksNames) {
  var checked = true;
  var i = 0;
  while(document.getElementById(checksNames+i) != null && checked) {
    checked = checked && document.getElementById(checksNames+i).checked;
    i++;
  }
  document.getElementById(alCheckName).checked = checked;
}

function show(id){
  document.getElementById(id).style.visibility = "visible";
  document.getElementById(id).style.display = "block";
}

function hide(id){
  document.getElementById(id).style.visibility = "hidden";
  document.getElementById(id).style.display = "none";
}

function hideShow(hideId, showId) {
  hide(hideId);
  show(showId);
}

function formatCpf(cpf) {
  cpf = new String(cpf);
  cpf = cpf.substring(0, 3) + "." + cpf.substring(3, 6) + "." +
        cpf.substring(6, 9) + "-" + cpf.substring(9, 11);

  return cpf;
}

function openJavaHelp() {
  window.open('../javaHelp.do', 'help','width=639px,height=747px,resizable=yes,location=no,scrollbars=no');
}

function openJavaHelpLogin() {
  window.open('javaHelp.do', 'help','width=639px,height=747px,resizable=yes,location=no,scrollbars=no');
}

function showPopupHelp(idDivPopup) {
  if(document.getElementById(idDivPopup).style.visibility == "hidden") {
    document.getElementById(idDivPopup).style.visibility = "";
  } else {
    document.getElementById(idDivPopup).style.visibility = "hidden"
  }
}

function validatePass(event) {
  var whichCode = (window.Event) ? event.which : event.keyCode;
   if(whichCode == 8 || whichCode == 0)
     return true;

   key = String.fromCharCode(whichCode);
   if(key == "&" || key == "'" || key == "\"")
     return false;
   return true;
}

function kmgFormat(qtd){
  var format = qtd.charAt(qtd.length - 1);
  qtd = parseFloat(qtd);
  switch (format) {
    case "G":
      qtd = qtd*1000000000;
      break;
    case "M":
      qtd = qtd*1000000;
      break;
    case "K":
      qtd = qtd*1000;
      break;
    default:
      qtd = qtd*1;
  }
  return qtd;
}

function kmgFormatConvert(qtd){
  var qte = Math.abs(qtd);
  var value;
  if(qte >= 1000000000){
    value = (parseFloat(qtd,10)/1000000000) + "G";
  }else if(qte >= 1000000){
    value = (parseFloat(qtd,10)/1000000) + "M";
  }else if(qte >= 1000){
    value = (parseFloat(qtd,10)/1000) + "K";
  }else{
    value = qtd;
  }
  return value;
}

function setOption(select, option_pos) {
  select.options[option_pos].selected = true;
}

function currencyFormatted(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00;}
	var minus = '';
        i = Math.abs(i);
	if(i < 0) { minus = '-'; }
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;

        str = new String(s);
        str = str.replace(/\./g, ",");
        pos = str.lastIndexOf(",");
        for(var i = (pos - 3); i > 0; i = i-3) {
          strAux = new String(str.substring(0, i) + ".");
          str = strAux.concat(str.substring(i, str.length));
        }
	return str;
}

String.prototype.formatCurrency=formatamoney

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

function trimAll(sString)
{
    while (sString.substring(0,1) == ' ')
    {
      sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
      sString = sString.substring(0,sString.length-1);
    }
  return sString;
}

function trim(inString){
  outString = "";
  for(i = 0; i < inString.length; i++){
    if(inString.charAt(i) != ' '){
        outString += inString.charAt(i);
    }
  }
  return outString;
}

String.prototype.Trim = function() {
  return this.replace(/^\s+|\s+$/, '');
};

function isEmpty(sString)
{
  var empty = true;
  var i = 0;
  for(i = 0; i < sString.length; i++){
    if(sString.charAt(i)!=" "){
      empty = false;
      break;
    }
  }
  return empty;
}

function restrictDays(begin,end,nroDays){
	control = new controlDate();
	d1 = control.converDate("-", begin);
	d2 = control.converDate("-", end);
	Ddias = control.subDates(d1, d2);
	checkDay = control.todayCheck(d2);

	try {
		if (Ddias < 0) {
			alert(" Data inicial está maior que a data final ");
			return false;

		} else if (checkDay.valueOf()) {
			alert(" Data é maior que data atual ( " + control.today() + " )");
			return false;

		} else if (Ddias > nroDays) {
			alert(" Periodo de Busca esta restrito a " + nroDays + " dias");
			return false;
		}

	} catch (e) {
		alert(e);
	}

	return true;
}

function getObject( obj ) {
  if ( document.getElementById ) {
    obj = document.getElementById( obj );
  }
  else if ( document.all ) {
          obj = document.all.item( obj );
        }
        else {
          obj = null;
        }
  return obj;
}

function setCookieValue(name, value) {
	var now = new Date();
	// fix the bug in Navigator 2.0, Macintosh
	fixDate(now);

	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookieExpires(name, value, now);
}

function setCookieExpires(name, value, expires, path, domain, secure) {
	var cookiePos = findCookiePosition(name);
	/*alert(cookiePos[0]);
	if (cookiePos[0] == -1)
  	return;
 	var dc = document.cookie;
 	var cook = dc.substring(0, cookiePos[0]);
 	cook += dc.substring(cookiePos[1]+2, dc.length);*/

  /*var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");*/

  var curCookie = name + "=" + escape(value) + ";";
  document.cookie = curCookie;
}

function findCookiePosition(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return [-1, -1];
  } else
    begin += 2;

  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return [begin, end]
}

function getCookieValue(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  /*var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));*/
  var cookiePos = findCookiePosition(name);
  if (cookiePos[0] == -1)
  	return null;
  return unescape(dc.substring(cookiePos[0] + prefix.length, cookiePos[1]));
}

function deleteCookie(name, path, domain) {
  if (getCookieValue(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

function openNews(code) {
  var url = "opViewNewsPortal.do?popup=yes&c=" + code;
  window.open(url, 'news','left=400,top=200,width=750,height=300,menubar=1,resizable=1,location=no,scrollbars=yes');
}
function openPortal(code) {
  var url = "opViewNewsPortal.do?c=OTc5OTk0" + code;
  window.open(url, 'news','left=400,top=200,width=750,height=300,menubar=1,resizable=1,location=no,scrollbars=yes');
}
/*
function openChart(ativo, market,typeserver)
{

//html =                    "<h1>";
html =                    "  <APPLET id=\"CedroFullChartApplet\" name=\"CedroFullChartApplet\" archive=\"CedroFullChartApplet.jar\" CODE=\"br.com.cedro.visual.CedroChartsApplet\" WIDTH=\"110\" HEIGHT=\"23\" align=\"middle\" codebase=\".\" MAYSCRIPT=\"TRUE\">";
html +=                        "<param name=\"cache_option\" value=\"Plugin\">";
html +=                        "<param name=\"cache_archive\" value=\"CedroFullChartApplet.jar\">";
html +=                        "<param name=\"quote\" value=\""+ativo+"\">";
html +=                        "<param name=\"market\" value=\""+market+"\">";
html +=                        "<param name=\"type\" value=\"candle\">";
html +=                        " <param name=\"typeServer\" value=\""+typeserver+"\">";
html +=                      "</APPLET>";
//html +=                    "</h1>";

  if (document.layers) {
    document.layers['chart'].innerHTML=html;
  }
  else{
  document.getElementById('chart').innerHTML=html;
  }

}
*/
function StringBuffer() {

   this.buffer = [];

   append = function append(string) {
      this.buffer.push(string);
      return this;
   };

   toString = function toString() {
    return this.buffer.join("");
   };
}
function findPositionnew(oElement) {
  if( typeof( oElement.offsetParent ) != 'undefined' ) {
    for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
      posX += oElement.offsetLeft;
      posY += oElement.offsetTop;
    }
    //alert(posX);
    //alert(posY);
    return [posX,posY];
  } else {
    //alert(oElement.x);
    //alert(oElement.y);
    return [ oElement.x, oElement.y ];
  }
}
function findPositionX(obj){
    var curleft = 0;
    //alert("entrei x");
    if(obj.offsetParent){
    	//alert("teste")
        while(1){
        	//alert(obj.offsetLeft);
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;


        }
    }else if(obj.x){
        curleft += obj.x;
    }
    //alert("ns "+obj.x);
    //alert(curleft);
    return curleft;
  }
function findPositionY(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 getLeft(This){
      var el = This;var pL = 0;
      while(el){pL+=el.offsetLeft;el=el.offsetParent;}
      return pL;
}

function getTop(This){
      var el = This;var pL = 0;
      while(el){pL+=el.offsetTop;el=el.offsetParent;}
      return pL;
}
// getAnchorPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
	// This function will return an Object with x and y properties
	var useWindow=false;
	var coordinates=new Object();
	var x=0,y=0;
	// Browser capability sniffing
	var use_gebi=false, use_css=false, use_layers=false;
	if (document.getElementById) { use_gebi=true; }
	else if (document.all) { use_css=true; }
	else if (document.layers) { use_layers=true; }
	// Logic to find position
 	if (use_gebi && document.all) {
		x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
		}
	else if (use_gebi) {
		var o=document.getElementById(anchorname);
		x=AnchorPosition_getPageOffsetLeft(o);
		y=AnchorPosition_getPageOffsetTop(o);
		}
 	else if (use_css) {
		x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
		}
	else if (use_layers) {
		var found=0;
		for (var i=0; i<document.anchors.length; i++) {
			if (document.anchors[i].name==anchorname) { found=1; break; }
			}
		if (found==0) {
			coordinates.x=0; coordinates.y=0; return coordinates;
			}
		x=document.anchors[i].x;
		y=document.anchors[i].y;
		}
	else {
		coordinates.x=0; coordinates.y=0; return coordinates;
		}
	coordinates.x=x;
	coordinates.y=y;
	return coordinates;
	}
// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
	var ol=el.offsetLeft;
	while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
	return ol;
	}
function AnchorPosition_getWindowOffsetLeft (el) {
	return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
	}
function AnchorPosition_getPageOffsetTop (el) {
	var ot=el.offsetTop;
	while((el=el.offsetParent) != null) { ot += el.offsetTop; }
	return ot;
	}
function AnchorPosition_getWindowOffsetTop (el) {
	return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
	}


function getAnchorWindowPosition(anchorname) {
	var coordinates=getAnchorPosition(anchorname);
	var x=0;
	var y=0;
	if (document.getElementById) {
		if (isNaN(window.screenX)) {
			x=coordinates.x-document.body.scrollLeft+window.screenLeft;
			y=coordinates.y-document.body.scrollTop+window.screenTop;
			}
		else {
			x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
			y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
			}
		}
	else if (document.all) {
		x=coordinates.x-document.body.scrollLeft+window.screenLeft;
		y=coordinates.y-document.body.scrollTop+window.screenTop;
		}
	else if (document.layers) {
		x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
		y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
		}
	coordinates.x=x;
	coordinates.y=y;
	return coordinates;
	}

function getElementAbsPosX(el)
{
    var dx = 0;
    if (el.offsetParent) {
        dx = el.offsetLeft + 8;
        while (el = el.offsetParent) {
            dx += el.offsetLeft;
        }
    }
    return dx;
}

function getElementAbsPosY(el)
{
    var dy = 0;
    if (el.offsetParent) {
        dy = el.offsetTop + el.offsetHeight / 2;
        while (el = el.offsetParent) {
            dy += el.offsetTop;
        }
    }
    return dy;
}

function restrictdate(data,begin,end,nroDays){

	control = new controlDate();
	selectD = control.converDate("-",data);

	d1 = control.converDate("-", begin);
	d2 = control.converDate("-", end);
	checkDate = control.todayCheck(selectD);
	
	Ddias = control.subDates(d1, d2);
	checkDay = control.todayCheck(d2);
	
	try {
		if(checkDate.valueOf()){
			alert(" Data é maior que data atual ( " + control.today() + " )");
			return false;
		}				
		else if (Ddias < 0) {
			alert(" Data inicial está maior que a data final ");
			return false;

		} else if (checkDay.valueOf()) {
			alert(" Data é maior que data atual  ( " + control.today() + " )");
			return false;

		} else if (Ddias > nroDays) {
			alert(" Periodo de Busca esta restrito a " + nroDays + " dias");
			return false;
		}

	} catch (e) {
		alert(e);
	}finally{
		control = null;
	}

	return true;
}

/**
 *@author Renato.dias
 */
function controlDate()
{
	this.data = new Date();
	this.dia  = this.data.getDate();      //dia atual
	this.mes  = this.data.getMonth();     //mes atual
	this.ano  = this.data.getFullYear();  //ano atual

	/**
	 * @param  delimitador  / ou - 
	 * @param  data ####-##-## para ##-##-####
	 */
	
	this.converDate = function(delimitador,data){
		 limit = delimitador  
		 return data.substr(8,2)+limit+data.substr(5,2)+limit+data.substr(0,4);			
	}

	/**
	 * Subtrai datas ,retorna o numero de dias 
	 * @param  data1  data inicial  
	 * @param  data2  data final
	 * @return Integer 
	 */
	
	this.subDates  = function(data1,data2){		    
		 subd1 = new Date(data1.substr(6,4), data1.substr(3,2)-1, data1.substr(0,2));
         subd2 = new Date(data2.substr(6,4), data2.substr(3,2)-1, data2.substr(0,2));
		return Math.ceil((subd2.getTime() - subd1.getTime())/1000/60/60/24);
	}
	/**
	 * checa diferença de data em um determinado periodo 
	 * @return boolean
	 */
	this.restrictDays = function(dataini,datafim,Ndias){
			if(this.subDates(dataini,datafim)>Ndias){
				return false;
			}
			return true;	
	}
	/**
	 * checa se a data atual é menor que a data setada 
	 * @param data1
	 */
	
	this.todayCheck = function(data1){
		    todayd1 = new Date(data1.substr(6,4), data1.substr(3,2)-1, data1.substr(0,2));
			
			todayd1 = Math.ceil((todayd1.getTime())/1000/60/60/24);
			todayd2 = Math.ceil((this.data.getTime())/1000/60/60/24);
				
			if(todayd1 > todayd2){
				return true;
			}
		  return false;	  
	}
	/**
	 * data atual 
	 */
	this.today = function(){
		
		if(this.mes <= 9){
			mes = "0" + (this.mes + 1);
		}else{
			mes = this.mes;
		}
		if(this.dia <=9){
			dia = "0" + this.dia;
		}else{
			dia = this.dia;
		}
		
		t = new String(dia+'/'+ mes +'/'+this.ano);
		return t;
	}
	
}

/***fim classe data **/
