String.prototype.trim= function() {return this.replace(/(^\s*)|(\s*$)/g,"");}
String.prototype.nospaces= function() {return this.replace(/(\s*)/g,"");}


function URLDecode(encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}
var tmpMarkerState = new Array();
var menustate;
var submenustate;
var menuTabActived = 1;
var Session = new Class({
						Implements:Options,
						options:{
							initialized:0,
							text:''
						},
						initialize:function(options){
							this.setOptions(options);
						},
						start:function(callback){
							this.initialized = 1;
							eval(callback);
						},
						stop:function(){
							this.initialized = 0;
						},
						status:function(){
							return this.initialized;
						},
						info:function(){
							if(this.initialized){
								this.text = 'Sesi&oacute; Iniciada';
							}else{
								this.text = 'Sesi&oacute; No Iniciada';
							}
							return this.text;
						},
						set:function(option,value){
							this[option] = value;
						},
						get:function(option){
							return this[option];
						}
						});
var sssn = new Session();
var usrFavoritos = new Array();
var myLightBox = null;
var myPageContent = null;
var lightBoxActive = false;
var lbCont;
var photoLargeArray;
var photoLarge,photoLargeOld;
var menu;
var slider = false;
var sliderInterval;
var mouseX = 0;
var myCount = 0;
var tabInfoBox;
var company_id;
var option_id;
var fichaOpen = 0;
var micuenta = 'ver';
//variables para el tamaño del contenedor
var size;
var contWidth;
var contHeight;

window.addEvent('domready', windowLoad);

function windowLoad(){
	
	size = $('container').getSize();
	contWidth = getWidth() + 'px';
	contHeight = getHeight() +'px';//size.y + 'px';
	//Cookie para recordar el estado de cada boton
	submenustate = new Hash.Cookie('submenustate');
	menustate = new Hash.Cookie('menustate');
	var myMenu = new MenuMatic({ orientation:'vertical' });
	var values = '';
	
	getSubmenuTop();
	
	var navCount = 0;
	$('nav').getElements('li').each(function(obj)
	{
		//eventos
		obj.addEvent('click',menuClick);
		//objeto checkbox
		var checkbox = obj.getElement('a').getElement('div').getFirst('img');
		//id del checkbox
		var i = checkbox.getProperty('id');		
		var parts = i.split('_');
		//obtengo el estado del boton
		var state = menustate.get(parts[0]);
		//le aplico el estado
		if(state == 'checked'){
			checkbox.setProperty('src','webimg/checked.png');
		}else{
			checkbox.setProperty('src','webimg/unchecked.png');
		}
		//obj.setStyles({'display':'block','width':'220px'});
		//obj.getElement('a').setStyles({'display':'block','width':'220px'});
		//var number = obj.getProperty('id');
		
		/*var icon = new Element('img',{'styles':{'float':'right','width':'29px','height':'24px'},'src':'webimg/category/menu_icon_'+number+'.png','border':'0','align':'absmiddle'});
		icon.inject(obj.getElement('a'));*/
		navCount++;
	});
	//submenu
	$$('.subnav').each(function(subobj)
	{
		subobj.getElements('li').each(function(li)
		{
			li.addEvent('click',subMenuClick);
			//objeto checkbox
			var subcheckbox = li.getElement('a').getElement('div').getFirst('img');
			//id del checkbox
			var j = subcheckbox.getProperty('id');
			var parts = j.split('_');
			//obtengo el estado del boton
			var substate = submenustate.get(parts[0]);
			//le aplico el estado
			if(substate == 'checked'){
				subcheckbox.setProperty('src','webimg/checked.png');
			}else{
				subcheckbox.setProperty('src','webimg/unchecked.png');
			}
		});
	});
	//evento click de los botones del menu principal
	function menuClick()
	{
		//objeto checkbox
		var checkbox = this.getElement('a').getElement('div').getFirst('img');
		//id del checkbox
		var alt = checkbox.getProperty('id');
		var parts = alt.split('_');
		var id = parts[0];
		var act = parts[1];	
		if(act == 1) return false;

		//si el checkbox esta activo...
		if(checkbox.getProperty('src') == 'webimg/checked.png'){
			//lo desactivo
			checkbox.setProperty('src','webimg/unchecked.png');
			//elimino el estado del boton
			menustate.erase(id);
			checkSubMenuStatus(id,this);
			resetSearchCompany('menu',id);
		}else{						
			//guardo el estado del boton
			menustate.set(id,'checked');
			if(act == '0'){
				//lo activo
				checkbox.setProperty('src','webimg/checked.png');				
				searchCompany('empresas',id);
			}
		}
	}
		
	//evento click de los botones del submenu principal
	function subMenuClick()
	{
		menuTop(0);
		//objeto checkbox
		var subcheckbox = this.getElement('a').getElement('div').getFirst('img');
		//id del checkbox
		var k = subcheckbox.getProperty('id');
		var parts = k.split('_');
		var id = parts[0];
		var act = parts[1];
		
		if(act == 1) return false;
		
		//si el checkbox esta activo...
		if(subcheckbox.getProperty('src') == 'webimg/checked.png'){
			//lo desactivo
			subcheckbox.setProperty('src','webimg/unchecked.png');
			//elimino el estado del boton
			submenustate.erase(id);
			resetSearchCompany('submenu',id);
		}else{			
			//lo activo
			subcheckbox.setProperty('src','webimg/checked.png');
			//guardo el estado del boton
			submenustate.set(id,'checked');
			searchCompany('empresas',id);
			/*if(markerFromObject){
				map.clearOverlays();
			}*/
		}
		checkMenuStatus(id,this);
		if($('tabListado').getProperty('class') == 'tabMapOn'){
			mapTab(2);
		}
	}
	
	//accion para deshabilitar el checkbox en un boton del menu principal
	//verifica que ningun elemento del submenu quede checkeado
	function checkSubMenuStatus(id,obj)
	{
		var mid = id;
		$$('.subnav').each(function(subobj)
		{
			subobj.getElements('li').each(function(li)
			{
				var subcheckbox = li.getElement('a').getElement('div').getFirst('img');
				//id del checkbox
				var j = subcheckbox.getProperty('id');
				
				var parts = j.split('_');
				
				var parent_id = parts[0];
				
				if(mid == parent_id)
				{					
					if(subcheckbox.getProperty('src') == 'webimg/checked.png')
					{
						subcheckbox.setProperty('src','webimg/unchecked.png');
						//elimino el estado del boton
						menustate.erase(j);
					}
				}
				
			});
		});
	}
	
	//accion para habilitar el checkbox en un boton del submenu principal
	//verifica que el menu quede checkeado si no lo estaba
	var pathof;
	var paths = new Array();
	function checkMenuStatus(id,subobj)
	{
		pathof = getPathOf(id);
		paths = pathof.split(',');		
		var level = paths.length-1;		
		
		checkPrevLevel(level);
	}
	
	function checkPrevLevel(level)
	{
		
		if(level < 0) return false;		
		
		var id = paths[level];
		level--;
		
		var checkedChilds = getCheckedChilds(id);
		
		var object = getObjectById(id);
		
		var img = object.getProperty('src');
		
		if(!checkedChilds && img == 'webimg/checked.png')
		{
			object.setProperty('src','webimg/unchecked.png');
			if(level == -1){
				menustate.erase(id);
			}else{
				submenustate.erase(id);
			}
		}else{
			object.setProperty('src','webimg/checked.png');
			if(level == -1){
				menustate.set(id,'checked');
			}else{
				submenustate.set(id,'checked');
			}
		}
		checkPrevLevel(level);
	}
	
	var info = '';
	function getCheckedChilds(id)
	{
		var childs = 0;
		//cada elemento del path
		//proceso unicamente los elementos guardados
		var treelen = tree[id].length;
		for(var i = 0; i < treelen; i++)
		{
			if(tree[id][i]){
				var object = getObjectById(i);
				var objid = object.getProperty('id');
				var objimg = object.getProperty('src');
				childs += (objimg == 'webimg/checked.png') ? 1 : 0;
			}
		}
		return childs;
		//alert(tree[id]);
	}
	
	function getObjectById(id)
	{
		var id0 = id+'_0';
		var id1 = id+'_1';
		return ($(id0)) ? $(id0) : $(id1);
	}
	
	function getPathOf(id)
	{	
		for(var k in tree)
		{
			if(tree[k][id])
			{
				var parent = getPathOf(k);
				var keys = (parent && parent >0) ? parent +','+ k : k;
				return keys ;
			}
		}
		return false;
	}
	
	function equalIds(id,array)
	{
		for(var k in array)
			if(array[k] == id) return true;
		return false;
	}
	
	contResize();
	
}

window.addEvent('resize',function(e){
	contResize();
});

//redimensionar el tamanyo del contenido
function contResize()
{		
	var ciHeight = parseInt($("colizq").getStyle('height'));
	var cdHeight = parseInt($("colder").getStyle('height'));
	var cHeight = (ciHeight > cdHeight) ? ciHeight : cdHeight;
	$("content").setStyle('min-height',(cHeight+20)+'px');
	
}

//acho de la pantalla
function getWidth()
{
	if (this.khtml) return this.innerWidth;
	if (this.opera || this.gecko || this.ie6) return document.body.clientWidth;
	return document.documentElement.clientWidth;
}

//alto de la pantalla
function getHeight()
{
	if (this.khtml) return this.innerHeight;
	if (this.opera || this.gecko || this.ie6) return document.body.clientHeight;
	return document.documentElement.clientHeight;
}

//alto de la pantalla
function getSubmenuTop()
{
	var smTop = 0;
	var smLeft = 0;
	var navegador = navigator.appName 
	if (navegador == "Microsoft Internet Explorer")
	{ 
		smTop = 268;
		smLeft = 37;
	}
	$('subMenusContainer').setStyles({'top':smTop+'px','left':smLeft+'px'});
}

function resetMenu()
{
	if(!menustate){ return false;}
	$('nav').getElements('li').each(function(obj)
	{
		//objeto checkbox
		var checkbox = obj.getElement('a').getElement('div').getFirst('img');
		var j = checkbox.getProperty('id');
		var parts = j.split('_');
		menustate.erase(parts[0]);
		checkbox.setProperty('src','webimg/unchecked.png');
	});
	//submenu
	$$('.subnav').each(function(subobj)
	{
		subobj.getElements('li').each(function(li)
		{
			var subcheckbox = li.getElement('a').getElement('div').getFirst('img');
			var j = subcheckbox.getProperty('id');
			var parts = j.split('_');
			submenustate.erase(parts[0]);
			subcheckbox.setProperty('src','webimg/unchecked.png');
		});
	});
	
}

//pestañas del menú principal
function menuTab(id)
{
	menuTabActived = id;
	var m = 'block';
	var f = 'none';
	var c = 'none';
	switch(id)
	{
		case 2:
			m = 'none'; f = 'block'; c = 'none'; var li = 1;
		break;
		case 3:
			m = 'none'; f = 'none'; c = 'block'; var li = 2;
			if(micuenta == 'editar')
			{
				loadMiCuenta();
			}
		break;
		default:
			m = 'block'; f = 'none'; c = 'none'; var li = 0;
		break;
	}
	var clicked = $('menuNav').getElements('li').each(function(obj,j){
		if(j == li)//pestanna activada
			menuTabStatus(obj,1,j);
		else//pestanna desactivada
			menuTabStatus(obj,0,(j+1));
	});
	$('menu').setStyle('display',m);
	$('favoritos').setStyle('display',f);
	$('micuenta').setStyle('display',c);	
}

//estados de las pestañas del menú principal
function menuTabStatus(element,status,id)
{
	var button = element.getElement('div');
	if(status){
		element.getFirst('img').setProperty('src','./webimg/menu_btn_01_left.jpg');
		element.getLast('img').setProperty('src','./webimg/menu_btn_01_right.jpg');
		element.setStyles({'background-image':'url(./webimg/menu_btn_01_mid.jpg)','color':'#FFF'});
		button.setProperties({'class':'menuTabLinkOn','onclick':'void(0)'});
	}else{
		element.getFirst('img').setProperty('src','./webimg/menu_btn_02_left.jpg');
		element.getLast('img').setProperty('src','./webimg/menu_btn_02_right.jpg');
		element.setStyles({'background-image':'url(./webimg/menu_btn_02_mid.jpg)','color':'#999'});
		button.setProperty('class','menuTabLinkOff');
		if(sssn.status()){//si esta logueado
			button.setProperty('onclick','menuTab('+id+')');
		}else{
			button.setProperty('onclick','login(); menuTabActived=2;');
		}
	}
}

//carga de los datos del usuario logueado
function loadUserData()
{
	var toUrl = 'index.php';
	var favBox = $('favoritosCont');
	favBox.set('html','cargando datos...');
	var rqFavorito = new Request({
							  	method:'get',
								url:toUrl,
								onSuccess:function(text,xml)
								{
									var parts = text.split('##JS##');
									favBox.set('html',parts[0]);
									eval(parts[1]);
									setTimeout('menuFavoritos()',100);
								}
							  }).send('option=1001');
	loadMiCuenta();
}

function loadMiCuenta(){
	var toUrl = 'index.php';
	var uid = new Date();
	var mcBox = $('micuentaCont');
	mcBox.set('html','cargando datos...');
	
	var rqMiCuenta = new Request({
							  	method:'get',
								url:toUrl,
								onSuccess:function(text,xml)
								{
									mcBox.set('html',text);
								}								 
							}).send('option=1002&uid=' + uid);	
}

function removeUserData()
{
	var favBox = $('favoritosCont');
	favBox.set('html','');
	var mcBox = $('micuentaCont');
	mcBox.set('html','');
}

//evento para el menu de favoritos
function menuFavoritos()
{
	for(var i=0; i < usrFavoritos.length; i++)
	{
		var data = usrFavoritos[i].substr(2).split('#d#');
		
		var newMark = {
						'id':i,
						'icon':data[0],
						'empresa_id':data[1],
						'nombre':data[2],
						'direccion':data[3],
						'barrio':data[4],
						'cp':data[5],
						'telefono':data[6],
						'email':data[7],
						'lat':data[8],
						'lng':data[9],
						'rubro_id':data[10],
						'prov_id':data[11],
						'loc_id':data[12],
						'descripcion':data[13],
						'logo':data[14],
						'usuario_id':data[15],
						'fecha':data[16],
						'usuario':data[17],
						'votoWidth':data[20]
					  }
		createMPfromObject(newMark)
	}
	$$('.favoritosRow').each(function(obj)
	{
		var id = obj.getElement('a').getProperty('href');
		obj.getElement('a').setProperty('href','void(0);');
		obj.addEvent('mouseover',function()
		{
			this.addClass('favoritosRowOn');
		});
		obj.addEvent('mouseout',function()
		{
			this.removeClass('favoritosRowOn');
		});
		obj.addEvent('click',function()
		{
			map.clearOverlays();
			resetMenu();
			displayMarkerFromObject(id);
		});
	});
}

function editUserData(){
	micuenta = 'editar';
	var toUrl = 'index.php';
	var mcBox = $('micuentaCont');
	mcBox.set('html','cargando datos...');
	var uid = new Date();
	
	var rqMiCuenta = new Request({
							  	method:'get',
								url:toUrl,
								onSuccess:function(text,xml)
								{
									mcBox.set('html',text);
								}								 
							}).send('option=1002&accn=form&uid=' + uid);
	
}

function saveUserData(){
	var toUrl = 'index.php?option=1002';
	if($('nombre').getProperty('value') == ''){
		textInfoBox('<span class="txtYellow">Complete el campo "Nombre".</span>');
		$('nombre').focus();
		return false;				
	}else if($('apellido').getProperty('value') == ''){
		textInfoBox('<span class="txtYellow">Complete el campo "Apellido".</span>');
		$('apellido').focus();
		return false;				
	}else if($('apellido').getProperty('value') == ''){
		textInfoBox('<span class="txtYellow">Complete el campo "Apellido".</span>');
		$('apellido').focus();
		return false;				
	}else if($('direccion').getProperty('value') == ''){
		textInfoBox('<span class="txtYellow">Complete el campo "Direcci&oacute;n".</span>');
		$('direccion').focus();
		return false;
	}else if($('email').getProperty('value') == ''){
		textInfoBox('<span class="txtYellow">Complete el campo "E-mail".</span>');
		$('email').focus();
		return false;
	}else if(!checkAllEmails($('email').getProperty('value'))){
		textInfoBox('<span class="txtYellow">El E-mail ingresado es incorrecto.</span>');
		return false;
	}else if($('usuario').getProperty('value') == ''){
		textInfoBox('<span class="txtYellow">Complete el campo "Usuario"</span>');
		$('usuario').focus();
	}else if($('clave').getProperty('value') != ''){
		if($('clave2').getProperty('value') == ''){
			textInfoBox('<span class="txtYellow">Complete el campo "Repetir Clave"</span>');
			$('clave2').focus();
			return false;			
		}else if($('clave').getProperty('value') != $('clave2').getProperty('value')){
			textInfoBox('<span class="txtYellow">Las claves no coinciden.</span>');
			return false;				
		}
	}
	var request = new Request.HTML({
							  	method:'post',
								url:toUrl,
								onComplete:function(tree, elements, html, javascript)
								{
									var text;
									if(html == 'ok')
									{
										text = 'Cuenta modificada...';
										var form = $('formMiCuenta');
										form.setProperties({'action':'index.php','target':'iframeOculto','method':'post'});
										
										$('option').value = '1009';
										var avatar = form.getElement('input#avatar').value;										
										if(avatar && avatar.test(/\.(gif|jpg)$/i)){
											if(!iFrame){
												iFrame = new Element('iframe',{'id':'iframeOculto','name':'iframeOculto','width':'0','height':'0','frameborder':'0'});
												iFrame.inject(document.body,'top');
											}
											
											form.submit();
										}
									}else{
										text = '<span class="txtYellow">Proceso fallido</span>';
										//text = '<span class="txtYellow">'+html+'</span>';
									}
									textInfoBox(text);
									setTimeout("loadMiCuenta();",1000);
								}
							  }).post($('formMiCuenta'));
}
function sendConsult()
{
	var form = $('formConsultas');
	
	var nombre = form.getElement('input#nombre').value.trim();
	var apellido = form.getElement('input#apellido').value.trim();
	var email = form.getElement('input#email').value.trim();
	var asunto = form.getElement('input#asunto').value.trim();
	var consulta = form.getElement('textarea#consulta').value.trim();
	
	if(!nombre || !apellido || !email || !asunto || !consulta){
		alert('complete todos los campos del formulario');
		return false;
	}
	if(!emailCheck(email))
	{
		alert('El E-mail ingresado es incorrecto.');
		return false;
	}
	
	var request = new Request.HTML({
								method:'post',
								url:'index.php?option=1013',
								onComplete:function(tree, elements, html, javascript)
								{
									var text;
									if(html == 'ok')
									{
										text = 'Su consulta ha sido enviada.<br />Gracias por contactarnos.';
										setTimeout("void(menuTop(5));",1000);
									}else{
										text = '<span class="txtYellow">Su consulta no ha sido enviada.<br />Int&eacute;ntelo nuevamente.</span>' + html;
									}
									$('formConsultasInfo').set('html','<p>'+text+'</p>');
								}
							  }).post(form);
}

var nPageList = 1;
//pestañas listado - mapa
function mapTab(id)
{
	var ctl = 'tabMapOff';
	var ctm = 'tabMapOn';
	switch(id)
	{
		case 2:
			ctl = 'tabMapOn';
			ctm = 'tabMapOff';
			var totalKeys = new Array();
			var stringKeys = '';
			var keys = menustate.getKeys().toString().split(',');
			var subkeys = submenustate.getKeys().toString().split(',');
			
			for(var k = 0; k < keys.length; k++)
			{
				totalKeys[k] = keys[k];
				var parts = keys[k].split('_');
				if(parts[0] == 1000){
					stringKeys += keys[k] + ',';
				}
			}
			
			for(var j = 0; j < subkeys.length; j++)
			{
				totalKeys[k+j] = subkeys[j];
				stringKeys += subkeys[j] + ',';
			}
			var regs = 0;
			if($('listMarks')){
				regs = $('listMarks').getElements('div.listMarkRow').length;
			}
			
			if(!regs){
				var uid = new Date();
				getPage('index.php?option=112&id='+stringKeys+'&nPage='+nPageList+'&uid='+uid,'listado');
			}else{
				$('map_canvas').setStyles({'display':'block','width':'317px'});
				$('page_canvas').setStyles({'display':'block','width':'350px','overflow':'auto'});
			}
			if(!fichaOpen){
				$('page_canvas').setStyle('height','422px');
				$('content').setStyle('min-height','608px');
				contResize();
			}
		break;
		default:
			ctl = 'tabMapOff';
			ctm = 'tabMapOn';
			$('map_canvas').setStyles({'display':'block','width':'672px'});
			$('page_canvas').setStyles({'display':'none','width':'672px'});
			contResize();
		break;
	}
	$('tabListado').setProperty('class',ctl);
	$('tabMapa').setProperty('class',ctm);
}

function listGoToPage(accion){
	if(accion=='next'){
		nPageList++;
	}else if(accion=='prev'){
		nPageList--;
	}else{
		nPageList = accion;
	}
	mapTab(2);
}

//logueo
function login()
{
	displayLightBox();
	displayLoginBox();	
}
function testing()
{
	alert(myLightBox);
}
//logueo
function signup()
{
	displayLightBox();
	displaySignupBox();
}

function displayLightBox()
{
	hideLightBox();
	var lbBackground = new Element('div',{'id':'lightbox_background','styles':{'position':'absolute','width':'100%','height':'100%','background-color':'#000','z-index':'1','opacity':'0.7'}});
	
	myLightBox = new Element('div',{'id':'lightbox','styles':{'position':'fixed','width':contWidth,'height':contHeight,'z-index':'10000'}});
	
	lbBackground.inject(myLightBox);
}

function hideLightBox()
{
	if(myLightBox){
		myLightBox.destroy();
	}
	myLightBox = null;
}
function displayLoginBox()
{
	var tableWidth = 426;
	var tableHeight = 350;
	var tableLeft = parseInt(getWidth()/2) - (tableWidth/2);
	var tableTop = parseInt(getHeight()/2) - (tableHeight/2);
		
	cont = new Element('div',{'id':'lightbox_container','styles':{'position':'fixed','width': tableWidth+'px','height': tableHeight+'px','z-index':'2','top': tableTop +'px','left': tableLeft +'px'}});
	
	var uid = new Date();
	page = 'index.php?option=105&uid='+uid;
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
		cont.set('html',html);
		lbCont = cont;
		lbCont.inject(myLightBox);
		myLightBox.inject($(document.body),'top');
		$('userLgn').focus();
	}}).get(page);
}

function displaySignupBox()
{
	var tableWidth = 426;
	var tableHeight = 550;
	var tableLeft = parseInt(getWidth()/2) - (tableWidth/2);
	var tableTop = parseInt(getHeight()/2) - (tableHeight/2);	
	
	var cont = new Element('div',{'id':'lightbox_container','styles':{'position':'fixed','width': tableWidth+'px','height': tableHeight+'px','z-index':'2','top': tableTop +'px','left': tableLeft +'px'}});	
	var uid = new Date();
	page = 'index.php?option=106&uid='+uid;
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
		//buildMyPage(html);
		cont.set('html',html);
		lbCont = cont;
		lbCont.inject(myLightBox);
		myLightBox.inject($(document.body),'top');
		$('nombre').focus();
	 }}).get(page);
}

//servicios
function servicios(id,option)
{
	if($(id))
	{
		if($(id).getStyle('display') == 'none'){
			$(id).setStyle('display','block');
		}else{
			$(id).setStyle('display','none');										
			contResize();
		}
		if($(id).get('html') == ''){
			var request = new Request({url:'templates/html/es/menu_'+id+'.html',
											 onSuccess:function(text,xml){
													$(id).set('html',text);													
													contResize();
												 }
											 }).send();
		}else{												
			contResize();
		}	
		contResize();
	}else{
		alert(id);
	}
	resetServicios(id);
}

function resetServicios(id)
{
	$('menuServicios').getElement('ul').getElements('li').each(function(obj){
		var subOption = obj.getElement('div');
		if(subOption){
			if(subOption.getStyle('display') == 'block' && id != subOption.get('id'))
				subOption.setStyle('display','none');
		}
	});
}

function serviciosForm(id)
{
	var infoBox = $(id + 'info');
	infoBox.set('html','Cargando...');
	var form = $('form' + id);
	var inputs = form.length;
	var vars = '';
	var uid = new Date();
	for(var k=0; k < inputs; k++){
		if(form[k].type == 'radio' || form[k].type == 'checkbox'){
			if(form[k].checked == true)
				vars += '&'+form[k].id+'='+form[k].value;
		}else{
			vars += '&'+form[k].id+'='+form[k].value;
		}
	}
	vars += '&uid='+uid;
	var srch = {file:'index.php?option=1005&id='+id+vars,id:id,closeBox:infoBox};
	mapTab(1);
	if(id == 'transporteurbano'){
		GPolylines(srch);
	}else{
		GMarkerGroups(srch);
	}
}

function closeUp(seccion)
{
	switch(seccion)
	{
		case 'lightbox': hideLightBox(); break;
		case 'lightbox_gallery': hideLightBox(); break;
		case 'lightbox_uploadphoto': deleteUploadedTemp(); break;
	}
}

function loginUp(seccion)
{
	var toUrl;
	var infoBox;
	switch(seccion)
	{
		case 'lightbox':
			toUrl = 'index.php?option=1000';
			infoBox = $('lightbox_info');
		break;
	}
	infoBox.set('html','Enviando solicitud...');
	var request = new Request.HTML({
							  	method:'post',
								url:toUrl,
								onComplete:function(tree, elements, html, javascript)
								{
									var text;
									var rs = html.split('=');
									var vs = rs[1].split(';');
									if(rs[0] == 'ok')
									{
										sssn.set('usr_id',vs[0]);
										sssn.set('usr_usuario',vs[1]);
										text = 'Iniciando la Sesi&oacute;n...';
										sssn.start('fullSystem()');
										setTimeout("closeUp('lightbox');",1000);
									}else{
										text = '<span class="txtYellow">Sus datos son incorrectos.</span>';
									}
									infoBox.set('html',text);
								}
							  }).post($('formLogin'));
}

function logoutUp()
{
	var toUrl = 'index.php';
	var rqFavorito = new Request({
							  	method:'get',
								url:toUrl,
								onSuccess:function(text,xml)
								{
									simpleSystem();
								}
							  }).send('option=1003');
}
var iFrame;
function signUp(seccion)
{
	var toUrl;
	var infoBox;
	switch(seccion)
	{
		case 'lightbox':
			toUrl = 'index.php?option=1004';
			infoBox = $('lightbox_info');
		break;
	}
	infoBox.set('html','Enviando solicitud...');
	var request = new Request.HTML({
	method:'post',
	url:toUrl,
	onComplete:function(tree, elements, html, javascript){
		var text;
		if(html.match(/ok/)){
			var form = $('formSignup');
			form.setProperties({'action':'index.php','target':'iframeOculto','method':'post'});
			
			var parts = html.split(' ');
			$('insert_id').value = parts[1];
			$('option').value = '1009';
			if(!iFrame){
				iFrame = new Element('iframe',{'id':'iframeOculto','name':'iframeOculto','width':'0','height':'0','frameborder':'500'});
				iFrame.inject(document.body,'top');
			}
			
			form.submit();
			
			var newlbCont = new Element('div',{'id':'lightbox_container','styles':{'color':'#666','width': '100%','height': '100px','margin-top':'50px','text-align':'center'},'html':'<p>Su cuenta ha sido creada exitosamente.<br />Para ingresar a su cuenta inicie sesi&oacute;n</p>'});
			newlbCont.replaces($('tableForm'));
			setTimeout("closeUp('lightbox');",1000);
			return false;
		}else if(html == 'ko'){
			text = 'No pudimos procesar sus datos de registro.<br />Int&eacute;ntelo nuevamente.';
		}else if(html == 'exists'){
			text = 'La direcci&oacute;n de E-mail ingresada, fu&eacute; utilizada anteriormente para crear un usuario.';
		}else{
			text = 'Complete los datos solicitados.';
		}
		infoBox.set('html','<span class="txtYellow">'+text+'</span>');
	}
  }).post($('formSignup'));
}

function fullSystem()
{
	if(!sssn.status()) return false;
	menuTab(menuTabActived);
	loadUserData();
	var btnLog = $('headerBtns').getLast('a');
	btnLog.setProperty('href','javascript:logoutUp()');
	btnLog.getElement('img').setProperties({'src':'webimg/btn_01_cerrar_sesion.jpg','alt':'Cerrar Sesión'});
	elementsSession();
	if(!$('headerMsg').get('html')){
		$('headerMsg').set('html','&iexcl;Bienvenido ' + sssn.get('usr_usuario') +'!');
	}	
	var btnMarca = $('headerBottom').getLast('a');
	btnMarca.setProperty('href','javascript:void(GNewMark());');
	if($('formComentario')){
		var formCom = $('formComentario');
		formCom.getLast('input').setProperty('onclick','sendComment();');
		var id = $('btnAddFav').getProperty('rel');
		$('btnAddFav').setProperty('href','javascript:void(addFavorites('+id+'));');
		$('btns_photo').getFirst('a').setProperty('href','javascript:void(uploadPhoto('+id+','+sssn.get('usr_id')+'));');
	}
}

function simpleSystem()
{
	sssn.stop();
	menuTab(1);
	removeUserData();
	$('headerMsg').set('html','');
	var btnLog = $('headerBtns').getLast('a');
	btnLog.setProperty('href','javascript:login()');
	btnLog.getElement('img').setProperties({'src':'webimg/btn_01_iniciar_sesion.jpg','alt':'Iniciar Sesión'});
	var btnMarca = $('headerBottom').getLast('a');
	btnMarca.setProperty('href','javascript:void(login());');
	elementsSession();
	if($('formComentario')){
		var formCom = $('formComentario');
		formCom.getLast('input').setProperty('onclick','login();');
		$('btnAddFav').setProperty('href','javascript:void(login());');
		$('btns_photo').getFirst('a').setProperty('href','javascript:void(login());');
	}
}

function elementsSession()
{
	var styles = [];
	if(sssn.status())
	{
		styles = {'color':'#FFF','cursor':'pointer','text-decoration':'none'};
	}else{
		styles = {'color':'#989898','cursor':'default','text-decoration':'none'};
	}
	if($('detail_canvas').getStyle('display') == 'block'){
		$$('.session_link').each(function(obj){
			var img = obj.getElement('img');
			var parts = img.get('src').split('_');
			var last = parts[parts.length-1].split('.');
			ext = '.'+last.pop();
			if(obj.getProperty('href'))
			{
				obj.erase('href');
				parts[parts.length-1] = last.shift();
				parts[parts.length] = 'off'+ext;
			}else{
				parts.pop();
				parts[parts.length-1] = parts[parts.length-1]+ext;
				var id = obj.getProperty('alt');
				obj.setProperty('href','javascript:uploadPhoto('+id+')');				
			}
			src = parts.join('_');
			img.set('src',src);
			obj.setStyles(styles);
		});
		var btnComent = $$('.session_button');
		if(btnComent.getProperty('value') == '   Publicar   ')
		{
			btnComent.setProperty('value','Inicie sesi&oacuten para publicar un comentario');
			btnComent.setProperty('onclick','login();');
		}else{
			btnComent.setProperty('value','   Publicar   ');
			btnComent.setProperty('onclick','sendComment();');			
		}
	}
}

function getPage(page,type)
{
	var type = type;
	var uid = new Date();
	$('page_canvas').set('html','');
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
																buildMyPage(html,type);
															 }}).get(page);
}

function addFavorites(empresa_id){
	var uid = new Date();
	getPage('index.php?option=1010&empresa_id='+empresa_id+'&uid='+uid,'favorito');
}

//borrar un registro del listado de favoritos
function deleteFavorito(favorito_id){
	var uid = new Date();
	getPage('index.php?option=1011&favorito_id='+favorito_id+'&uid='+uid,'blank');	
}

function buildMyPage(html,type)
{
	if(type == 'favorito'){
		loadUserData();
		return false;
	}
	$('page_canvas').set('html',html);
	switch(type)
	{
		case 'listado':
			$('map_canvas').setStyles({'display':'block','width':'317px'});
			$('page_canvas').setStyles({'display':'block','width':'350px','overflow':'auto'});
		break;
		case 'blank':
			loadUserData();
		break;
		default:
			$('map_canvas').setStyle('display','none');
			$('page_canvas').setStyles({'display':'block','width':'672px','overflow':'hidden'});
			//mapTab(1);
		break;
	}
}

function menuTop(number)
{
	var myPage;
	var pch = '422px';
	var ch = '608px';
	switch(number)
	{
		case 0:
			$('page_canvas').set('html','');
			$('map_canvas').setStyle('display','block');
			$('page_canvas').setStyle('display','none');
			$('page_canvas').setStyle('height',pch);
			$('content').setStyle('min-height',ch);
			mapTab(1);
			if(!fichaOpen){
				homeUtils(true);
			}
			return false;
		break;
		case 1: myPage = 'templates/html/es/mp_que_es_guimap.html'; homeUtils(true); break;
		case 2: myPage = 'templates/html/es/mp_como_participar.html'; homeUtils(true); break;
		case 3: myPage = 'templates/html/es/mp_faqs.html'; pch = '950px'; ch = '1150px'; homeUtils(false);  break;
		case 4: signup(); return false; break;
		case 5: myPage = 'templates/html/es/mp_consultas.html'; homeUtils(true); break;
	}
	$('detail_canvas').set('html','');
	$('detail_canvas').setStyle('display','none');
	$('page_canvas').setStyle('height',pch);
	$('content').setStyle('min-height',ch);
	fichaOpen = 0;
	getPage(myPage);
}

function homeUtils(show)
{
	if(show)
	{
		$('empresas_adsense').setStyle('display','block');
		$('adSenseDer').setStyle('display','block');
		$('adSenseIzq').setStyle('display','none');
	}else{
		$('empresas_adsense').setStyle('display','none');
		$('adSenseDer').setStyle('display','none');
		$('adSenseIzq').setStyle('display','block');
	}
}

function companyDetails(id,page)
{
	homeUtils(false);
	$('detail_canvas').setStyle('display','block');
	fichaOpen = 1;
	var id_empresa = id;
	var page = page;
	var uid = new Date();
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
																$('detail_canvas').set('html',html);
																window.location = '#topPage';
																contResize();
																if($('votoTool')) $('votoTool').destroy();
																var linkVotar = new Votar($$('.votarmarca'),{'sendToPage':'index.php?option=1008&tipo=empresa'});
																linkVotar.addEvent('onSend',function(){companyDetails(id_empresa,page);});
															 }}).get('index.php?option=103&id=' + id + '&page=' + page + '&uid='+uid);
}

function userDetails(id,page)
{
	homeUtils(false);
	$('detail_canvas').setStyle('display','block');
	fichaOpen = 1;
	var id_usuario = id;
	var page = page;
	var uid = new Date();
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
																$('detail_canvas').set('html',html);
																window.location = '#topPage';
																contResize();
																if($('votoTool')) $('votoTool').destroy();
																var linkVotar = new Votar($$('.votarmarca'),{'sendToPage':'index.php?option=1008&tipo=usuario'});
																linkVotar.addEvent('onSend',function(){userDetails(id_usuario,page);});
															 }}).get('index.php?option=111&id=' + id + '&page=' + page + '&uid='+uid);
}


function minimizeMap()
{
	$('map_canvas').setStyles({'width':250,'height':250});
}

function maximizeDetails()
{
	$('detail_canvas').setStyles({'width':417,'height':422});
}

function photoGallery(id,nInit)
{
	displayLightBox();
	displayPhotosBox(id,nInit);	
	//myLightBox.getElementById('lightbox_background').addEvent('click',function(){closeUp('lightbox_gallery');});
}

function displayPhotosBox(id,nInit)
{
	photoLargeOld = nInit;
	var tableWidth = 800;
	var tableHeight = 600;
	var tableLeft = parseInt(getWidth()/2) - (tableWidth/2);
	var tableTop = parseInt(getHeight()/2) - (tableHeight/2);
	var thumbHeight = 100;
	
	var thumbnails = $$('.thumbnail');
	
	var cont = new Element('div',{'id':'lightbox_container','styles':{'position':'fixed','width': tableWidth+'px','height': tableHeight+'px','z-index':'2','top': tableTop +'px','left': tableLeft +'px'}});
	
	var bgCont = new Element('div',{'id':'lightbox_bgcontainer','styles':{'position':'fixed','width': tableWidth+'px','height': tableHeight+'px','top': tableTop +'px','left': tableLeft +'px'}});
	
	var photoLargeCont = new Element('div',{'id':'lightbox_photolarge','styles':{'position':'absolute','width': '100px','height': '100px','top': (tableHeight/2)-(100/2)-50+'px','left': (tableWidth/2)-(100/2)+'px','background-color':'#FFF'}});	
	
	var thumbnailCont = new Element('div',{'id':'lightbox_thumbnails','styles':{'position':'absolute','width': tableWidth+'px','height': thumbHeight+'px','top': (tableHeight-thumbHeight)+'px','left': '0px','overflow':'hidden'}});
	bgCont.inject(cont);
	
	bgCont.addEvent('mouseover',function(){hidePrevNext();});
	
	var btnPrev = new Element('img',{'id':'lightbox_btnPrev','src':'webimg/prevLabel.gif','styles':{'display':'none','position':'absolute','cursor':'pointer'}});
	btnPrev.addEvent('click',function()
	{
		$(this).setStyle('display','none');
		photoLargeOld--;
		var url = 'fotos/empresas/s_'+photoLargeArray[photoLargeOld];
		loadPhotoLarge(url);	
	});
	
	var btnNext = new Element('img',{'id':'lightbox_btnNext','src':'webimg/nextLabel.gif','styles':{'display':'none','position':'absolute','cursor':'pointer'}});
	btnNext.addEvent('click',function()
	{
		$(this).setStyle('display','none');
		photoLargeOld++;
		var url = 'fotos/empresas/s_'+photoLargeArray[photoLargeOld];
		loadPhotoLarge(url);
	});
	
	//elementos para la galeria de fotos
	photoLargeCont.inject(cont);	
	thumbnailCont.inject(cont); 
	btnPrev.inject(cont);
	btnNext.inject(cont);	
	cont.inject(myLightBox);
	//carga de fotos
	loadAllPhotos(id);
	//carga de foto grande
	loadPhotoLarge(thumbnails[nInit].get('src'));
	
	//alert(id+','+nInit);
	myLightBox.inject($(document.body),'top');
}

function loadAllPhotos(id)
{
	photoLargeArray = new Array();
	var id_empresa = id;
	var myHTMLRequest = new Request.HTML({
										 onSuccess:function(tree, elements, html, javascript)
										 {
												
											var thumbnailSlider = new Element('div',{'id':'lightbox_slider','styles':{'float':'left','width':'1px','height':'100px'}});
											thumbnailSlider.addEvents({'mouseover':startSlider,'mouseout':stopSlider,'mousemove':getCoords});
											//var names = html.split(',');
											var data = html.split(';');
											var tsWidth = 0;
											//for(var k = 0; k < names.length;k++)
											for(var k = 0; k < data.length;k++)
											{
												var thisData = data[k].split(',');
												photoLargeArray[k] = thisData[0];//nombre
												tsWidth += parseInt(thisData[1])+5; //ancho
												
												var img = new Element('img',{'src':'fotos/empresas/s_'+photoLargeArray[k],'alt':k,'styles':{'float':'left','cursor':'pointer','margin-right':'5px'}});
												//img.addEvent('load',thumbLoaded);
												img.addEvent('click',thumbClick);																
												img.inject(thumbnailSlider);
											}
											if(tsWidth < 800){
												tsWidth = 805;
											}
											thumbnailSlider.setStyle('width',tsWidth+'px');
											var cont = myLightBox.getElementById('lightbox_thumbnails');											
											thumbnailSlider.inject(cont);
										 }}).get('index.php?option=104&id=' + id_empresa + '&uid'+uid);
}

function thumbClick(){
	var url = $(this).src;
	loadPhotoLarge(url);
	photoLargeOld = $(this).alt;
	hidePrevNext();	
}

function thumbLoaded()
{
	var sliderBox = myLightBox.getElementById('lightbox_slider');
	var width = parseInt(sliderBox.getStyle('width'));
	var newWidth = width+$(this).width+5;
	sliderBox.setStyle('width',newWidth + 'px');
}

function loadPhotoLarge(src)
{
	src = src.replace('empresas/s_','empresas/m_');
	if(photoLarge){
		photoLarge.destroy();
	}
	if(menu){
		menu.destroy();
	}
	photoLarge = new Element('img',{'src':src,'styles':{'margin-left':'5px','margin-top':'5px'}});
	var tmpPhotoLarge = new Asset.image(src, {id: 'myImage', title: 'myImage', onload: imageLoaded});
	photoLarge.addEvent('mousemove',phMouseMove);
}
function phMouseMove(e)
{
	 var coords = getMouseXY();										 
	 var obj1 = myLightBox.getElementById('lightbox_container');
	 var obj2 = myLightBox.getElementById('lightbox_photolarge');								 
	 var btnPrev =  myLightBox.getElementById('lightbox_btnPrev');
	 var btnNext = myLightBox.getElementById('lightbox_btnNext');								 
	 var pLargeWidth = parseInt(obj2.getStyle('width'));
	 var pLargeHeight = parseInt(obj2.getStyle('height'));										 
	 var contLeftX = parseInt(obj1.getStyle('left'));
	 var pLargeLeftX = parseInt(obj2.getStyle('left'));										 
	 var pLargeY = parseInt(obj2.getStyle('top'));									 
	 var leftX = contLeftX + pLargeLeftX;										 
	 
	 if(coords.x < (leftX + (pLargeWidth/2))){
		 btnNext.setStyle('display','none');
		 if(photoLargeOld > 0)
			 btnPrev.setStyles({'display':'block','margin-left':pLargeLeftX,'margin-top':(pLargeY+50)});
	 }else{
		 btnPrev.setStyle('display','none');
		 if(photoLargeOld < photoLargeArray.length-1)
			 btnNext.setStyles({'display':'block','margin-left':(pLargeLeftX+pLargeWidth-btnNext.width),'margin-top':(pLargeY+50)});
	 }
 
}
function imageLoaded()
{
	menu = new Element('div',{'id':'lightbox_menu','styles':{'float':'left','width': photoLarge.width +'px','height': '22px','margin':'5px 5px 0px 5px','padding':'4px 0px 4px 0px','cursor':'pointer'}});
	var menuCont = '<img src="webimg/closelabel.gif" width="66" height="22" style="float:right;" onclick="closeUp(\'lightbox_gallery\');" />'
	menu.set('html',menuCont);
	var tableWidth = 800;
	var tableHeight = 600;
	var object = myLightBox.getElementById('lightbox_photolarge');
	var myFx = Fx.Transitions.Sine.easeOut;
	
	var widthPhotoBox = new Fx.Morph(object,{
										  duration: 400,
										  transition: myFx
									  });
	widthPhotoBox.start({'width':photoLarge.width+10}).chain(function(){
		var heightPhotoBox = new Fx.Morph(object,{
											  duration: 400,
											  transition: myFx
										  }).chain(function(){
												  photoLarge.inject(object);
  												  menu.inject(object);
										  });
		 heightPhotoBox.start({'height':photoLarge.height+45});
		 var topPhotoBox = new Fx.Tween(object,{duration:400,transition: myFx});
		 topPhotoBox.start('top',(tableHeight/2)-((photoLarge.height+45)/2)-55+'px');
	 });
	
	var leftPhotoBox = new Fx.Tween(object,{duration:400,transition: myFx});
	leftPhotoBox.start('left',(tableWidth/2)-(photoLarge.width/2)-5+'px');	
}
var prevPhotoLarge = function ()
{
	$(this).setStyle('display','none');
	photoLargeOld--;
	var url = 'webimg/temp/'+photoLargeArray[photoLargeOld];
	loadPhotoLarge(url);	
}

var nextPhotoLarge = function()
{
	$(this).setStyle('display','none');
	photoLargeOld++;
	var url = 'webimg/temp/'+photoLargeArray[photoLargeOld];
	loadPhotoLarge(url);	
}

function hidePrevNext()
{
	myLightBox.getElementById('lightbox_btnNext').setStyle('display','none');
	myLightBox.getElementById('lightbox_btnPrev').setStyle('display','none');
}

function startSlider()
{
	slider = true;
	sliderInterval = setInterval("moveSlider()",100);
}

function stopSlider()
{
	slider = false;
	clearInterval(sliderInterval);
}
function getCoords()
{
	var mouse = getMouseXY();
	mouseX = mouse.x;
}
function moveSlider()
{
//	alert('moveSlider');
	if(slider)
	{
		var sdr = myLightBox.getElementById('lightbox_slider');
		var parent = sdr.getParent();
		var parent2 = parent.getParent();
		
		var pWidth = parseInt(parent.getStyle('width'));
		var middle = parseInt(pWidth) /2;
		var p2x = parseInt(parent2.getStyle('left'));		
		var width = parseInt(sdr.getStyle('width'));
		
		var dif = pWidth - width + 5;
		
		var despl = Math.round((mouseX - p2x - middle)/50)*-1;
		
		var left = sdr.getStyle('margin-left') == 'auto' ? 0 : parseInt(sdr.getStyle('margin-left')) + despl;
		
		if(left > 0)
			left = 0;
		else if(left < dif)
			left = dif;
		
		sdr.setStyle('margin-left',  + left + 'px');
		//myLightBox.getElementById('lightbox_close').set('html',mouseX +'<br />'+middle+'<br />'+p2x+'<br />'+despl+'<br />'+left+'<br />'+dif);
		//myLightBox.getElementById('lightbox_close').set('html','moveSlider ');
	}
}

function getMouseXY(e)
{
	var posx = 0;
	var posy = 0;
	
	if(!e) var e = window.event;
	
	if (e.pageX || e.pageY){
		posx = e.pageX - window.pageXOffset;
		posy = e.pageY - window.pageYOffset;
	}else if (e.clientX || e.clientY){
		posx = e.clientX - document.body.scrollLeft - document.documentElement.scrollLeft;
		posy = e.clientY - document.body.scrollTop - document.documentElement.scrollTop;
	}
	return {x:posx,y:posy};
// posx and posy contain the mouse position relative to the document
// Do something with this information
}

/**
  *
  *
  * Funciones para el upload de fotos
  *
  */

var countPhotoTemp = 0;
var photosTemp = new Array();
function uploadPhoto(id,user)
{
	displayLightBox();
	displayUploadPhotoBox(id,user);
}
function displayUploadPhotoBox(id,user)
{
	
	var tableWidth = 300;
	var tableHeight = 400;
	var tableLeft = parseInt(getWidth()/2) - (tableWidth/2);
	var tableTop = parseInt(getHeight()/2) - (tableHeight/2);
	var iframe = new Element('iframe').setProperties({'id':'lightbox_iframe','name':'lightbox_iframe'}).setStyles({'width':'500px','height':'100px','border':'1px'});
		
	cont = new Element('div',{'id':'lightbox_container','styles':{'position':'fixed','width': tableWidth+'px','height': tableHeight+'px','z-index':'2','top': tableTop +'px','left': tableLeft +'px'}});
	
	var uid = new Date();
	page = 'index.php?option=107&id='+id+'&usuario_id='+user+'&uid='+uid;
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
		cont.set('html',html);
		lbCont = cont;
		iframe.inject(lbCont);
		lbCont.inject(myLightBox);
		myLightBox.inject($(document.body),'top');
	}}).get(page);
}

function uploadPhotoTemp()
{
	var name = $('foto').getProperty('value');
	$('subirFotos').setStyle('display','none');
	if(!name) return false;
	var extension = name.split('.').pop().toLowerCase();
	if(extension != 'jpg' && extension != 'jpeg'){
		textInfoBox('<span class="txtYellow">Sólo se permiten archivos con extensión .jpg</span>');
		return false;
	}
	
	$('formAccn').setProperty('value','photo_temp');
	$('formUploadPhoto').setProperties({'action':'index.php?option=1006','target' : 'lightbox_iframe'});	
	$('formUploadPhoto').submit();
	
	if(countPhotoTemp >= 3){
		$('foto').setStyle('display','none');
		textInfoBox('Sólo puede subir 4 archivos por vez.');
	}
}
function showUploadPhotoButton(){
	$('subirFotos').setStyle('display','block');
}
function deletePhotoTemp(obj)
{
	var id = obj.get('id');
	var parts = id.split('_');
	var index = parts.pop();
	photosTemp.splice(index,1);
	obj.destroy();
	countPhotoTemp--;
	if(countPhotoTemp <= 3){
		$('foto').setStyle('display','block');
		textInfoBox('');
	}
}

function textInfoBox(text)
{
	$('lightbox_info').set('html',text);
}

function deleteUploadedTemp()
{	
	$('formAccn').setProperty('value','photo_temp_delete');
	$('formUploadPhoto').setProperties({'action':'index.php?option=1006','target' : 'lightbox_iframe'});	
	$('formUploadPhoto').submit();
}
function responsePhotoTemp(name)
{
	var div = new Element('div',{'id':'photo_temp_'+countPhotoTemp,'styles':{'float':'left','margin-top':'5px'}});
	var fieldName = new Element('div',{'styles':{'float':'left','width':'200px','border':'1px solid #CCC','padding':'3px'}}).set('html',name);
	var fieldButton = new Element('div',{'styles':{'float':'left','width':'60px','background-color':'#CCC','text-align':'center','color':'#666','border':'1px solid #CCC','padding':'3px','cursor':'default'}}).set('html','Borrar').addEvent('click',function(){deletePhotoTemp($(this).getParent());});
	var fieldHidden = new Element('input').setProperties({'type':'hidden','id':'photo_temp[]','name':'photo_temp[]','value':name});
	fieldName.inject(div);
	fieldButton.inject(div);
	fieldHidden.inject(div);
	div.inject($('photo_list'));
	photosTemp[countPhotoTemp] = name;
	countPhotoTemp++;
}

function uploadPhotoUp(seccion)
{
	var toUrl;
	switch(seccion)
	{
		case 'lightbox':
			toUrl = 'index.php?option=1006';
			$('formAccn').setProperty('value','photo_data');
		break;
	}
	textInfoBox('Subiendo archivo...');
	var request = new Request.HTML({
							  	method:'post',
								url:toUrl,
								onComplete:function(tree, elements, html, javascript)
								{
									var text;
									if(html == 'ok')
									{
										text = 'Guardando archivo...';
									}else{
										text = '<span class="txtYellow">Ha ocurrido un error.</span>';										
									}
									setTimeout("closeUp('lightbox');",1000);
									textInfoBox(text);
									companyDetails($('id_empresa').getProperty('value'));
									countPhotoTemp = 0;
									//textInfoBox(html);
								}
							  }).post($('formUploadPhoto'));
}
/**
  *
  * Comentarios
  *
  */
function sendComment()
{
	var comment = $('comentario');
	if(comment.value == '' || comment.value == 'undefined'){
		alert('Complete el campo "Dejanos tu Comentario"');
		return false;
	}
	var toUrl = 'index.php?option=1007';
	tabInfo('create','Guardando datos...');
	var request = new Request.HTML({
							  	method:'post',
								url:toUrl,
								onComplete:function(tree, elements, html, javascript)
								{
									var text;
									if(html == 'ok')
									{
										tabInfo('text','Datos guardados...');
									}else{
										tabInfo('text','Proceso fallido');
									}
									setTimeout("tabInfo('close');",1000);
									$('comentario').set('html','');
									companyDetails($('id_empresa').getProperty('value'));
								}
							  }).post($('formComentario'));	
}

function tabInfo(action,text)
{
	switch(action)
	{
		case 'text':
			tabInfoBox.set('html',text);
		break;
		case 'close':
			tabInfoBox.destroy();
		break;
		case 'create':
			if(tabInfoBox)	tabInfoBox.destroy();
			
			tabInfoBox = new Element('div',{'styles':{'position':'fixed','top':'0px','right':'0px','background-color':'#900','padding':'5px','z-index':'800','color':'#FFF'}}).set('html',action);
			
			tabInfoBox.inject($(document.body));
		break;
	}
}

function displayRecommendBox(id_empresa)
{
	option_id = 108;//form_recomendar.php
	company_id = id_empresa;
	displayLightBox();
	displayContentBox();	
}

function displayReclaimBox(id_empresa)
{
	option_id = 110;//form_reclamar.php
	company_id = id_empresa;
	displayLightBox();
	displayContentBox();
}

function displayPoliticaBox()
{
	option_id = 113;//politica_privacidad.php
	displayLightBox();
	displayContentBox();
}

function displayRecommendWebBox()
{
	option_id = 114;//recomendar_web.php
	displayLightBox();
	displayContentBox();	
}

function displayMessageBox(id_usuario)
{
	option_id = 116;//recomendar_web.php
	company_id = id_usuario;
	displayLightBox();
	displayContentBox();	
}

function displayAdvSearchBox()
{
	option_id = 117;//form_busquedaavanzada.php
	displayLightBox();
	displayContentBox();
}
/**
  *
  * LightBox contenido por defecto
  *
  */
  
function displayContentBox()
{
	
	var tableWidth = 426;
	var tableHeight = 470;
	var tableLeft = parseInt(getWidth()/2) - (tableWidth/2);
	var tableTop = parseInt(getHeight()/2) - (tableHeight/2);
		
	cont = new Element('div',{'id':'lightbox_container','styles':{'position':'fixed','width': tableWidth+'px','height': tableHeight+'px','z-index':'2','top': tableTop +'px','left': tableLeft +'px'}});
	
	var uid = new Date();
	page = 'index.php?option='+option_id+'&id_empresa='+company_id+'&uid='+uid;
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
		cont.set('html',html);
		lbCont = cont;
		lbCont.inject(myLightBox);
		myLightBox.inject($(document.body),'top');
	}}).get(page);
}

function sendForm(from)
{
	switch(from)
	{
		case 'lightbox_recommend':
			var toUrl = 'index.php?option=108';
			if($('nombre').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Complete el campo "Tu Nombre".</span>');
				$('nombre').focus();
				return false;				
			}else if($('destinatarios').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Debe ingresar al menos un<br />E-mail destinatario.</span>');
				$('destinatarios').focus();
				return false;				
			}else if(!checkAllEmails($('destinatarios').getProperty('value'))){
				textInfoBox('<span class="txtYellow">Alg&uacute;n E-mail de los destinatarios es incorrecto.</span>');
				return false;
			}else if($('asunto').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Complete el campo "Asunto"</span>');
				$('asunto').focus();
			}
		break;
		case 'lightbox_recommendweb':
			var toUrl = 'index.php?option=114';
			if($('nombre').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Complete el campo "Tu Nombre".</span>');
				$('nombre').focus();
				return false;				
			}else if($('destinatarios').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Debe ingresar al menos un<br />E-mail destinatario.</span>');
				$('destinatarios').focus();
				return false;				
			}else if(!checkAllEmails($('destinatarios').getProperty('value'))){
				textInfoBox('<span class="txtYellow">Alg&uacute;n E-mail de los destinatarios es incorrecto.</span>');
				return false;
			}else if($('asunto').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Complete el campo "Asunto"</span>');
				$('asunto').focus();
			}
		break;
		case 'lightbox_mensajeusuario':
			var toUrl = 'index.php?option=116';
			if($('asunto').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Complete el campo "Asunto".</span>');
				$('asunto').focus();
				return false;				
			}else if($('mensaje').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Complete el campo "Mensaje".</span>');
				$('mensaje').focus();
				return false;				
			}
		break;
		case 'lightbox_reclaim':
			var toUrl = 'index.php?option=110';
			
			if($('destinatarios').getProperty('value') == ''){
				textInfoBox('<span class="txtYellow">Complete el campo "E-mail".</span>');
				$('destinatarios').focus();
				return false;				
			}else if(!checkAllEmails($('destinatarios').getProperty('value'))){
				textInfoBox('<span class="txtYellow">El E-mail es incorrecto.</span>');
				return false;
			}
		break;
		case 'lightbox_newmark':
			var toUrl = 'index.php?option=115';
		break;
	}
	var uid = new Date();
	toUrl += '&uid=' + uid;
	textInfoBox('Procesando datos...');
	var request = new Request.HTML({
							  	method:'post',
								url:toUrl,
								onComplete:function(tree, elements, html, javascript)
								{
									var text;
									if(html == 'ok')
									{
										text = 'Datos enviados...';
									}else if(html == 'ko'){
										text = '<span class="txtYellow">Proceso fallido</span>';
									}
									textInfoBox(text);
									setTimeout("closeUp('lightbox');",1000);
									if(newMarkPoint){
										/*setTimeout("newMarkPoint.closeInfoWindow();",1000);
										setTimeout("map.removeOverlay(newMarkPoint);",1100);*/
										window.location.reload();
									}
									//textInfoBox(html);
								}
							  }).post($('formOptions'));	
}

var nPageSearch = 1;
var urlSearch = '';
function searchGoToPage(page){
	//$('nPage').set('value',page);
	urlSearch = page;
	sendFormAdvSearch();
	//sendAdvSearch(url);
}

function sendAdvSearch(url){
	var uid = new Date();
	var page = url + '&fromForm=lightbox&uid=' + uid;
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
																buildMyPage(html,'listado');
															 }}).get(page);
}
function sendFormAdvSearch(){
	
	if(urlSearch){
		//alert(urlSearch);
		toUrl = urlSearch;
		var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
																var text;
																if(html == 'ok')
																{
																	text = 'Datos enviados...';
																}else if(html == 'ko'){
																	text = '<span class="txtYellow">Proceso fallido</span>';
																}
																var parts = html.split('##INFO##');
																buildMyPage(parts[0],'listado');
																GSearchSearchCompany(parts[1]);
																resetMenu();	
															 }}).get(toUrl);
		urlSearch = '';
		return false;
	}
	var form = $('formOptions');
	var iso = form.pais_id.options[form.pais_id.selectedIndex].value;
	var tmp_iso = form.ssn_pais_id.value;
	//alert('searching');
	if(iso != tmp_iso){
		form.pais_id.setProperties({'name':'pais','id':'pais'});
		form.provincia_id.setProperties({'name':'provincia','id':'provincia'});
		form.submit();
		return false;
	}
	var toUrl = 'index.php?option=117&nPage=' + nPageSearch;
	var error = 0;
	var info = '';
	for(var i = 0; i < form.length; i++){
		if(form[i].value == '' || form[i].value == 0){ error++;}
		info += i +') ' + form[i].value + '<br />';
	}
	if(error == 5){
		textInfoBox('<span class="txtYellow">Complete o seleccione alguna opci&oacute;n.</span>');
		//textInfoBox('<span class="txtYellow">Complete o seleccione alguna opci&oacute;n.<br />'+info+'</span>');
	}else{
		//textInfoBox('<span class="txtYellow">'+info+'</span>');
	}
	//return false;
	var uid = new Date();
	toUrl += '&uid=' + uid;
	textInfoBox('Procesando datos...');
	var request = new Request.HTML({
								method:'post',
								url:toUrl,
								onComplete:function(tree, elements, html, javascript)
								{
									var text;
									if(html == 'ok')
									{
										text = 'Datos enviados...';
									}else if(html == 'ko'){
										text = '<span class="txtYellow">Proceso fallido</span>';
									}
									var parts = html.split('##INFO##');
									buildMyPage(parts[0],'listado');
									GSearchSearchCompany(parts[1]);
									resetMenu();
									textInfoBox(text);
									setTimeout("closeUp('lightbox');",1000);									
									//textInfoBox(html);
								}
							  }).post($('formOptions'));	
}

function searchBy(field)
{
	
	palabra = $(field).value;
	if(!palabra){return false;}
	if(!fichaOpen){
		$('page_canvas').setStyle('height','422px');
		$('content').setStyle('min-height','608px');
		contResize();
	}
	resetMenu();
	var uid = new Date();
	
	var page = 'index.php?option=117&nPage='+nPageSearch+'&palabra='+palabra+'&fromForm=lightbox';
	
	var myHTMLRequest = new Request.HTML({onSuccess:function(tree, elements, html, javascript){
															 	var parts = html.split('##INFO##');
																buildMyPage(parts[0],'listado');
																GSearchSearchCompany(parts[1]);
																resetMenu();
															 }}).get(page);
}

function changeCountry(iso,provincia)
{
	if(iso == 'AR'){
		$('provincia').setProperty('disabled','');
		$('provincia').setStyle('display','inline');
	}else{	
		$('provincia').setProperty('disabled','disabled');
		$('provincia').setStyle('display','none');	
	}
	document.formChangeProv.submit();
}

function checkCountry(iso){
	if(iso=='AR'){
		$('provincia_id').setProperty('disabled','');
	}else{
		$('provincia_id').setProperty('disabled','disabled');
	}
}

function selectCountryFormOptions(selectCountryName,pais,selectStateName,provincia)
{
	var sel = $(selectName);
	for(var i = 0; i < sel.length; i++){
		if(sel[0].option[i].value == pais){
			sel[0].option[i].selectedIndex = true;
		}
	}
}

function checkAllEmails(emails){emails=emails.nospaces();var e = emails.split(',');var c=0;for(var k=0;k<e.length;k++){if(!emailCheck(e[k])){return false;}}return true;}

function emailCheck(emailStr){var emailPat=/^(.+)@(.+)$/;var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";var validChars="\[^\\s"+specialChars+"\]";var quotedUser="(\"[^\"]*\")";var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;var atom=validChars+'+';var word="("+ atom+"|"+quotedUser+")";var userPat=new RegExp("^"+word+"(\\."+word+")*$");var domainPat=new RegExp("^"+atom+"(\\."+atom+")*$");var matchArray=emailStr.match(emailPat);if(matchArray==null){return false;}var user=matchArray[1];var domain=matchArray[2];if(user.match(userPat)==null){return false;}var IPArray=domain.match(ipDomainPat);if(IPArray!=null){for(var i=1;i<=4;i++){if(IPArray[i]>255){return false;}}return true;}var domainArray=domain.match(domainPat);if(domainArray==null){return false;}var atomPat=new RegExp(atom,"g");var domArr=domain.match(atomPat);var len=domArr.length;if(domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3){return false;}if(len<2){var errStr="Esta direccion es desconocida como IP!";return false;}return true;}