var indicemodal	= 0
var first 		= 0
var NLayer 		= new Array()

function Clayer(mensaje, ancho, alto, colorTrans)
{
	var self 
	var label
	 
	this.errorTimeout = 5
	this.hideTimeout  = 2
	this.nav = navigator.appName
	
	this.top = '<div class="rowTitCLayer" id="ClayerBottom_$idLayer$" style="text-align:left; $mode$">'+
 			   '<a href="javascript:;" title="Cerrar" class="botonClose" style="float:right; visibility:$visibility_aspa$" onclick="$action_aspa$">X</a>'+
			   '<span class="naranja normal" style="font-size:21px; font-weight:bold;">&raquo;</span>'+
			   '<span class="font14 bold"> $titulo_layer$</span></div>'
			   
	this.modal = '<div class="boxCLayer" style="$mode2$" id="$idLayer$">' +
			 	 '$ClayerTop$' +
				 '<div class="$ClayerRow$" style="$altura_layer$$mode$" id="ClayerContent_$idLayer$">$ClayerMensaje$</div>' +
				 '$ClayerBottom$'
				 '</div>'
				 
	this.button = '<a href="$ancla_boton$" $id$ onclick="$action$" title="$text_button$" class="botonGood" style=" float:right; margin-left:5px;">$text_button$</a>'
	
	this.button_close = '<a href="javascript:;" onclick="$action_button_close$" title="$text_button_close$" class="botonCancelar" style=" float:right; margin-left:5px;">$text_button_close$</a>'
	
	this.init = function ()  
	{
		this.texto = mensaje
		this.buttons = new Array()
		this.actions = new Array()
		this.anclas = new Array()
		this.ids = new Array()
		this.numbuttons = 0
		this.needbuttonsdefault = 1
		this.ancla = 0
		this.width = ancho
		if (alto)
			this.height = alto
		else 
			this.height = 100
		this.lanzador = "layer"
		this.topandbottom = 1
		this.titulo = "Aviso"
		this.ActionAspa = ""
		this.visibility_aspa = 'visible'
		this.botones_duplicados = 0
		this.id_layer = Math.random()
		this.BClose = 0 // Si vale cero el button_close será 'Cerrar', si vale 1 'Cancelar' y si vale 2 'Se deshabilita el BClose'
		this.ActionBClose = ''
		if (colorTrans)
			this.colorTrans = colorTrans
		else
			this.colorTrans = 'default_color'
		
		if (first == 0)
		{
			var html_doc = $_('head').item(0)
			var st = document.createElement('link')
			st.setAttribute('rel', 'stylesheet')
			st.setAttribute('href','css/layer.css')
			html_doc.appendChild(st)
			first++
		}
	}
	
	this.init()
	
	// Función que abre el layer dependiendo del tipo que se desee.
	this.open = function()
	{
		var caja_layer = ''
		var m1 = this.top
		var m2 = this.modal
		var m3 = ''
				
		// Titulo
		m1 = m1.replace(/\$titulo_layer\$/, this.titulo)
		if (this.ActionAspa == "")
			m1 = m1.replace(/\$action_aspa\$/,"$ocultarAviso("+this.id_layer+");")
		else
			m1 = m1.replace(/\$action_aspa\$/,this.ActionAspa)
		m1 = m1.replace(/\$visibility_aspa\$/, this.visibility_aspa)
		
		// Cuerpo
		if (this.topandbottom == 1)
		{
			m2 = m2.replace('$ClayerTop$', m1)
			m2 = m2.replace('$ClayerRow$',"row")
		}
		else
		{
			m2 = m2.replace(/\$ClayerTop\$/,"")
			m2 = m2.replace(/\$ClayerRow\$/,"row_without_top")
		}
		
		// Botones
		for (i = 0; i < this.numbuttons; i++)
		{
			var aux = this.button
			aux = aux.replace(/\$text_button\$/g, this.buttons[i])
			aux = aux.replace("$action$",this.actions[i] + ";return false;")
			// Establecemos los ids
			if (this.ids[i] != "")
				aux = aux.replace("$id$",'id="' + this.ids[i] + '"')
			else
				aux = aux.replace("$id$",'')
			// Establecemos las anclas
			if (this.anclas[i] == 0 && this.ancla == 1)
				aux = aux.replace("$ancla_boton$","#")
			else
				aux = aux.replace("$ancla_boton$","javascript:;")
			m3 = m3 + aux
		}
		// Añadimos los botones y el boton close
		m3_aux = '<div style=" float:left; $mode$; " id="ClayerBottons_'+this.id_layer+'">'
		if (this.BClose != 2)
			m3_aux += this.button_close
		m3_aux += m3 + '</div>'
		m3 = m3_aux
		
		// Juntamos todo
		caja_layer = m2.replace("$ClayerMensaje$", "$ClayerDuplicateBottons$" + this.texto)
		if (this.botones_duplicados == 1)
			caja_layer = caja_layer.replace("$ClayerDuplicateBottons$","<div style='margin-bottom:30px;'>"+m3+"</div>")
		else	
			caja_layer = caja_layer.replace("$ClayerDuplicateBottons$","")
		caja_layer = caja_layer.replace("$ClayerBottom$", m3)
		caja_layer = caja_layer.replace(/\$mode2\$/g,"width:" + this.width + "px; height:" + this.height + "px;")
		caja_layer = caja_layer.replace(/\$mode\$/g,"width:" + this.width + "px;")
		caja_layer = caja_layer.replace(/\$idLayer\$/g,this.id_layer)
		if (this.BClose != 2) 
		{
			if (this.BClose == 0)
				text_button_close = 'CERRAR'
			else
				text_button_close = 'CANCELAR'
			caja_layer = caja_layer.replace(/\$text_button_close\$/g,text_button_close)
			if (this.ActionBClose == '')
				caja_layer = caja_layer.replace(/\$action_button_close\$/g,"$ocultarAviso("+this.id_layer+");")
			else
				caja_layer = caja_layer.replace(/\$action_button_close\$/g,this.ActionBClose)
		}
		
		if (this.topandbottom == 1)
			AltoContenido = this.height - 60 // Para firefox.
		else
			AltoContenido = this.height - 35
		caja_layer = caja_layer.replace(/\$altura_layer\$/g,'height:'+AltoContenido+'px;')
		this.showModal(caja_layer)
	}
	
	// Función que establece los botones y las acciones que van a realizar
	this.AddButton = function(text,action)
	{
		this.buttons[this.numbuttons] = text.toUpperCase()
		this.actions[this.numbuttons] = action
		this.ids[this.numbuttons] = ""
		this.numbuttons++
	}
	
	this.setMensaje = function(mensaje)
	{
		this.texto = mensaje
		this.buttons = new Array()
		this.actions = new Array()
		this.numbuttons = 0
	}
	
	this.addButton 				 	= function(text,action){this.AddButton(text, action)}
	this.setNoNeedButtonsDefault 	= function(){this.needbuttonsdefault = 0}
	this.setYesNeedButtonsDefault 	= function(){this.needbuttonsdefault = 1}
	this.setLanzador 				= function(launch){this.lanzador = launch}
	this.setActionDefault 			= function(action){this.ActionAspa = action; this.ActionBClose = action}
	this.setModeBClose				= function(num){this.BClose = num}
	
	this.AddIdButton 				= function(pos,id){this.ids[pos] = id}
	this.addIdButton 				= function(pos,id){this.AddIdButton(pos,id)}
	
	this.SinTopAndBottom 			= function(){this.topandbottom = 0}
	this.ConTopAndBottom 			= function(){this.topandbottom = 1}
	this.setTitulo 					= function(texto){this.titulo = texto}	
	
	this.getIndiceModal 			= function(){return indicemodal}
	this.setAlto 					= function(num){this.height = num}
	this.setAncho 					= function(num){this.width = num}
	this.setVisibleAspa 			= function(){this.visibility_aspa = 'visible'}
	this.setHiddenAspa 				= function(){this.visibility_aspa = 'hidden'}
	this.Cerrar						= function(){this.hideModal()}
	
	this.setAncla 					= function(numBottom){this.ancla = 1; this.anclas[numBottom] = 1}
	this.setDuplicateButtons 		= function(){this.botones_duplicados = 1}
	this.setColorTrans				= function(color){this.colorTrans = color}
	
	// Funciones de etiquetas label
	this.errorLabel = function(msg)
	{
		crearEtiqueta()
		label.style.color = '#FFF'
		label.style.background = '#C30'
		label.innerHTML = msg
		setTimeout(function(){if($('_ajax_label')) document.body.removeChild($('_ajax_label'))},this.errorTimeout*1000)
	}
	
	this.showLabel = function(msg)
	{
		crearEtiqueta()
		label.style.color = '#000'
		label.style.background = '#FD6'
		label.innerHTML = msg
		label.style.display = ''
	}
	
	this.hideLabel = function(msg)
	{
		if(msg){
			crearEtiqueta()
			label.style.color = '#FFF'
			label.style.background = '#093'
			label.innerHTML = msg
			setTimeout(function(){if($('_ajax_label')) document.body.removeChild($('_ajax_label'))},this.hideTimeout*1000)
		}
		else 
			if($("_ajax_label")) 
				document.body.removeChild($("_ajax_label"))
	}
	
	// Funciones de redimensionamiento del layer
	this.NewAlto = function(nAlto)
	{
		var idventana = this.id_layer
		if (nAlto > this.height)
		{
			var diferencia = nAlto - this.height
			var NuevoAlto = this.height + diferencia
		}
		else
		{
			if (this.height > nAlto)
			{
				var diferencia = this.height - nAlto
				var NuevoAlto = this.height - diferencia
			}
			else
				var NuevoAlto = this.height
		}
		$(idventana).style.height = NuevoAlto +'px'
	}
	
	this.NewAncho = function(nAncho)
	{
		var navegador = navigator.appName
		if (navegador == "Microsoft Internet Explorer") 
			NuevoAncho = nAncho - 10
		else
			NuevoAncho = nAncho
		var idventana = this.id_layer
		
		$(idventana).style.width = NuevoAncho + 'px'
		$('ClayerBottom_'+this.id_layer).style.width = NuevoAncho + 'px'
		$('ClayerContent_'+this.id_layer).style.width = NuevoAncho + 'px'
		$('ClayerBottons_'+this.id_layer).style.width = NuevoAncho + 'px'
	}
	
	// Funciones utilizadas para no depender de la clase Ajax.
	this.showModal = function(html)
	{
		indicemodal++
	
		var idframe_trans = '_ajax_frame_trans_' + indicemodal
		var modalcontent = ''
		var modaldivtrans = ''
		var altura = document.documentElement.scrollHeight;
		
		if (!$(idframe_trans))
		{
			modalcontent = document.createElement('IFRAME')
			modalcontent.id = idframe_trans
			modalcontent.name = idframe_trans
			modalcontent.scrolling = "no" 
			modalcontent.frameBorder = "0"
			if (this.nav == "Microsoft Internet Explorer" && this.colorTrans != 'default_color')  
				modalcontent.src = "http://new.expocasa.com/comun/gestion/gestion_clayer/js/layer_trans.cfm?altura=" + altura + "&className=" + this.colorTrans
			modalcontent.style.cssText = "border:none;width:100%; height:" + altura + "px; position:absolute; top:0; left:0; z-index:"+((1000*indicemodal)+1)+"; filter:alpha(opacity=70);opacity:.70;"
			modalcontent.className = this.colorTrans
			document.body.appendChild(modalcontent)
		}
		
		indicemodal++
		NLayer[indicemodal] = idventana
		var idventana = '_ajax_modalcontent_' + this.id_layer + '_' + indicemodal 
		modalcontent = ''
		if(!$(idventana))
		{
			modalcontent = document.createElement('DIV')
			modalcontent.style.cssText = 'position:absolute; left: 0px; top: 0px; width: 100%; height: 100%; z-index:'+((1000*indicemodal)+1)+';'
			modalcontent.id = idventana
			document.body.appendChild(modalcontent)
		}
		
		$(idventana).innerHTML = '<table border="0" width="100%" height="100%" align="center"><tr><td align="center"><div class="modalstyle">' + html + '</div></td></tr></table>'
		document.body.style.height = '100%'
		$(idventana).style.top = getScrollY() + 'px'
	}
	
	this.hideModal = function()
	{
		if($('_ajax_modalcontent_'+this.id_layer+'_'+indicemodal)){
			document.body.removeChild($('_ajax_modalcontent_'+this.id_layer+'_'+indicemodal))
			indicemodal--
			document.body.removeChild($('_ajax_frame_trans_'+indicemodal))
			NLayer[indicemodal] = null
			indicemodal--
		}

		if(indicemodal>0 && $('_ajax_modalcontent_'+this.id_layer+'_'+indicemodal))
			$('_ajax_modalcontent_'+this.id_layer+'_'+indicemodal).style.top = getScrollY()
	}
	
	
	// Funciones privadas
	function crearEtiqueta()
	{
		if($('_ajax_label'))
			label = $('_ajax_label')
		else{
			label = document.createElement('SPAN')
			label.style.cssText = 'position: absolute; right:0px; padding: 2px 20px 2px 20px; font-family: arial; font-size: 13px; font-weight: bold; z-index:'+((1000*indicemodal)+2)
			label.id = '_ajax_label'
			document.body.appendChild(label)
		}

		label.style.top = getScrollY()+'px'
	}
	
	function getScrollY()
	{
		var scrollY = 0
		
		if ( document.documentElement && document.documentElement.scrollTop )		
		{
			scrollY = document.documentElement.scrollTop
		}else if ( document.body && document.body.scrollTop ){
			scrollY = document.body.scrollTop
		}else if ( window.pageYOffset ){
			scrollY = window.pageYOffset
		}else if ( window.scrollY ){
			scrollY = window.scrollY
		}
		return scrollY
	}
	
	function $(id){return document.getElementById(id)}
	
	function $_(name){return document.getElementsByTagName(name)}
	
	self = this
	//Fin de la clase.
}

// Funcion que monta un layer básico para sacar avisos en las validaciones.
function $aviso(texto,colorTrans)
{
	if (colorTrans)
		var miLayer = new Clayer(texto, 344, 120, colorTrans)
	else
		var miLayer = new Clayer(texto, 344, 120)
	var id_layer = miLayer.id_layer
	var indicemodal = miLayer.getIndiceModal()
	miLayer.ConTopAndBottom()
	miLayer.setTitulo('Aviso')
	miLayer.setVisibleAspa()
	miLayer.setModeBClose(0)
	miLayer.setActionDefault('$ocultarAviso('+id_layer+')')
	miLayer.open()
} 

// Funcion que saca un layer de loading...
var miLayerLoading = new Clayer('', 344, 120)
function $Loading(texto,texto_espere,colorTrans,url_image)
{
	if (url_image)
		var ruta = url_image
	else
		var ruta = 'images/loading.gif'
	if (texto == '')
		texto = 'CARGANDO'
	var loading = '<div style="width:552px; margin: 0 auto">'+
	'<div style="padding:5px 0; width:540px; text-align:center; font-size:14px; color:#e83b45;"><img src="' + ruta + '" /></div>'+
	'<div style="padding:5px 0; width:540px; text-align:center; font-size:14px; color:##e83b45;">' + texto + '<BR />' + ((texto_espere)?texto_espere:'ESPERE UN MOMENTO POR FAVOR...') + '</div>'+
	'</div>'
	
	if (colorTrans)
		miLayerLoading.setColorTrans = colorTrans
	miLayerLoading.SinTopAndBottom();
	miLayerLoading.setMensaje(loading);
	miLayerLoading.setAncho(560)
	miLayerLoading.setModeBClose(2);
	miLayerLoading.open();
}

function $CloseLoading()
{
	miLayerLoading.Cerrar()	
}

// Funcion que monta el label de error
function $LError(msg)
{
	var miLabel = new Clayer('',0,0)
	miLabel.errorLabel(msg)
}

// Funcion que monta el label tipo google
function $LAviso(msg)
{
	var miLabel = new Clayer('',0,0)
	miLabel.showLabel(msg)
}

// Funcion que saca un label verde que se cierra solo a los 2 segundos
function $Label(msg)
{
	var miLabel = new Clayer('',0,0)
	miLabel.hideLabel(msg)
}

// Funciones externas a la clase que buscan el layer cuando se pierde el objeto una vez pintado
// Esto es necesario en los casos de $aviso y cuando sale la barra de titulo por defecto.
function $ocultarAviso(id)
{
		if(document.getElementById('_ajax_modalcontent_'+id+'_'+indicemodal)){
			document.body.removeChild(document.getElementById('_ajax_modalcontent_'+id+'_'+indicemodal))
			indicemodal--
			document.body.removeChild(document.getElementById('_ajax_frame_trans_'+indicemodal))
			NLayer[indicemodal] = null
			indicemodal--
		}

		if(document.getElementById('_ajax_modalcontent_'+id+'_'+indicemodal))
			document.getElementById('_ajax_modalcontent_'+id+'_'+indicemodal).style.top = getScrollY()
}

function getScrollY()
{
	var scrollY = 0
	
	if ( document.documentElement && document.documentElement.scrollTop ){
		scrollY = document.documentElement.scrollTop
	}else if ( document.body && document.body.scrollTop ){
		scrollY = document.body.scrollTop
	}else if ( window.pageYOffset ){
		scrollY = window.pageYOffset
	}else if ( window.scrollY ){
		scrollY = window.scrollY
	}
	
	return scrollY
}