/*
 * $Id: common.js,v 1.4 2008/03/29 17:51:35 desenvolvedor Exp $
 * Scrips Comuns a todas a paginas...
 *
 */

function ajaxErrorHandler(status, msg ) {
	if ( status != 200 ) {
		//alert("Erro acessando servidor:\n[" + status + "] - " + msg);
	}
	if( $('statusContainer') != null )
		setTimeout("$('statusContainer').style.visibility='hidden';",500);

}




//mostraumdiv
function mostraDiv(divId){
	$(divId).style.display='block';
	$(divId).style.visibility='visible';
}

//ocultaumdiv
function ocultaDiv(divId){
	$(divId).style.display='none';
	$(divId).style.visibility='hidden';
}


/**
* Mostra um div por algum tempo
* div_id ==> id do div aplicado
* msg ==> Mensagem
* t ==> tempo que o div aparece, se == 0 nao esconde
*/
function setStatus(div_id, div_msg, msg, t) {
	showDiv(div_id);
	
	$(div_msg).innerHTML = msg + " ";
	
	if( t > 0 )
		setTimeout( "clearStatus('"+ div_id +"','"+ div_msg +"');", t );
}

function setStatusBlink(div_id, div_msg, msg) {
	
	pass = 0;
	if( arguments.length == 4 )
		pass = parseInt(arguments[3]);

	$(div_msg).innerHTML = msg + " ";
	if( pass % 2 == 0 )
		showDiv(div_id);
	else
		$(div_id).style.visibility = 'hidden';
	
	if( pass < 6 )
		setTimeout( 'setStatusBlink("'+ div_id +'","'+ div_msg +'","'+ msg +'","'+ (++pass) +'");', 300 );
		
}

function clearStatus(div_id, div_msg ) {
	$(div_id).style.visibility = "hidden";
	$(div_msg).innerHTML = "&nbsp;";
}




var AlertMessageHandler = Class.create();

AlertMessageHandler.attributes = [ "Message" ];

AlertMessageHandler.prototype = {

   initialize: function() {
      this.message    = null;
   },

   ajaxUpdate: function(ajaxResponse) {
      this.showMessage(ajaxResponse.childNodes);
   },

   showMessage: function( nodes ){
   	for( t=0; t < nodes.length; t++ ){
		aMessage = nodes[t];
		if( aMessage.attributes != null ){
   			alert(aMessage.getAttribute("msg"));
		}
	}
   }

};

var SiteMessageHandler = Class.create();

SiteMessageHandler.attributes = [ "titulo","message" ];

SiteMessageHandler.prototype = {

   initialize: function() {
      this.message    = null;
   },

   ajaxUpdate: function(ajaxResponse) {
      this.showMessage(ajaxResponse.childNodes);
   },

   showMessage: function( nodes ){
   		titulo = "";
		msg = "";
   		for( t=0; t < nodes.length; t++ ){
			aMessage = nodes[t];
			values = aMessage.childNodes;
			if(aMessage.nodeName == "titulo")
				titulo = flattenChildren(values);
			if(aMessage.nodeName == "message")
				msg = flattenChildren(values);
			
				
		}
		//alert(msg);
		//alert(titulo);
		showSiteMsg(titulo,msg);		
	}
 };
  
function showSiteMsg(tit,msg){
	$('showimage_tit').innerHTML = tit;
	$('showimage_msg').innerHTML = msg;
	$('showimage').style.visibility='visible';
	$('showimage').style.display='block';
	document.onmouseup=new Function("dragapproved=false");
	setTimeout('hideSiteMsg()',15000);
}
function hideSiteMsg(){
	$('showimage').style.visibility='hidden';
	$('showimage').style.display='none';
}
/******************************************
* Popup Box- By Jim Silver @ jimsilver47@yahoo.com
* Visit http://www.dynamicdrive.com/ for full source code
* This notice must stay intact for use
******************************************/

var ns4=document.layers
var ie4=document.all
var ns6=document.getElementById&&!document.all

//drag drop function for NS 4////
/////////////////////////////////

var dragswitch=0
var nsx
var nsy
var nstemp

function drag_dropns(name){
if (!ns4)
return
temp=eval(name)
temp.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP)
temp.onmousedown=gons
temp.onmousemove=dragns
temp.onmouseup=stopns
}

function gons(e){
temp.captureEvents(Event.MOUSEMOVE)
nsx=e.x
nsy=e.y
}
function dragns(e){
if (dragswitch==1){
temp.moveBy(e.x-nsx,e.y-nsy)
return false
}
}

function stopns(){
temp.releaseEvents(Event.MOUSEMOVE)
}

//drag drop function for ie4+ and NS6////
/////////////////////////////////


function drag_drop(e){
if (ie4&&dragapproved){
crossobj.style.left=tempx+event.clientX-offsetx
crossobj.style.top=tempy+event.clientY-offsety
return false
}
else if (ns6&&dragapproved){
crossobj.style.left=tempx+e.clientX-offsetx+"px"
crossobj.style.top=tempy+e.clientY-offsety+"px"
return false
}
}

function initializedrag(e){
crossobj=ns6? document.getElementById("showimage") : document.all.showimage
var firedobj=ns6? e.target : event.srcElement
var topelement=ns6? "html" : document.compatMode && document.compatMode!="BackCompat"? "documentElement" : "body"
while (firedobj.tagName!=topelement.toUpperCase() && firedobj.id!="dragbar"){
firedobj=ns6? firedobj.parentNode : firedobj.parentElement
}

if (firedobj.id=="dragbar"){
offsetx=ie4? event.clientX : e.clientX
offsety=ie4? event.clientY : e.clientY

tempx=parseInt(crossobj.style.left)
tempy=parseInt(crossobj.style.top)

dragapproved=true
document.onmousemove=drag_drop
}
}



////drag drop functions end here//////

function hidebox(){
crossobj=ns6? document.getElementById("showimage") : document.all.showimage
if (ie4||ns6)
crossobj.style.visibility="hidden"
else if (ns4)
document.showimage.visibility="hide"
}





//conta caracteres
function countChar( string, ch ){
	c = 0;
	for( t = 0; t < string.length; t++ ){
		if( string.charAt(t) == ch )c++;
	}
	return c;
}


function showDiv(div_id) {
	$(div_id).style.visibility = "visible";
}

function hideDiv(div_id) {
	$(div_id).style.visibility = "hidden";
}


/**
* Altera a cor de fundo de uma linha
**/
alter = false;
var elSel = null;
var corAnt;
function fundo(el, cor, qtde){
	tdId = el.id.split("_")[1];
	
	if(alter && elSel != null){
		tdId_sel = elSel.id.split("_")[1];
		if( tdId == tdId_sel )return;
	}
	for( t = 1; t <= qtde; t++ )
		$(t + '_' + tdId).style.background=cor;
	
}


function seleciona(el, cor, ant, qtde){
	alter = false;
	if( elSel != undefined )
		fundo(elSel,corAnt, qtde);

	alter = true;
	elSel = el;
	corAnt = ant

	tdId = el.id.split("_")[1];
	
	for( t = 1; t <= qtde; t++ )
		$(t + '_' + tdId).style.background=cor;
	
}





//alerta vindo do ajax
var MessageBoxHandler = Class.create();

MessageBoxHandler.attributes = [ "message" ];

MessageBoxHandler.prototype = {

   initialize: function() {
      this.message    = null;
   },

   ajaxUpdate: function(ajaxResponse) {
      this.showMessage(ajaxResponse.childNodes);
   },

   showMessage: function( nodes ){
   	for( t=0; t < nodes.length; t++ ){
		aMessage = nodes[t];
		if( aMessage.attributes != null ){
   			alert(aMessage.getAttribute("msg"));
		}
	}
   }

};


//ajusta o scroll depois da busca
SearchRowsConfigurator = Class.create();
SearchRowsConfigurator.prototype = {

   initialize: function(liveGrid) {
     this.liveGrid = liveGrid;
   },

   ajaxUpdate: function(ajaxResponse) {
      var cell = ajaxResponse.getElementsByTagName("numResults")[0];
      var numResults = cell.text != undefined ? cell.text : cell.textContent;
      if ( this.liveGrid.metaData.getTotalRows() != numResults && numResults != -1) {
         this.liveGrid.metaData.setTotalRows(numResults);
         this.liveGrid.scroller.updateSize();
      }
      
      if( $('bookmark_total') != undefined ){
      	if( numResults == "-1" )numResults="Nenhum";
      	$('bookmark_total').innerHTML = ' de ' + numResults;
      }
      	
   }
};


/**
 * Atualizador para dados de um form. Aceita um objeto de resposta
 * com elementos <field name="nome do campo" value="valor" />
 */
var FormDataUpdater = Class.create();

FormDataUpdater.prototype = {

	initialize: function(f) {
		this.form = f;
	},

	ajaxUpdate: function(ajaxResponse) {

		var fields = ajaxResponse.getElementsByTagName("field");
		var i;
		
		for( i = 0 ; i < fields.length ; i++ ) {
			var field = fields[i];
			var fname = field.getAttribute("name");
			if ( this.form[fname] ) {			
				// Atualiza valor do campo
				setValue(this.form[fname], field.getAttribute("value"));
			}
		}
	}
}


var PopularCombo = Class.create();

PopularCombo.prototype = {

	initialize: function(combo) {
		this.combo = combo;
	},

	ajaxUpdate: function(ajaxResponse) {
		
		
		var fields = ajaxResponse.getElementsByTagName("option");
		var i;
		var combo = this.combo;
		for( i = 0 ; i < fields.length ; i++ ) {
			var field = fields[i];
			var flabel = field.getAttribute("label");
			var fvalue = field.getAttribute("value");
			
			combo.options.length=(i + 1);
			combo.options[i].value=fvalue;
			combo.options[i].text=flabel;
			
		}
	}
}

var AlertarMensagens = Class.create();

AlertarMensagens.prototype = {

	initialize: function() {

	},

	ajaxUpdate: function(ajaxResponse) {
		
		
		var fields = ajaxResponse.getElementsByTagName("message");
		var i;
		var msg = "";
		for( i = 0 ; i < fields.length ; i++ ) {
			var field = fields[i];
			if( i > 0 ) msg += "\n";
			msg  += field.getAttribute("value");
		}
		
		if( msg.length > 0 )
		alert(msg);
		
	}
}


var ConfirmarMensagens = Class.create();
ConfirmarMensagens.prototype = {
	initialize: function(funcaoconfirma) {
		this.funcao=funcaoconfirma;
	},

	ajaxUpdate: function(ajaxResponse) {
		var fields = ajaxResponse.getElementsByTagName("message");
		var i;
		var msg = "";
		for( i = 0 ; i < fields.length ; i++ ) {
			var field = fields[i];
			if( i > 0 ) msg += "\n";
			msg  += field.getAttribute("value");
		}
		
		if( msg.length > 0 ){
			if(confirm(msg)){
				this.funcao();
			}
		}
		
	}
}

var OpenPopup = Class.create();
OpenPopup.prototype={

	initialize: function() {

	},

	ajaxUpdate: function(ajaxResponse) {
		
		
		var fields = ajaxResponse.getElementsByTagName("popup");
		var i;
		var url = "";
		var settings = "";
		var name = ""
		for( i = 0 ; i < fields.length ; i++ ) {
			var field = fields[i];
			url = field.getAttribute("url");
			settings = field.getAttribute("settings");
			name = field.getAttribute("name");						
		}
		if( url.length > 0 )
			window.open(url,name,settings);
		
	}
}




//para arrendar a borda de algum div necess?rio
var ArredondaBordasHandler = Class.create();
ArredondaBordasHandler.prototype = {

   initialize: function() {
      
   },

   ajaxUpdate: function(ajaxResponse) {
      this.showMessage(ajaxResponse.childNodes);
   },

   showMessage: function( nodes ){
   	for( t=0; t < nodes.length; t++ ){
		aMessage = nodes[t];
		if( aMessage.attributes != null ){
   			if( aMessage.getAttribute("div_id") != null ){
				Rico.Corner.round(aMessage.getAttribute("div_id"))
			}
		}
	}
   }

};

/**
 * Atualizador para dados de um form. Aceita um objeto de resposta
 * com elementos <field name="nome do campo" value="valor" />
 */
var FlowControlUpdater = Class.create();

FlowControlUpdater.prototype = {

	initialize: function(d) {
		this.doc = d;
	},

	ajaxUpdate: function(ajaxResponse) {

		var fields = ajaxResponse.getElementsByTagName("location");
		var i;
		
		for( i = 0 ; i < fields.length ; i++ ) {

			var field = fields[i];
			
			// Manobra para evitar leaks no IE
			var tmpDoc = this.doc;
			this.doc = null;
			tmpDoc.location.href = field.getAttribute("href");
		}
	}

}

/**
 * Atualizador do estado do documento. Recebe uma lista
 * de comandos de atualiza??o com os segiuntes atributos:
 * type - tipo do comando
 * target - id do objeto que ser? atualizado
 * property - "propriedade" a ser alterada pelo comando.<b>
 * value - Novo valor da propriedade 
 */
var ViewControlUpdater = Class.create();

ViewControlUpdater.prototype = {

	initialize: function(d) {
		this.doc = d;
	},

	ajaxUpdate: function(ajaxResponse) {

		var cmdlist = ajaxResponse.getElementsByTagName("cmd");
		var i;
		
		for( i = 0 ; i < cmdlist.length ; i++ ) {
			var cmd = cmdlist[i];
			var cmdType = cmd.getAttribute("type");
			if ( cmdType == "setstyle" ) {
				this.setStyle(
					cmd.getAttribute("target"),
					cmd.getAttribute("property"),
					cmd.getAttribute("value") );
			}
			// Outros comandos por vir...			
		}
	},
	
	/**
	 * Altera o estilo de um objeto
	 */
	setStyle: function(target, property, value ) {
		var el = document.getElementById(target);
		if ( !el ) {
			return;
		}
		
		el.style[property] = value;
	}

}

function imprimir( f, e ){
	
	openpopup(f, '', '600', '450', e);
}




var temp = null;
var Temporizador = Class.create();
Temporizador.prototype = {
	initialize: function(f){
		this.funcao = f;
	},
	
	ajaxUpdate: function(ajaxResponse) {
			if(temp != null)clearTimeout(temp);
			var fields = ajaxResponse.getElementsByTagName("temporizador");
			tempo = fields[0].getAttribute("timeout");
			temp = setTimeout(this.funcao + '()',parseInt(tempo));
  	}
	
	
}


var AtualizaStatusLotesUpdater = Class.create();
AtualizaStatusLotesUpdater.prototype = {

	initialize: function(idLeilao, page, maxRegs) {
		this.cont = 0;
		this.idLeilao = idLeilao;
		this.page=page;
		this.maxRegs=maxRegs;
	},

	ajaxUpdate: function(ajaxResponse) {
		var fields = ajaxResponse.getElementsByTagName("lote");
		var i;
		for( i = 0 ; i < fields.length ; i++ ) {
			var field = fields[i];
			var id = field.getAttribute("id");
			ajaxEngine.registerAjaxElement( 'status_lote_' + id );	
			
		}
		//alert("oi");
		atualizarStatus(this.idLeilao,this.page,this.maxRegs);	
	}

}

function atualizarStatus(idLeilao, page, maxRegs){
	
	ajaxEngine.sendRequest('atualizaStatusLotes', 'id='+ idLeilao, 'cont='+(cont++),'page='+page,'maxRegs='+maxRegs);
	setTimeout('atualizarStatus("'+ idLeilao +'","'+page+'","'+maxRegs+'")',5000);
}


var AtualizaLanceLotesUpdater = Class.create();
AtualizaLanceLotesUpdater.prototype = {

	initialize: function(idLeilao, page, maxRegs) {
		this.cont = 0;
		this.idLeilao = idLeilao;
		this.page=page;
		this.maxRegs=maxRegs;
	},

	ajaxUpdate: function(ajaxResponse) {
		var fields = ajaxResponse.getElementsByTagName("lote");
		var i;
		for( i = 0 ; i < fields.length ; i++ ) {
			var field = fields[i];
			var id = field.getAttribute("id");
			ajaxEngine.registerAjaxElement( 'lance_lote_' + id );
		}
		
		atualizarLances(this.idLeilao,this.page,this.maxRegs);	
	}

}

function atualizarLances(idLeilao, page, maxRegs){
	//document.location.href="/leiloando/atualizaLancesLotes.do?id="+ idLeilao;
	ajaxEngine.sendRequest('atualizaLancesLotes', 'id='+ idLeilao, 'cont='+(cont++),'page='+page,'maxRegs='+maxRegs);
	setTimeout('atualizarLances("'+ idLeilao +'","'+page+'","'+maxRegs+'")',5000);
}




