var interval;
var d1=0;
var d2=0;

http = getHTTPObject();
 
function getHTTPObject(){
  var xmlhttp;
 
  /*@cc_on
 
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
      try{
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }catch(E){
      xmlhttp = false;
    }
  }
  @else
    xmlhttp = false;
  @end @*/
 
  if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
    try {
      xmlhttp = new XMLHttpRequest();
    }catch(e){
      xmlhttp = false;
    }
  }
 
  return xmlhttp;
}

	
	var scrollInt;
	var scrTime, scrSt, scrDist, scrDur, scrInt;
	
	

	/*
	SCROLL FUNCTIONS
	*/
	
	function scrollPage()
	{
		scrTime += scrInt;
		if (scrTime < scrDur) {
			window.scrollTo( 0, easeInOut(scrTime,scrSt,scrDist,scrDur) );
		}else{
			window.scrollTo( 0, scrSt+scrDist );
			clearInterval(scrollInt);
		}
	}
	
	function scrollToAnchor(aname)
	{

		var anchors, i, ele;
	
		if (!document.getElementById)
			return;
		
		// get anchor
		anchors = document.getElementsByTagName("a");
		for (i=0;i<anchors.length;i++) {
			if (anchors[i].name == aname) {
				ele = anchors[i];
				i = anchors.length;
			}
		}
		
		// set scroll target
		if (window.scrollY)
			scrSt = window.scrollY;
		else if (document.documentElement.scrollTop)
			scrSt = document.documentElement.scrollTop;
		else
			scrSt = document.body.scrollTop;

		
		
		scrDist = ele.offsetTop - scrSt;
		scrDur = 500;
		scrTime = 0;
		scrInt = 10;
		
		// set interval
		clearInterval(scrollInt);
		scrollInt = setInterval( scrollPage, scrInt );
	}
	
	
	
	
	/*
	EASING FUNCTIONS
	*/
	
	function easeInOut(t,b,c,d)
	{
		return c/2 * (1 - Math.cos(Math.PI*t/d)) + b;
	}
	
	


var divID;
function loadPage(loadPageIndex,loadPageRunning,page,querystring,divIDTmp,scroll){
	if(scroll!='no'){
		scrollToAnchor('top');
	}

	if(page){	
		var url = "/global/loadpage.backend.c?page="+page+"&"+querystring;
	}else{
		var url = "/global/loadpage.backend.c";
	}

	if(loadPageIndex!=loadPageRunning){
		location=loadPageIndex+"?loadPage=1";
	}

	//var url = "http://dev.dalmeida.com.br/global/js/"+page;
	http.open("GET", url, true);
    http.onreadystatechange = loadPagehandleHttpResponse;
	http.send(null);
	
	if(document.getElementById(divIDTmp)){
		 divID=divIDTmp;
	}else{
		 divID='loadpage';
	}
    document.getElementById(divID).innerHTML = "<br><br><br><br><br><br><br><br><br><br><br><center><div style='background-color:#FFFFFF; color:#999999; font-size:10px; font-family:arial; width:90px; padding:5px 3px 5px 0px; text-align:right;'><img src='/images/loading.gif' align='absmiddle'>&nbsp;Carregando...</div></center><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>"; 
}

function extraiScript(texto){
//Funo feita pelo SkyWalker.TO do imasters/forum
//http://forum.imasters.com.br/index.php?showtopic=165277
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            //eval(codigo);
            /**********************
            * Alterado por Micox - micoxjcg@yahoo.com.br
            * Alterei pois com o eval no executava funes.
            ***********************/
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}


function loadPagehandleHttpResponse(){
  if(http.readyState == 4){
        //document.getElementById('loadpage').innerHTML = http.responseText;
		var txt=http.responseText;
		document.getElementById(divID).innerHTML=txt;
		var htxt = txt.replace(/\'/g, "\\'").replace(/[\r\n\s]/g, " ");
		ajaxHistory.add("document.getElementById(divID).innerHTML = '"+htxt+"';");
		//alert(htxt);
		extraiScript(txt);
	}
}

//window.onload = function() { ajaxHistory.activateBrowserHistory(); };

function postForm(formName,action){
		split = formName.split(",");
		
		var formNames='';
		for (var i=0;i<split.length;i++){

			if(i>0){
				formNames=formNames+',';
			}
			
			formNames=formNames+split[i];
		}
		var query='formName='+formNames+'&';
		query=query+'action='+action+'&';

				

		//var input = document.forms[0].;
		var x=document.getElementById("frmForm");	
		
		for (var i=0;i<x.length;i++)
		{
			var value=x.elements[i].value;
			var value2=value.replace(/&/g, "_AND_");
			
			if(x.elements[i].type!='radio' && x.elements[i].type!='checkbox'){
				query=query+(x.elements[i].name)+"="+(value2+"&");
			}else{
				
				if(x.elements[i].checked){
					query=query+(x.elements[i].name)+"="+(value2+"&");
				}else{
					//query=query+(x.elements[i].name)+"=&";
				}
				
			}
		}
	
		var url = "/global/form/form.backend.c";
		http.open("POST", url, true);
		http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		http.onreadystatechange = postFormHandleHttpResponse;
		http.send(query);
}

function postFormHandleHttpResponse(){
	  if(http.readyState == 4){
		text=http.responseText;
		//alert(text);
		var query='';
		
		var x=document.getElementById("frmForm");	
		
		start=text.indexOf("startFormClass-");
		start=start+15;
		end=text.indexOf("-endFormClass");
		finalend=text.substring(start,end);
		eval(finalend);
		
		
		if(text.indexOf("startFormBackend-")>0){
			start=text.indexOf("startFormBackend-");
			start=start+17;
			end=text.indexOf("-endFormBackend");
			finalend=text.substring(start,end);
			eval(finalend);
		}			
		/*
		for (var i=0;i<x.length;i++)
		{
				 
		 
		//var query=query+(x.elements[i].name)+"="+(x.elements[i].value+"&");
		}

		alert(finalWarning);
		*/	
	  }
}

function postFormDbSelect(target,targetDb,targetTable,targetField,targetKey,targetCondition,targetValueCondition,targetClean,targetBring,targetXml){
	var url = "/global/form/formDbSelectBackend.c?target="+target+"&targetDb="+targetDb+"&targetTable="+targetTable+"&targetField="+targetField+"&targetKey="+targetKey+"&targetCondition="+targetCondition+"&targetValueCondition="+targetValueCondition+"&targetClean="+targetClean+"&targetBring="+targetBring+"&targetXml="+targetXml;
	http.open("GET", url, true);
	http.onreadystatechange=postFormDbSelectHandleHttpResponse;
	http.send(null);
}

function postFormDbSelectHandleHttpResponse(){
	if(http.readyState == 4){
		 text=http.responseText;	
		 startFormDbSelectBackend=text.indexOf("startFormDbSelectBackend-");
		 startFormDbSelectBackend=startFormDbSelectBackend+25;
		 endFormDbSelectBackend=text.indexOf("-endFormDbSelectBackend");
		 finalFormDbSelectBackend=text.substring(startFormDbSelectBackend,endFormDbSelectBackend);
		 eval(finalFormDbSelectBackend);	
		 //alert(finalFormDbSelectBackend);
		 //alert(split[1]);
		 //document.getElementById(split[0]).innerHTML=split[1];
	}
}

function postFormTargetBring(postFormTargetBring){
	var elementId='';
	split1=postFormTargetBring.split(";");
	for (var i=0;i<split1.length;i++){
		split2=split1[i].split(",");
		if(document.getElementById(split2[0])){
			document.getElementById(split2[0]).value=split2[1];	
		}
	}
}

function postFormTextSearchFill(formName,group,line,keyField,keyFieldValue){
	var url = "/global/form/postFormTextSearchFill.c?formName="+formName+"&group="+group+"&line="+line+"&keyField="+keyField+"&keyFieldValue="+keyFieldValue;
	http.open("GET", url, true);
	http.onreadystatechange=postFormTextSearchFillHandleHttpResponse;
	http.send(null);
}

function postFormTextSearchFillHandleHttpResponse(){
	if(http.readyState == 4){
		 text=http.responseText;	
		 //alert(text);
		 start=text.indexOf("startFormTextSearchFill-");
		 start=start+24;
		 end=text.indexOf("-endFormTextSearchFill");
		 finalend=text.substring(start,end);
		 eval(finalend);	
		 //alert(final);
		 //alert(split[1]);
		 //document.getElementById(split[0]).innerHTML=split[1];
	}
}

function widget(widgetSrc){
	//alert(widgetID);
	//By Annimo e Micox - http://elmicox.blogspot.com
	//document.getElementById("novidades_home").innerHTML="carregando";
	var novo = document.createElement("script");
	novo.setAttribute('type', 'text/javascript');
	novo.setAttribute('src', widgetSrc);
	document.body.appendChild(novo);
	 //document.getElementsByTagName('p')[0].appendChild(novo);
	 //apos a linha acima o navegador inicia o carregamento do arquivo
	 //portanto aguarde um pouco at o navegador baix-lo. :)
		
		//var url = "/global/widgets.c?widgetID=w001";
		//http.open("GET", url, true);
		//http.onreadystatechange = widgetHandleHttpResponse;
		//http.send(null);
}

function widgetHandleHttpResponse(){
	//if(http.readyState == 4){
		 //alert(http.responseText);	
	//}
}

function cart(itemsID,_ordersItemsQty){
	_ordersItemsQty=_ordersItemsQty.replace(/\,/g,".");
		
		
	if(_ordersItemsQty>=0){
		
		if(document.getElementById('loading')){
			document.getElementById('loading').style.display="block";
		}

		var url = "/global/cart/cartBackend.c?itemsID="+itemsID+"&_ordersItemsQty="+_ordersItemsQty;~
		http.open("GET", url, true);
		http.onreadystatechange = cartHandleHttpResponse;
		http.send(null);
		
		if(document.getElementById('adicionado_cesta')){
			document.getElementById('adicionado_cesta').style.display="block";
		}

		
		if(_ordersItemsQty==0){
			if(document.getElementById('adicionado_cesta')){
				document.getElementById('adicionado_cesta').style.display="none";
			}
		}

	}else{
		 document.getElementById('_ordersItemsQty'+itemsID).value="";
	}
}

function cartHandleHttpResponse(){
	 if(http.readyState == 4){
		 text=http.responseText;
		 //alert(text);
		
		 startMiniCart=text.indexOf("startMiniCart-");
		 startMiniCart=startMiniCart+14;
		 endMiniCart=text.indexOf("-endMiniCart");
		 finalMiniCart=text.substring(startMiniCart,endMiniCart);
	
		if(document.getElementById('miniCart')){		
			document.getElementById('miniCart').innerHTML=finalMiniCart;
		}
		
		 startCart=text.indexOf("startCart-");
		 startCart=startCart+10;
		 endCart=text.indexOf("-endCart");
		 finalCart=text.substring(startCart,endCart);

		 

		if(document.getElementById('cart')){		
			document.getElementById('cart').innerHTML=finalCart;
		}

		
		startCartParameter=text.indexOf("startParameter-");
		startCartParameter=startCartParameter+15;
		endCartParameter=text.indexOf("-endParameter");
		finalCartParameter=text.substring(startCartParameter,endCartParameter);
		split=finalCartParameter.split(";");
		var _ordersItemsQty=split[0].replace(/\./g,",");
		if(document.getElementById('_ordersItemsQty'+split[1])){
			document.getElementById('_ordersItemsQty'+split[1]).value=_ordersItemsQty;
		}
		 //cartTotal=split[1];	
	
	 // document.getElementById('cartTotalItems').innerHTML=split[0];	  
	 // document.getElementById('cartTotal').innerHTML=split[1];
	  //document.getElementById('_ordersItemsQty'+itemsID).value="";
		
		if(document.getElementById('loading')){
			document.getElementById('loading').style.display="none";
		}
	}
}


var pageUrl;
var doWhat;
var divID;
function login(whichLogin,doWhatTmp,pageUrlTpm,extra){
		var query='';
		//var input = document.forms[0].;
		var x=document.getElementById("frmLogin");	
		for (var i=0;i<x.length;i++)
		{
		var query=query+(x.elements[i].name)+"="+(x.elements[i].value+"&");
		}

		var url = "/global/login.backend.c?"+query+"&whichLogin="+whichLogin;

		pageUrl=pageUrlTpm;
		doWhat=doWhatTmp;

		http.open("GET", url, true);
		http.onreadystatechange = loginHandleHttpResponse;
		http.send(null);
}
function loginHandleHttpResponse(){
	  if(http.readyState == 4){
	   var text=http.responseText;
		   
	   if(text.indexOf("logged")>-1){
			
			
									
			if(document.getElementById('loading')){
				document.getElementById('loading').style.display="block";
			}
			
			if(doWhat=='redir'){
				location=pageUrl;
			}else if(doWhat=='return'){
				//resultLogin="logged";
			}

	   }else{

		   startWarning=text.indexOf("startWarning-");
		   startWarning=startWarning+13;
		   endWarning=text.indexOf("-endWarning");
		   //endWarning= endWarning-1;
		   finalWarning=text.substring(startWarning,endWarning);	
				
		   if(document.getElementById("warning")){
				document.getElementById("warning").innerHTML=finalWarning;	
		   }
	   }
	}
}



function search(q){
	//var query='';
	//var input = document.forms[0].;
	//var x=document.getElementById("frmSearch");	
	//for (var i=0;i<x.length;i++)
	//{
	//var query=query+(x.elements[i].name)+"="+(x.elements[i].value+"&");
	//}
	var url = "/global/search.backend.c?q=" + q;
	http.open("GET", url, true);
    http.onreadystatechange = searchHandleHttpResponse;
	http.send(null);
}

function searchHandleHttpResponse(){
  if(http.readyState == 4){
	    document.getElementById('loadpage').innerHTML = http.responseText;	
		text=http.responseText;
		//indice = text.indexOf("logged");
		//alert(text.substring(11,17));
		//location="/";
	}
}

/*

function date(value){
	//var query='';
	//var input = document.forms[0].;
	//var x=document.getElementById("frmSearch");	
	//for (var i=0;i<x.length;i++)
	//{
	//var query=query+(x.elements[i].name)+"="+(x.elements[i].value+"&");
	//}
	var url = "/global/date.backend.c?q=";
	http.open("GET", url, true);
    http.onreadystatechange = dateHandleHttpResponse;
	http.send(null);
}

function dateHandleHttpResponse(){
  if(http.readyState == 4){
	    document.getElementById('date').innerHTML = http.responseText;	
		text=http.responseText;
		//indice = text.indexOf("logged");
		//alert(text.substring(11,17));
		//location="/";
	}
}

*/


/*Timer*/


function trim(str){
	return str.replace(/^\s+|\s+$/g,"");
}

// Exemplo de utilizao:

function set_date(){
	setInterval("clockDisplay()",1000);
	//alert('setclock');
	
	//if(document.getElementById('showSchedule')){
		//3();
	//}

}

function clockDisplay(value){
	
	if(value){
		clock=trim(value);
		split = clock.split(";");
		posdate = new Array();
		posdate[0]='date_H';
		posdate[1]='date_i';
		posdate[2]='date_ss';
		posdate[3]='date_p';
		posdate[4]='date_m';
		posdate[5]='date_d';
		posdate[6]='date_Y';
		posdate[7]='date_F';
		posdate[8]='date_l';
		posdate[9]='date_S';
		posdate[10]='lang';
	}

	hor=clock.substring(0,2);
	hor2=parseFloat(hor);
	min=clock.substring(3,5);
	min2=parseFloat(min);
	seg=clock.substring(6,8);
	seg2= 1 + parseFloat(seg);
	
	
	if(seg2==60){
		seg="00";
		min2=parseFloat(min)+1;
	}else if(seg2<10){
		seg="0"+parseFloat(seg2);
	}else{
		seg=parseFloat(seg2);
	}
	
	if(min2==60){
		min="00";
		hor2=parseFloat(hor)+1;
	}else if(min2<10){
		min="0"+parseFloat(min2);
	}else{
		min=parseFloat(min2);
	}

	if(split[10]=='pt_BR'){

		if(hor2==24){
			hor="00";
		}else if(hor2<10){
			hor="0"+parseFloat(hor2);
		}else{
			hor=parseFloat(hor2);
		}
	}

	if(split[10]=='en_US'){
		if(hor2>12){
			hor=(hor2-12);
			if(hor < 10){
				hor="0"+hor;
			}

		}else if(hor2<10){
			hor="0"+parseFloat(hor2);
		}else if (hor2==0){
			hor=12;
		}else{
			hor=parseFloat(hor2);
		}
	}

	clock=hor+":"+min+":"+seg;


	for (var i=0;i<split.length;i++){
		if(document.getElementById(posdate[i])){
			document.getElementById(posdate[i]).innerHTML=split[i];	
		}
	}

	if(document.getElementById('date_clock')){
		document.getElementById('date_clock').innerHTML=clock;	
	}

	if(value){
		set_date();
	}
	
}

/*Timer*/



function schedule(nodeSchedule,day,month,year){
	if(typeof(month)!='undefined' && typeof(year)!='undefined'){
		var url = "/global/schedule.backend.c?nodeSchedule="+nodeSchedule+"&day="+day+"&month="+month+"&year="+year;
	}else{
		//var url = "/global/schedule.backend.c";
	}

	div=nodeSchedule+"Show";

	http.open("GET", url, true);
    http.onreadystatechange = scheduleHandleHttpResponse;
	http.send(null);
	document.getElementById(div).innerHTML="<table cellpadding='0' cellspacing='0' style='margin-top:5px;'><tr><td width='200'><img src='/en_US/images/topshelftransportation.calendar.top.gif'></td></tr><tr><td width='200' align='center' style='background-image:url(/en_US/images/topshelftransportation.calendar.bg.gif);' class='calendar'>	<table cellpadding='0' cellspacing='0' style='margin:6px 12px 5px 13px;'>	<tr>	<td width='172' style='font-family:arial narrow, arial; font-size:11px; color:#FFFFFF;'><img src='/en_US/images/topshelftransportation.calendar.seta.month.gif' align='absmiddle'>Loading</td>	<td width='10'>&nbsp;</td>	<td width='10'>&nbsp;</td>	</tr>	</table></td></tr><tr><td width='200'><img src='/en_US/images/topshelftransportation.calendar.bottom.gif'></td></tr></table>";
}

function scheduleHandleHttpResponse(){
	  if(http.readyState == 4){
			if(http.status==200){
				if(document.getElementById(div)){
					document.getElementById(div).innerHTML=http.responseText;
				}
			}
	 }
}

function setDateToHtml(nodeSchedule,dateMask,dateMaskDb,submit){
	
		concat=nodeSchedule+"Date";
		document.getElementById(concat).value=dateMask;

		concat2=nodeSchedule+"DateDb";
		document.getElementById(concat2).value=dateMaskDb;
		
		if(submit){
			document.getElementById("frmSchedule").submit();
		}
}



function autoComplete(){
	var url = "/global/autoComplete.backend.c?q=" + document.getElementById('autoComplete01').value;
	http.open("GET", url, true);
    http.onreadystatechange = autoCompleteHandleHttpResponse;
	http.send(null);
}

function autoCompleteHandleHttpResponse(){
  if(http.readyState == 4){
	    document.getElementById('gridAutoComplete01').innerHTML = http.responseText;	  
  }
}

function pressWait(e){
	clearInterval(interval);

	d=new Date();
	d2=d.getTime();
	result=d2-d1;
	//window.status=result;

	directionsKey=0;

	if(e){
		unicode=(e.keyCode)?e.keyCode:e.charCode;
		directionsKey=(unicode==37 || unicode==38 || unicode==39 || unicode==40)?1:0;
		//window.status=unicode;
	}

	if(!directionsKey && unicode!=13){
		if(result>=400){
			//window.status='POST NOW!';
			autoComplete();

		}else{
			interval=window.setTimeout(pressWait, 400);
		}
	}

	d1=d.getTime();
}

optBlur=0;
optFocus=0;
jsLoadPage=null;

function navWords(e, txt, codGrid){
	//txt.value=txt.value.replace(/(^\s*)|(\s*$)/g, "");
	unicode=(e.keyCode)?e.keyCode:e.charCode;

	downKey=(unicode==40)?1:0;
	enterKey=(unicode==13)?1:0;
	directionsOk=(unicode==38 || unicode==40)?1:0;
	numbersOk=(unicode>=48 && unicode>=50)?1:0;
	charsOk=(unicode>=65 && unicode>=90)?1:0;

	gridAutoComplete=document.getElementById('gridAutoComplete'+codGrid);

	if(numbersOk || charsOk || downKey){

		if(gridAutoComplete){

			l=txt.offsetLeft;
			t=txt.offsetTop;
			w=txt.offsetWidth;
			h=txt.offsetHeight;

			//window.status='L='+l+' T='+t+' W='+w+' H='+h;

			//gridAutoComplete.style.left=l;
			//gridAutoComplete.style.top=t+h;
			gridAutoComplete.style.width=w;
			//gridAutoComplete.style.height=h;

			gridAutoComplete.style.visibility="visible";
		}
	}

	if(directionsOk){
		if(optBlur){
			optionAutoComplete=document.getElementById('optionAutoComplete'+codGrid+'['+optBlur+']');
			optionAutoCompleteHout(txt, codGrid, optionAutoComplete);
		}

		if(unicode==40){
			//window.status='SELF='+optFocus+' NEW='+(optFocus+1);

			optionAutoComplete=document.getElementById('optionAutoComplete'+codGrid+'['+(optFocus+1)+']');

			if(optionAutoComplete){
				optFocus+=1;
			}

		}else if(unicode==38){
			//window.status='SELF='+optFocus+' NEW='+(optFocus-1);

			if(optFocus>0){
				optionAutoComplete=document.getElementById('optionAutoComplete'+codGrid+'['+(optFocus-1)+']');

				if(optionAutoComplete){
					optFocus-=1;

				}else{
					gridAutoCompleteReset(codGrid);
				}
			}
		}

		optionAutoComplete=document.getElementById('optionAutoComplete'+codGrid+'['+optFocus+']');
		
		if(optFocus){
			optionAutoCompleteHover(txt, codGrid, optionAutoComplete);
		}

		optBlur=optFocus;
	}

	if(enterKey){
		if(typeof(optionAutoComplete) != 'undefined'){
			optionAutoCompleteHenter(txt, codGrid, optionAutoComplete);

		}else{
			optionAutoCompleteHenter(txt, codGrid);
		}
	}

	if(txt.value=='' && !directionsOk && !downKey && !enterKey && !directionsOk && !numbersOk && !charsOk){
		gridAutoComplete.style.visibility="hidden";
		optBlur=0;
		optFocus=0;
	}
}

function gridAutoCompleteReset(codGrid){
	gridAutoComplete=document.getElementById('gridAutoComplete'+codGrid);
	gridAutoComplete.style.visibility="hidden";
	optBlur=0;
	optFocus=0;
}

hoverColorOpt='#00509F';
lastColorOpt='';

function optionAutoCompleteHover(txt, codGrid, opt, optFocusTmp){
	if(typeof(optFocusTmp)!='undefined'){
		//window.status='LAST='+optFocus+' SELF='+optFocusTmp;

		optionAutoComplete=document.getElementById('optionAutoComplete'+codGrid+'['+optFocus+']');

		if(optionAutoComplete){
			optionAutoComplete.style.backgroundColor=lastColorOpt;
		
		}
		
		optFocus=parseInt(optFocusTmp);
		optBlur=parseInt(optFocus);

	}else{
		//window.status='LAST='+optBlur+' SELF='+optFocus;
	}

	lastColorOpt=opt.style.backgroundColor;
	opt.style.backgroundColor=hoverColorOpt;

	//optionAutoCompleteSelect(txt, codGrid, opt);
}

function optionAutoCompleteHout(txt, codGrid, opt, optBlurTmp){
	opt.style.backgroundColor=lastColorOpt;
	lastColor='';
}

function optionAutoCompleteSelect(txt, codGrid, opt){	
	txt.value=opt.innerHTML;
}

function optionAutoCompleteHenter(txt, codGrid, opt){
	optBlur=0;
	optFocus=0;

	document.getElementById('gridAutoComplete'+codGrid).style.visibility='hidden';

	if(typeof(opt) != 'undefined'){
		optionAutoCompleteHout(txt, codGrid, opt);

		if(opt.firstChild.href){
			jsLoadPage = opt.firstChild.href.replace(/javascript\:/g,'');
		}
	}
}


var exts = "jpg|gif|png|bmp|mp3|mp4|mpg|mpeg|avi|rar|zip|7z|gz|txt|csv|rec|doc|pdf|mov|mid|wmv|wma|enc|cpt|psd|cdr|swf|fla|ppt|xls|html|htm|xml|eml|msg|ttf|wav";
//var exts = ".*"; //Use this to accept all Extensions

var UID,NF=0,cx=0;
function openStatusWindow()
{ 
 if(document.F1.popup.checked == true)
 {
   win1 = window.open('http://redeopen2.redeopen.com:8080/cgi-bin/upload_pt_BR/upload_status.cgi?upload_id='+UID,'win1','width=320,height=240,resizable=1');
   win1.window.focus();
 }
}

function generateSID()
{
 UID = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
 var f1=document.F1;
 f1.action = f1.action.split('?')[0]+'?upload_id='+UID;
}

function StartUpload()
{
    NF=0;
    for (var i=0;i<document.F1.length;i++)
    {
     current = document.F1.elements[i];
     if(current.type=='file' && current.value!='')
      {
         if(!checkExt(current.value))return false;
         NF++;
      }
    }
    //if(NF==0){alert('Select at least one file to upload');return false;};
   if(NF>0){
		generateSID();
		openStatusWindow();
   }
}




///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

//Funes adicionadas por andr cury 28/04/2008 - 12:17.

function ins(img){
	img_on=img;
	img_on.filters.alpha.opacity=60;
	img_on.style.cursor='hand';
}

function outs(img){
	img_off=img;
	img_off.filters.alpha.opacity=100;
}


///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////





function checkExt(value)
{
    if(value=="")return true;
    var re = new RegExp("^.+\.("+exts+")$","i");
    if(!re.test(value))
    {
        alert("Extension not allowed for file: \"" + value + "\"\nOnly these extensions are allowed: "+exts.replace(/\|/g,',')+" \n\n");
        return false;
    }
    return true;
}

/**
 * ajaxHistory - histrico de comandos para navegao por Ajax
 * -----------------------------------------------
 * autor: Cau Guanabara <caugb@ibest.com.br>
 * data: 2006-06-07 :: 2006-11-07
 * -----------------------------------------------
 * O objeto ajaxHistory permite trabalhar com o histrico do navegador
 * em pginas com sistema de navegao por ajax, onde para se mostrar um
 * contedo no h o carregamento de uma nova pgina, mas apenas a execuo de
 * um comando em javascript. Para que tudo funcione,  preciso adicionar
 * itens ao histrico manualmente, a cada comando que mude o contedo exibido,
 * com o mtodo ajaxHistory.add().
 * -----------------------------------------------
 */

/**
Propriedades
------------
ajaxHistory.items -> array - contm os itens do histrico (comandos em forma de texto)
ajaxHistory.captions -> array - contm os ttulos para os itens do histrico (opcional)
ajaxHistory.currentIndex -> inteiro - ndice do item atual no array ajaxHistory.items
ajaxHistory.activeHistory -> boleano - true se os botes de histrico foram ativados

Mtodos pblicos
----------------
ajaxHistory.activateBrowserHistory -> function - ativa os botes de histrico do navegador
                                      Deve ser executada apenas uma vez, no onload da pgina.
ajaxHistory.add -> function - adiciona um item ao histrico
  @param str - comando JS em forma de string para ser executado ao mostrar o item
  @param cap - string para ser usada como title da pgina no carregamento do item
ajaxHistory.go -> function - recebe um nmero x e avana ou retrocede x itens no histrico
  @param ref - inteiro indicando quantos itens avanar (pos.) ou retroceder (neg.) no histrico
ajaxHistory.goTo -> function - recebe um nmero x e mostra o item x do histrico
  @param ind - inteiro indicando o ndice do item do histrico a exibir
ajaxHistory.hasBack -> function - testa se h um item anterior ao atual
ajaxHistory.hasForward -> function - testa se h um item  frente do atual

Mtodos privados
----------------
ajaxHistory.makeIframe -> function - cria o iframe (IExplore)
ajaxHistory.checkHash -> function - checa se h mudanas no hash (Mozilla)
ajaxHistory.setHash -> function - aplica a mudana no hash
*/

/**
 * Para usar os botes de histrico do navegador,  preciso ter o arquivo 'historyframe.html',
 * na mesma pasta da pgina que est usando o objeto ajaxHistory (no do arquivo ajax_history.js).
 * O arquivo 'historyframe.html' ser includo na pgina, em um iframe (apenas para o IExplorer).

 historyframe.html
 -----------------
 <html><head><script type="text/javascript" language="javascript">
  function checkHistory() {
  var pi = parent.location.hash.replace(/#/,''), si = location.href.replace(/^.+\?/,'') || false;
    if(si && pi && (parent.ajaxHistory || false)) 
      if(pi != si) parent.ajaxHistory.goTo(si);
  }
  </script></head><body onLoad="checkHistory();"></body></html>
 */
var ajaxHistory = {
  'items': [],
  'captions': [],
  'currentIndex': 0,
  'go': function(ref) {
    if(this.hasKey(this.currentIndex + ref)) this.currentIndex += ref;
    else return;
  this.setHash();  
    if(this.captions[this.currentIndex]) document.title = this.captions[this.currentIndex];
  new Function(this.items[this.currentIndex])();
  },
  'goTo': function(ind) {
    if(this.hasKey(ind)) this.currentIndex = ind;
    else return;
  this.setHash();
    if(this.captions[this.currentIndex]) document.title = this.captions[this.currentIndex];
  new Function(this.items[this.currentIndex])();
  },
  'add': function(str, cap) { 
    if(str == this.items[this.currentIndex]) return false;
  this.currentIndex = this.items.length;
  this.items.push(str);
  this.captions.push(cap || false);
  this.setHash();  
  return true;
  },
  'hasKey': function(key) { return (this.items[key] || false) ? true : false; },
  'hasBack': function() { return (this.items[this.currentIndex - 1] || false) ? true : false; },
  'hasForward': function() { return (this.items[this.currentIndex + 1] || false) ? true : false; },
  'activeHistory': false,
  'activateBrowserHistory': function() {
    if(document.all) this.makeIframe();
    else setInterval("ajaxHistory.checkHash()", 100);
  this.activeHistory = true;
  },
  'makeIframe': function() {
  this.iframe = document.createElement('iframe');
  this.iframe.src = 'historyframe.html';
  this.iframe.style.display = 'none';
  document.getElementsByTagName('body')[0].appendChild(this.iframe);
  },
  'checkHash': function() {
  var curHash = location.hash.replace(/#/,'');
    if(this.currentIndex != curHash) this.goTo(curHash);
  },
  'setHash': function() {
	  if(!this.activeHistory) return;
  top.location.hash = this.currentIndex;
    if(!document.all) return;
	this.iframe.contentWindow.location.href = '/global/historyframe.html?'+this.currentIndex;
  }
};

function strim(str){
	return str.replace(/(^\s*)|(\s*$)/g,"");
}

esgotou=0;
k=0;
stop=0;
function mask(e, campo, mascara, validos){
	if(document.all){ // Internet Explorer
		ch=strim(String.fromCharCode(event.keyCode));

	}else{
		if(e.charCode == 0){
			return true;
		}

		ch=String.fromCharCode(e.charCode);		
	}

	delimitador=new Array();
	pos=new Array();
	ini=0;
	j=0;

	if(validos.indexOf(ch)==-1){
		campo.focus();
		return false;

	}else{
		if(mascara!=""){
			lencampo=campo.value.length;
			mascara=mascara.split('');
			lenmascara=mascara.length;
			
			for(i=0;i<lenmascara;i++){
				if(mascara[i]!="@"){
					if(!ini && lencampo<=i){
						campo.value=campo.value + mascara[i];

					}else{
						delimitador[j]=mascara[i];
						pos[j]=i;
						j++;
					}					

				}else{
					ini=1;
				}
			}
			
			for(i=0;i<=j-1;i++){
				posicao=pos[i]-1;	
				///alert(lencampo+"=="+posicao);
				if(lencampo==posicao){
					k=i;
				}
			}			
			
			if(lencampo==lenmascara){
				stop=1;
			}else{
				stop=0;
			}
	
			if(stop==1) return false;
				
			posicao=pos[k]-1;
			//alert(lencampo+"=="+posicao+"    k="+k);
			if(lencampo==posicao){
				campo.value=campo.value + ch + delimitador[k];
				campo.focus();
				return false;
			}else{
				return true;
			}
		}
	}
}

function chval(validos, txt){
	if(event.keyCode!="13" && event.keyCode!="27"){
		ch=String.fromCharCode(event.keyCode);
		if(validos.indexOf(ch) == -1){
			txt.focus();
			return false;
		}
	}
	return true;
}


//################################################################################################//

///////////////////////////////////////// RICH TEXT ////////////////////////////////////////////////

//################################################################################################//

// Cross-Browser Rich Text Editor
// http://www.kevinroth.com/rte/demo.htm
// Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM)
// Visit the support forums at http://www.kevinroth.com/forums/index.php?c=2

//init variables
var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;


function initRTE(imgPath, incPath, css) {
	//set browser vars
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); 
	isGecko = (ua.indexOf("gecko") != -1);
	isSafari = (ua.indexOf("safari") != -1);
	isKonqueror = (ua.indexOf("konqueror") != -1);
	
	//check to see if designMode mode is available
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}
	
	if (isIE) {
		document.onmouseover = raiseButton;
		document.onmouseout  = normalButton;
		document.onmousedown = lowerButton;
		document.onmouseup   = raiseButton;
	}
	
	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
	
	if (isRichText) document.write('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');
	
	//for testing standard textarea, uncomment the following line
	//isRichText = false;
}

function writeRichText(rte, html, width, height, buttons, readOnly) {
	if (isRichText) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;
		
		if (readOnly) buttons = false;
		
		//adjust minimum table widths
		if (isIE) {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width;
		} else {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width + 4;
		}
		
		document.write('<div class="rteDiv">');
		if (buttons == true) {
			document.write('<table class="rteBack" cellpadding=2 cellspacing=0 id="Buttons1_' + rte + '" width="' + tablewidth + '">');
			document.write('<tr>');
			document.write('<td>');
			document.write('<select id="formatblock_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);">');
			document.write('<option value="">[Style]</option>');
			document.write('<option value="<p>">Paragraph &lt;p&gt;</option>');
			document.write('<option value="<h1>">Heading 1 &lt;h1&gt;</option>');
			document.write('<option value="<h2>">Heading 2 &lt;h2&gt;</option>');
			document.write('<option value="<h3>">Heading 3 &lt;h3&gt;</option>');
			document.write('<option value="<h4>">Heading 4 &lt;h4&gt;</option>');
			document.write('<option value="<h5>">Heading 5 &lt;h5&gt;</option>');
			document.write('<option value="<h6>">Heading 6 &lt;h6&gt;</option>');
			document.write('<option value="<address>">Address &lt;ADDR&gt;</option>');
			document.write('<option value="<pre>">Formatted &lt;pre&gt;</option>');
			document.write('</select>');
			document.write('</td>');
			document.write('<td>');
			document.write('<select id="fontname_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id)">');
			document.write('<option value="Font" selected>[Font]</option>');
			document.write('<option value="Arial, Helvetica, sans-serif">Arial</option>');
			document.write('<option value="Courier New, Courier, mono">Courier New</option>');
			document.write('<option value="Times New Roman, Times, serif">Times New Roman</option>');
			document.write('<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>');
			document.write('</select>');
			document.write('</td>');
			document.write('<td>');
			document.write('<select unselectable="on" id="fontsize_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);">');
			document.write('<option value="Size">[Size]</option>');
			document.write('<option value="1">1</option>');
			document.write('<option value="2">2</option>');
			document.write('<option value="3">3</option>');
			document.write('<option value="4">4</option>');
			document.write('<option value="5">5</option>');
			document.write('<option value="6">6</option>');
			document.write('<option value="7">7</option>');
			document.write('</select>');
			document.write('</td>');
			document.write('<td width="100%">');
			document.write('</td>');
			document.write('</tr>');
			document.write('</table>');
			document.write('<table class="rteBack" cellpadding="0" cellspacing="0" id="Buttons2_' + rte + '" width="' + tablewidth + '">');
			document.write('<tr>');
			document.write('<td><img id="bold" class="rteImage" src="' + imagesPath + 'bold.gif" width="25" height="24" alt="Bold" title="Bold" onClick="rteCommand(\'' + rte + '\', \'bold\', \'\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'italic.gif" width="25" height="24" alt="Italic" title="Italic" onClick="rteCommand(\'' + rte + '\', \'italic\', \'\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'underline.gif" width="25" height="24" alt="Underline" title="Underline" onClick="rteCommand(\'' + rte + '\', \'underline\', \'\')"></td>');
			document.write('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'left_just.gif" width="25" height="24" alt="Align Left" title="Align Left" onClick="rteCommand(\'' + rte + '\', \'justifyleft\', \'\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'centre.gif" width="25" height="24" alt="Center" title="Center" onClick="rteCommand(\'' + rte + '\', \'justifycenter\', \'\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'right_just.gif" width="25" height="24" alt="Align Right" title="Align Right" onClick="rteCommand(\'' + rte + '\', \'justifyright\', \'\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'justifyfull.gif" width="25" height="24" alt="Justify Full" title="Justify Full" onclick="rteCommand(\'' + rte + '\', \'justifyfull\', \'\')"></td>');
			document.write('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'hr.gif" width="25" height="24" alt="Horizontal Rule" title="Horizontal Rule" onClick="rteCommand(\'' + rte + '\', \'inserthorizontalrule\', \'\')"></td>');
			document.write('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'numbered_list.gif" width="25" height="24" alt="Ordered List" title="Ordered List" onClick="rteCommand(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'list.gif" width="25" height="24" alt="Unordered List" title="Unordered List" onClick="rteCommand(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>');
			document.write('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'outdent.gif" width="25" height="24" alt="Outdent" title="Outdent" onClick="rteCommand(\'' + rte + '\', \'outdent\', \'\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'indent.gif" width="25" height="24" alt="Indent" title="Indent" onClick="rteCommand(\'' + rte + '\', \'indent\', \'\')"></td>');
			document.write('<td><div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'textcolor.gif" width="25" height="24" alt="Text Color" title="Text Color" onClick="dlgColorPalette(\'' + rte + '\', \'forecolor\', \'\')"></div></td>');
			document.write('<td><div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" width="25" height="24" alt="Background Color" title="Background Color" onClick="dlgColorPalette(\'' + rte + '\', \'hilitecolor\', \'\')"></div></td>');
			document.write('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'hyperlink.gif" width="25" height="24" alt="Insert Link" title="Insert Link" onClick="insertLink(\'' + rte + '\')"></td>');
			document.write('<td><img class="rteImage" src="' + imagesPath + 'image.gif" width="25" height="24" alt="Add Image" title="Add Image" onClick="addImage(\'' + rte + '\')"></td>');
			document.write('<td><div id="table_' + rte + '"><img class="rteImage" src="' + imagesPath + 'insert_table.gif" width="25" height="24" alt="Insert Table" title="Insert Table" onClick="dlgInsertTable(\'' + rte + '\', \'table\', \'\')"></div></td>');
			if (isIE) {
				document.write('<td><img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="25" height="24" alt="Spell Check" title="Spell Check" onClick="checkspell()"></td>');
			}
	//		document.write('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
	//		document.write('<td><img class="rteImage" src="' + imagesPath + 'cut.gif" width="25" height="24" alt="Cut" title="Cut" onClick="rteCommand(\'' + rte + '\', \'cut\')"></td>');
	//		document.write('<td><img class="rteImage" src="' + imagesPath + 'copy.gif" width="25" height="24" alt="Copy" title="Copy" onClick="rteCommand(\'' + rte + '\', \'copy\')"></td>');
	//		document.write('<td><img class="rteImage" src="' + imagesPath + 'paste.gif" width="25" height="24" alt="Paste" title="Paste" onClick="rteCommand(\'' + rte + '\', \'paste\')"></td>');
	//		document.write('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
	//		document.write('<td><img class="rteImage" src="' + imagesPath + 'undo.gif" width="25" height="24" alt="Undo" title="Undo" onClick="rteCommand(\'' + rte + '\', \'undo\')"></td>');
	//		document.write('<td><img class="rteImage" src="' + imagesPath + 'redo.gif" width="25" height="24" alt="Redo" title="Redo" onClick="rteCommand(\'' + rte + '\', \'redo\')"></td>');
			document.write('<td width="100%"></td>');
			document.write('</tr>');
			document.write('</table>');
		}
		document.write('<iframe id="' + rte + '" name="' + rte + '" width="' + width + 'px" height="' + height + 'px" src="' + includesPath + 'blank.htm"></iframe>');
		if (!readOnly) document.write('<br /><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" />&nbsp;View Source');
		document.write('<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; position: absolute;"></iframe>');
		document.write('<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="' + html.replace(/\"/g, '\'') + '">');
		document.write('</div>');

		if(document.getElementById('hdn' + rte)){
			document.getElementById('hdn' + rte).value = html;
		}

		enableDesignMode(rte, html, readOnly);

	} else {
		if (!readOnly) {
			document.write('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
		} else {
			document.write('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>');
		}
	}
}

function enableDesignMode(rte, html, readOnly) {
	var frameHtml = "<html id=\"" + rte + "\">\n";
	frameHtml += "<head>\n";
	//to reference your stylesheet, set href property below to your stylesheet path and uncomment
	if (cssFile.length > 0) {
		frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
	} else {
		frameHtml += "<style>\n";
		frameHtml += "body {\n";
		frameHtml += "background: #FFFFFF;\n";
		frameHtml += "margin: 0px;\n";
		frameHtml += "padding: 0px;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
	}
	frameHtml += "</head>\n";
	frameHtml += "<body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";
	
	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) oRTE.designMode = "On";
	} else {
		try {
			if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try {
				var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if (isGecko && !readOnly) {
					//attach a keyboard handler for gecko browsers to make keyboard shortcuts work
					oRTE.addEventListener("keypress", kb_handler, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
}

function updateRTEs() {
	var vRTEs = allRTEs.split(";");
	for (var i = 0; i < vRTEs.length; i++) {
		updateRTE(vRTEs[i]);
	}
}

function updateRTE(rte) {
	if (!isRichText) return;
	
	//set message value
	var oHdnMessage = document.getElementById('hdn' + rte);
	var oRTE = document.getElementById(rte);
	var readOnly = false;
	
	//check for readOnly mode
	if (document.all) {
		if (frames[rte].document.designMode != "On") readOnly = true;
	} else {
		if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
	}
	
	if (isRichText && !readOnly) {
		//if viewing source, switch back to design view
		if (document.getElementById("chkSrc" + rte).checked) {
			document.getElementById("chkSrc" + rte).checked = false;
			toggleHTMLSrc(rte);
		}
		
		if (oHdnMessage.value == null) oHdnMessage.value = "";
		if (document.all) {
			oHdnMessage.value = frames[rte].document.body.innerHTML;
		} else {
			oHdnMessage.value = oRTE.contentWindow.document.body.innerHTML;
		}
		
		//if there is no content (other than formatting) set value to nothing
		if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == "" 
			&& oHdnMessage.value.toLowerCase().search("<hr") == -1
			&& oHdnMessage.value.toLowerCase().search("<img") == -1) oHdnMessage.value = "";
		//fix for gecko
		if (escape(oHdnMessage.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A") oHdnMessage.value = "";
	}
}

function rteCommand(rte, command, option) {
	//function to perform command
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	try {
		oRTE.focus();
		if(command == "CreateLink" && oRTE.document.selection){
			var userSelection;

			if(oRTE.document.getSelection){// NON IE
				userSelection = oRTE.document.getSelection();
				/*if(userSelection.getRangeAt){
					alert('ok');
					//rangeObject = userSelection.getRangeAt(0);
					//alert(rangeObject);
				}*/

			}else if(oRTE.document.selection){// ONLY IE
				userSelection = oRTE.document.selection.createRange();
				a = '<a href="' + option + '" target="_blank">' + userSelection.text + '</a>';
				userSelection.pasteHTML(a);
			}

		}else{
			oRTE.document.execCommand(command, false, option);
		}

		oRTE.focus();

	} catch (e) {
		//alert(e);
		//setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 10);
	}	
}

function toggleHTMLSrc(rte) {
	//contributed by Bob Hutzel (thanks Bob!)
	var oRTE;
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}
	
	if (document.getElementById("chkSrc" + rte).checked) {
		showHideElement("Buttons1_" + rte, "hide");
		showHideElement("Buttons2_" + rte, "hide");
		if (document.all) {
			oRTE.body.innerText = oRTE.body.innerHTML;
		} else {
			var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		showHideElement("Buttons1_" + rte, "show");
		showHideElement("Buttons2_" + rte, "show");
		if (document.all) {
			//fix for IE
			var output = escape(oRTE.body.innerText);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
			
			oRTE.body.innerHTML = unescape(output);
		} else {
			var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
	}
}

function dlgColorPalette(rte, command) {
	//function to display or hide color palettes
	setRange(rte);
	
	//get dialog position
	var oDialog = document.getElementById('cp' + rte);
	var buttonElement = document.getElementById(command + '_' + rte);
	var iLeftPos = getOffsetLeft(buttonElement);
	var iTopPos = getOffsetTop(buttonElement) + (buttonElement.offsetHeight + 4);
	oDialog.style.left = (iLeftPos) + "px";
	oDialog.style.top = (iTopPos) + "px";
	
	if ((command == parent.command) && (rte == currentRTE)) {
		//if current command dialog is currently open, close it
		if (oDialog.style.visibility == "hidden") {
			showHideElement(oDialog, 'show');
		} else {
			showHideElement(oDialog, 'hide');
		}
	} else {
		//if opening a new dialog, close all others
		var vRTEs = allRTEs.split(";");
		for (var i = 0; i < vRTEs.length; i++) {
			showHideElement('cp' + vRTEs[i], 'hide');
		}
		showHideElement(oDialog, 'show');
	}
	
	//save current values
	parent.command = command;
	currentRTE = rte;
}

function dlgInsertTable(rte, command) {
	//function to open/close insert table dialog
	//save current values
	setRange(rte);
	parent.command = command;
	currentRTE = rte;
	var windowOptions = 'history=no,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=no,width=360,height=200';
	window.open(includesPath + 'insert_table.htm', 'InsertTable', windowOptions);
}

function insertLink(rte) {
	//function to insert link
	var szURL = prompt("Enter a URL:", "");
	try {
		//ignore error for blank urls
		rteCommand(rte, "Unlink", null);
		rteCommand(rte, "CreateLink", szURL);
	} catch (e) {
		//do nothing
	}
}

function setColor(color) {
	//function to set color
	var rte = currentRTE;
	var parentCommand = parent.command;
	
	if (document.all) {
		//retrieve selected range
		var sel = frames[rte].document.selection; 
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		if (sel != null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}
	
	rteCommand(rte, parentCommand, color);
	showHideElement('cp' + rte, "hide");
}

function addImage(rte) {
	//function to add image
	imagePath = prompt('Enter Image URL:', 'http://');
	if ((imagePath != null) && (imagePath != "")) {
		rteCommand(rte, 'InsertImage', imagePath);
	}
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2; //the positioning div is 2 elements up the tree
	
	while(parents_up > 0) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2;
	
	while(parents_up > 0) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetLeft;
}

function selectFont(rte, selectname) {
	//function to handle font changes
	var idx = document.getElementById(selectname).selectedIndex;
	// First one is always a label
	if (idx != 0) {
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + rte, '');
		rteCommand(rte, cmd, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function kb_handler(evt) {
	var rte = evt.target.id;
	
	//contributed by Anti Veeranna (thanks Anti!)
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			rteCommand(rte, cmd, null);
			
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

function insertHTML(html) {
	//function to add HTML -- thanks dannyuk1982
	var rte = currentRTE;
	
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	oRTE.focus();
	if (document.all) {
		oRTE.document.selection.createRange().pasteHTML(html);
	} else {
		oRTE.document.execCommand('insertHTML', false, html);
	}
}

function showHideElement(element, showHide) {
	//function to show or hide elements
	//element variable can be string or object
	if (document.getElementById(element)) {
		element = document.getElementById(element);
	}
	
	if (showHide == "show") {
		element.style.visibility = "visible";
	} else if (showHide == "hide") {
		element.style.visibility = "hidden";
	}
}

function setRange(rte) {
	//function to store range of current selection
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		var selection = oRTE.document.selection; 
		if (selection != null) rng = selection.createRange();
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
}

function stripHTML(oldString) {
	//function to strip all html
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");
	
	//replace carriage returns and line feeds
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");
	
	//trim string
	newString = trim(newString);
	
	return newString;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
	
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length - 1, retValue.length);
	
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length - 1);
      ch = retValue.substring(retValue.length - 1, retValue.length);
   }
	
	// Note that there are two spaces in the string - look for multiple spaces within the string
   while (retValue.indexOf("  ") != -1) {
		// Again, there are two spaces in each of the strings
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
   }
   return retValue; // Return the trimmed string back to the user
}

//*****************
//IE-Only Functions
//*****************
function checkspell() {
	//function to perform spell check
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		} else {
			alert("Error Loading ieSpell: Exception " + exception.number);
		}
	}
}

function raiseButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageLowered') {
		el.className = 'rteImageRaised';
	}
}

function normalButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImageRaised' || className == 'rteImageLowered') {
		el.className = 'rteImage';
	}
}

function lowerButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageRaised') {
		el.className = 'rteImageLowered';
	}
}

//################################################################################################//

///////////////////////////////////////// END RICH TEXT ////////////////////////////////////////////////

//################################################################################################//

var carregar;

function abrePagina( img ){
	carregar = new Image();
	carregar.src = img;
	document.getElementById("showImage").innerHTML = "<div style='color:#000000; font-size:10px; font-family:arial; width:90px; padding:5px 3px 5px 0px; text-align:right;'><img src='http://dev.dalmeida.com.br/pt_BR/images/loading.gif' align='absmiddle'>&nbsp;Carregando...</div>";
	setTimeout( "verificaCarregamento()", 100 );
}

function verificaCarregamento(){
	if( carregar.complete ){
		document.getElementById("showImage").innerHTML = "<img src='" + carregar.src + "'>";
	}else{
		setTimeout( "verificaCarregamento()", 100 );
	}
}




//////////////////////////////////////////// thumb //////////////////////////////////////////////////////////////////////////////

$(document).ready(function(){

		
		$('#etapa').click(function () {
			
		  var payment;
		  payment=$('#frmPaymentAux input:radio:checked').val();
			  
			
			if(payment=='payment1'){		
				
				var n1 = $("[name=payment1_cardnumberPart1]").val().length;
				var n2 = $("[name=payment1_cardnumberPart2]").val().length;
				var n3 = $("[name=payment1_cardnumberPart3]").val().length;
				var n4 = $("[name=payment1_cardnumberPart4]").val().length;

				if(n1<4 || n2<4 || n3<4 || n4<4) {
					alert("Digite Corretamente o Nmero do Carto");
					return false;
				}
			}

			if(payment=='payment2'){		
				
				var n1 = $("[name=payment2_cardnumberPart1]").val().length;
				var n2 = $("[name=payment2_cardnumberPart2]").val().length;
				var n3 = $("[name=payment2_cardnumberPart3]").val().length;
				var n4 = $("[name=payment2_cardnumberPart4]").val().length;

				if(n1<4 || n2<4 || n3<4 || n4<4) {
					alert("Digite Corretamente o Nmero do Carto");
					return false;
				}
			}
		});

		



		//Larger thumbnail preview 

		$("ul.thumb li").hover(function() {
			$(this).css({'z-index' : '10'});
			$(this).find('img').addClass("hover").stop()
				.animate({
					marginTop: '-110px', 
					marginLeft: '-110px', 
					top: '50%', 
					left: '50%', 
					width: '174px', 
					height: '174px',
					padding: '20px' 
				}, 200);
			
			} , function() {
			$(this).css({'z-index' : '0'});
			$(this).find('img').removeClass("hover").stop()
				.animate({
					marginTop: '0', 
					marginLeft: '0',
					top: '0', 
					left: '0', 
					width: '100px', 
					height: '100px', 
					padding: '5px'
				}, 400);
		});

		//Swap Image on Click
			$("ul.thumb li a").click(function() {
				$("#main_view img").hide();
				$("#main_view").html('<img src="/global/images/spinner.gif" alt="Loading" />');
				var mainImage = $(this).attr("href"); //Find Image Name
				$("#main_view img").attr({ src: mainImage })
				$("#main_view img").fadeIn(1000);
				return false;		
			});

			
//////////////////////////////////////////// form  features //////////////////////////////////////////////////////////////////////////////
			

		
		
		// end cartRow //////////////////////////////////////////////////////////

		
		// cartShipping  //////////////////////////////////////////////////////////

	

		// end  cartShipping  //////////////////////////////////////////////////////////




	//$('#frmPaymentAux input:radio:checked').val();
		 /*
		 //$(this).next("span").css('display','inline').fadeOut(1000);
		//alert(this.name + $(this).val());
		
		$.post("/cart/add/7599",  
		{ajax:1, time: "2pm" },  
			function(data){  
			//alert("Data Loaded: " + data);
			//alert(data);  
			$(".cart_container").empty();
			//$(".cart_container").h();
			$(".cart_container").append(data);

			//$(data).replaceAll(".cart_container");
			 //$(".cart_container").replaceWith(data);

			},
			"html"  
		); 
			
		*/
		/*
		$.ajax({
			type: "POST",
			url: "cart/add/7599",
			data: "ajax=1",
			cache: false,
			success: function(html){
			//alert(html);
			//alert($(".cart_container").html());
			$(".cart_container").append(html);
			}
		




	


	

/*
$("#cep_calcular").click(function () {
		alert("calcular frete");
});

$("#q").focus(function () {
	 $(this).val("");
});*/
		
		
	
	
});


/***************************************************************************************************/
/**************************************		function		****************************************/
/***************************************************************************************************/
//module bu
//controller orders
//action detail

$(document).ready(function() {

	$('.order__detail__href__templateRender').live("click", function(){
			
			var mailControl__code=$(this).attr("id");
			element_id=Math.floor(Math.random() * 1600);
			$("body").append('<div id="'+element_id+'"></div>');
			//$.ui.dialog.defaults.bgiframe = false;
			element_id_jquery='#'+element_id;
						
			$(element_id_jquery).load("/bu/mail-control/detail",{mailControl__code:mailControl__code}).dialog(
					{	
						width: 700,
						height: 450	,
						modal:true,
						title:"Mensagem enviada:"
					}
			);
				//var width = $("#mailControlTemplateRender").dialog('option', 'width');
				//$("#mailControlTemplateRender").dialog('option', 'width', 700);

				//$("#mailControlTemplateRender").dialog({ height: 600 });
				//var height = $("#mailControlTemplateRender").dialog('option', 'height');
				//$("#mailControlTemplateRender").dialog('option', 'height', 600);
			//});
	
	});	
});
