1;
v gVersion = 'v1.6.1';
var gbMostrarVersion = false;
var gbMostrarPeticionesAJAX = false;
var gbMostrarRespuestasAJAX = false;
var iPos = (location.pathname.lastIndexOf('/') == 0 ? 1 : location.pathname.lastIndexOf('/'));
var gsCookiePath = location.pathname.substring(0, iPos);
var gsCookieDomain = location.hostname.substr((location.hostname.indexOf('.') + 1));
var giCookieExpiration = 365;

/*********************************************************************
Funcion: consultarListadoDeUsuario
Motivo:
	Consulta el listado en el server asincrónicamente.
Parametros:
Devuelve:
	No devuelve datos ni resultados.
**********************************************************************/
function consultarListadoDeUsuario(sAccion, iID, sEmail, sNombre)
{
	var oListado = $('#ListadoPropiedadSeleccionada');

	if (oListado.length )
	{
		var sKey = getCookieList();

		if (!sKey)
			sKey = '';

		if (sKey != '' || sAccion + '' != 'undefined' )
		{
			if (!sAccion)
				sAccion = 'cantidad';

			if (!sEmail)
				sEmail = '';

			if (!sNombre)
				sNombre = '';

			if (!iID || isNaN(parseFloat(iID)))
				iID = '';

			var url = 'ajax_listadoPersonalizado.php';
			var pars = 'accion=' + sAccion +
			'&key=' + sKey +
			'&prop=' + iID +
			'&email=' + sEmail +
			'&nombre=' + sNombre;

			if (gbMostrarPeticionesAJAX) prompt('ajax', url + '?' + pars);

			oListado.html($('#ListadoPropiedadCargando').html() );

			$.ajax(
			{
				type: "GET",
				url: url,
				data: pars,
				dataType: "html",
				success: resultado,
				error: resultadoError
			});
		}
		else
		{
			cargarMensajeLista(null, 0, false);
		}
	}
}

/*********************************************************************
Funcion: imagenListadoPropiedad
Motivo:
	Cambia el class dependiendo si se agregó o quitó la propiedad.
Parametros:
Devuelve:
	No devuelve datos ni resultados.
**********************************************************************/
function imagenListadoPropiedad(iID, bEsAgregar)
{
	try
	{
		var oMensaje = $('#ListadoPropiedadSeleccionada');
		var oCaja = $('#GI_ListadoTituloDepartamento_Lista' + String(iID));

		if (isNaN(parseInt(iID))) return false;

		if (oCaja.length )
		{
			oCaja.unbind('click');
			if (bEsAgregar)
			{
				if (oCaja.parent().hasClass('busqueda-propiedad-info') ||
					oCaja.parent().parent().hasClass('busqueda-propiedad-info'))
				{
					if (oCaja.hasClass('busqueda-propiedad-add-from-list'))
						oCaja.removeClass('busqueda-propiedad-add-from-list');

					if (!oCaja.hasClass('busqueda-propiedad-remove-from-list'))
						oCaja.addClass('busqueda-propiedad-remove-from-list');
				}
				else
				{
					if (oCaja.hasClass('listado-propiedad-add-from-list') )
						oCaja.removeClass('listado-propiedad-add-from-list');

					if (!oCaja.hasClass('listado-propiedad-remove-from-list'))
						oCaja.addClass('listado-propiedad-remove-from-list');
				}

				oCaja.find('span').text($('#txtTextoQuitarDeLaLista').val());

				oCaja.click(function (event){
					$(this).unbind('click');
					$(this).find('span').text('');
					$(this).removeClass('busqueda-propiedad-remove-from-list');
					var iProp = parseInt($(this).find('input.propiedad-id').val());
					consultarListadoDeUsuario('quitar', iProp);
					event.cancelBubble = true;
					if(event.stopPropagation)
						event.stopPropagation();
				});
			}
			else
			{
				if (oCaja.parent().hasClass('busqueda-propiedad-info') ||
					oCaja.parent().parent().hasClass('busqueda-propiedad-info'))
				{
					if (oCaja.hasClass('busqueda-propiedad-remove-from-list'))
						oCaja.removeClass('busqueda-propiedad-remove-from-list');

					if (!oCaja.hasClass('busqueda-propiedad-add-from-list'))
						oCaja.addClass('busqueda-propiedad-add-from-list');
				}
				else
				{
					if (oCaja.hasClass('listado-propiedad-remove-from-list') )
						oCaja.removeClass('listado-propiedad-remove-from-list');

					if (!oCaja.hasClass('listado-propiedad-add-from-list'))
						oCaja.addClass('listado-propiedad-add-from-list');
				}

				oCaja.find('span').text($('#txtTextoAgregarALaLista').val());

				oCaja.click(function (event){
					$(this).unbind('click');
					$(this).find('span').text('');
					$(this).removeClass('busqueda-propiedad-add-from-list');
					var iProp = parseInt($(this).find('input.propiedad-id').val());
					consultarListadoDeUsuario('agregar', iProp);
					event.cancelBubble = true;
					if(event.stopPropagation)
						event.stopPropagation();
				});
			}
		}
		return true;
	}
	catch(e)
	{
		mostrarMensaje(oMensaje, e.message, true, false);
		alert('Error(imagenListadoPropiedad): ' + e.message);
		return false;
	}
}

/*********************************************************************
Funcion: setCookieList
Motivo:
	Setear el valor de la cookie
Parametros:
	key -> Es el key enviado el server.
Devuelve:
**********************************************************************/
function setCookieList(key)
{
	$.cookie('w2ba_list', key, {
		expires: giCookieExpiration,
		path: gsCookiePath,
		domain: gsCookieDomain,
		secure: false
	});
}

/*********************************************************************
Funcion: getCookieList
Motivo:
	Obtener la cookie
Parametros:
Devuelve:
	Devuelve la cookie.
**********************************************************************/
function getCookieList()
{
	var oCookie = $.cookie('w2ba_list');

	return oCookie;
}

/*********************************************************************
Funcion: resultado
Motivo:
	Maneja la respuesta del servidor
Parametros:
	responseText -> Es el texto devuelto por el server.
	statusText	 -> Es el mensaje de status.
Devuelve:
	No devuelve datos ni resultados.
**********************************************************************/
function resultado(responseText, statusText)
{
	try
	{
		var oMensaje = $('#ListadoPropiedadSeleccionada');
		var sHTML = '';

		if (gbMostrarRespuestasAJAX) prompt('responseText', responseText);

		if (responseText.substring(0,1) == '[' || responseText.substring(0,1) == '{' )
		{
			// Genero el resultado objeto
			var oResultado = eval('(' + responseText + ')');
			if (oResultado.Mensaje) alert(oResultado.Mensaje);

			if (oResultado.Ok)
			{
				// Set the Key
				if (
					((oResultado.Recuperar && oResultado.Existe) || !oResultado.Recuperar) &&
					oResultado.Key != '')
					{
					setCookieList(oResultado.Key);
					cargarMensajeLista(oResultado.Cantidad, oResultado.Registrado, oResultado.Bienvenida);
				}
				else
				{
					cargarMensajeLista(null, 0, false);
					if (oResultado.Cantidad)
					{
						return true;
					}
				}

				// Agregar
				if (oResultado.Agregar)
				{
					imagenListadoPropiedad(oResultado.Propiedad, true);
				}
				// Quitar
				if (oResultado.Quitar)
				{
					imagenListadoPropiedad(oResultado.Propiedad, false);
				}
				// Registro
				if (oResultado.Registro)
				{
					formularioRegistro();
					$('.GI_propiedadSeleccionadaRegistro').remove();
				}
				// Recuperar
				if (oResultado.Recuperar)
				{
					formularioRecupero();
				}
				// Recuperar && No Existe => Confirma registrar
				if (oResultado.Recuperar && oResultado.Existe == false)
				{
					if (gsLang == 'in')
						sMensaje = 'Your email "' + oResultado.Email + '" was not found.\nDo you want to register?';
					else
						sMensaje = 'Su email "' + oResultado.Email + '" no se encontró.\n¿Desea registrarse?';

					if (confirm(sMensaje))
					{
						formularioRegistro(oResultado.Email);
					// consultarListadoDeUsuario('registrar', null, oResultado.Email, oResultado.Nombre)
					}
				}

				if (oResultado.Existe)
				{
			// Mostrar el welcome
			}
			}
			else
			{
				if (oResultado.Recuperar)
					cargarMensajeLista(null, 0, false);
				else if (oResultado.Registro)
					cargarMensajeLista(null, 0, false);
				else if (oResultado.Agregar && !oResultado.Key)
					cargarMensajeLista(null, 0, false);
				else
					cargarMensajeLista(oResultado.Cantidad, oResultado.Registrado, oResultado.Bienvenida);
			}
		}
		else
		{
			if (gsLang == 'in')
				alert('An error has occurred.');
			else
				alert('Ocurrió un error.');

			alert('ERROR:\n\n' + responseText);
			cargarMensajeLista(null, 0, false);
		// Enviar mensaje a soporte de welcome2ba
		}

		return oResultado.Ok;

	}
	catch(e)
	{
		mostrarMensaje(oMensaje, e.message + '\n' + responseText, true, false);
		alert('Error(resultado): ' + e.message);
		return false;
	}
}

/*********************************************************************
Funcion: resultadoError
Motivo:
	Maneja los errores en la respuesta del servidor.
Parametros:
	oHTML		-> Es el objeto XMLHttpRequest.
	sMensaje	-> Es el mensaje de error.
	oError		-> Es el objeto con el error si ocurrió alguno.
Devuelve:
	No devuelve datos ni resultados.
**********************************************************************/
function resultadoError(oHTML, statusText, oError)
{
	try
	{
		var oMensaje = $('#ListadoPropiedadSeleccionada');
		var sError = '';
		var sMensaje = '';

		if (oHTML.status == 0)
		{
			if (gsLang == 'in')
				sMensaje = 'Action canceled by user. <a href="#" onclick="javascript: consultarListadoDeUsuario(); event.cancelBubble = true; if(event.stopPropagation) event.stopPropagation();">Reload</a>';
			else
				sMensaje = 'Acción cancelada por el usuario. <a href="#" onclick="javascript: consultarListadoDeUsuario(); event.cancelBubble = true; if(event.stopPropagation) event.stopPropagation();">Refrescar</a>';
			mostrarMensaje(oMensaje, sMensaje, false, false);
			return;
		}

		cargarMensajeLista(null, 0, false);

		if (oHTML.responseText.substring(0,1) == '[' || oHTML.responseText.substring(0,1) == '{' )
		{

			var oRegistro = eval('(' + oHTML.responseText + ')');
			if (oRegistro.Ok)
			{
				if (gsLang == 'in')
					alert('NOTICE response Ok but with ERROR.' + oRegistro.Mensaje);
				else
					alert('ATENCION OK con error.' + oRegistro.Mensaje);
			}
			else
			{
				if (gsLang == 'in')
					alert('NOTICE ERROR.' + oRegistro.Mensaje);
				else
					alert('ATENCION Error.' + oRegistro.Mensaje);
			}
		}
		else
		{
			if (oError)
				sError = '\n' + oError.message + '\n';

			sError += oHTML.responseText;
			if (gsLang == 'in')
				alert('NOTICE:\nError has occurred.\n' + sError);
			else
				alert('ATENCIÓN:\nOcurrió un error.\n' + sError);

		}

	}
	catch(oError)
	{
		alert('Error(resultadoError):' + oError.message);
		mostrarMensaje(oMensaje, oError.message + ':<br><br>' + oHTML.responseText, true, false);
	}
}

/*********************************************************************
Funcion: cargarMensajeLista
Motivo:
	Maneja los errores en la respuesta del servidor.
Parametros:
	oHTML		-> Es el objeto XMLHttpRequest.
	sMensaje	-> Es el mensaje de error.
	oError		-> Es el objeto con el error si ocurrió alguno.
Devuelve:
	No devuelve datos ni resultados.
**********************************************************************/
function cargarMensajeLista(iCantidad, bRegistered, sWelcome)
{
	try
	{
		var oCajaLista = $('#ListadoPropiedadSeleccionada');
		var sHTML = '';
		var sCantidad = '';
		var sVerMiLista = '';
		var sSuLista = '';
		var sRegistro = '';

		oCajaLista.empty();

		if (iCantidad === false || isNaN(parseInt(iCantidad)))
		{
			sHTML = $('#ListadoPropiedadSeleccionadaNOEXISTE').html();
		}
		else
		{
			/////////////////////////////////////////////////////////////////////////////////////////
			// Cantidad de propiedades en la lista
			/////////////////////////////////////////////////////////////////////////////////////////
			if (gsLang == 'in')
			{
				sCantidad = 'There ' + (iCantidad == 1 ? 'is 1 property' : 'are ' + iCantidad + ' properties') + ' on your list.';
				sVerMiLista = 'My list';
				sSuLista = 'THIS IS YOUR LIST';
				sRegistro = 'Save my selection';

				if (sWelcome) sWelcome = 'Welcome, ' + sWelcome + '!';
			}
			else
			{
				sCantidad = 'Hay ' + iCantidad + ' propiedad' + (iCantidad == 1 ? '' : 'es' ) + ' en su lista.';
				sVerMiLista = 'Mi lista';
				sSuLista = 'ESTA ES SU LISTA';
				sRegistro = 'Guardar selecci&oacute;n';

				if (sWelcome) sWelcome = '¡Bienvenido, ' + sWelcome + '!';
			}

			if (!bRegistered)
				sHTML += '<div class="GI_propiedadSeleccionadaRegistro" onclick="javascript: formularioRegistro();"><img src="/images/save.jpg" title="' + sRegistro + '" /></div>';

			if (sWelcome)
			{
				sHTML += '<div class="GI_propiedadSeleccionadaBienvenido">' + escapeHTML(sWelcome) + '</div>';
			}

			sHTML += '<a href="./?p=dto_l&amp;d=-2"><div id="VerListadoPersonalizado" class="GI_propiedadSeleccionadaVerLista">' + sVerMiLista + '</div></a>';

			sHTML += '<div class="GI_propiedadSeleccionadaCantidad">';

			var bCustomList = ((!isNaN(parseInt($('#customlist').val())) && parseInt($('#customlist').val())) ? true : false );
			if (bCustomList)
			{
				sHTML += '<span style="float: left;">' + escapeHTML(sSuLista) + '</span>';
				sHTML += '<img src="/images/fav.jpg" title="' + sCantidad + '" /><span style="color: black; float: right; margin-right: 3px;padding-left: 2px;">' + iCantidad + '</span>';
			}
			else
			{
				sHTML += '<img src="/images/fav.jpg" title="' + sCantidad + '" /><div style="display: inline-block;vertical-align: 2px;padding-left: 2px;">' + iCantidad + '</div>';
			}
			sHTML += '</div>';

		}

		$('#ListadoPropiedadSeleccionada').append(sHTML);
		//		$('#VerListadoPersonalizado').click(function(){
		//				if (this.getAttribute('href'))
		//					location.href = this.getAttribute('href');
		//				return false;
		//			});
		destacarCuadrosDeTexto();
		return true;

	}
	catch(oError)
	{
		alert('Error(resultadoEnviarMisDatosError):' + oError.message);
		mostrarMensaje(oCajaLista, oError.message + ':<br><br>' + oHTML.responseText, true, false);
		return false;
	}
}

/*********************************************************************
Funcion: formularioRegistro
Motivo:
	Muestra el formulario para registrarse.
Parametros:
Devuelve:

**********************************************************************/
function formularioRegistro(sEmail)
{
	$('#ListadoPropiedadesRegistro *:input').val('');
	$('#ListadoPropiedadesRegistro').toggle();

	if (sEmail) $('#EmailRegistro').val(sEmail);

	if ($('#ListadoPropiedadesRegistro').css('display') != 'none')
	{
		$('#ListadoPropiedadesRecupero').hide();
		$('#EmailRegistro').focus();
	}
}

/*********************************************************************
Funcion: formularioRecupero
Motivo:
	Muestra el formulario para registrarse.
Parametros:
Devuelve:

**********************************************************************/
function formularioRecupero()
{
	$('ListadoPropiedadesRecupero *:input').val('');
	$('#ListadoPropiedadesRecupero').toggle();

	if ($('#ListadoPropiedadesRecupero').css('display') != 'none')
	{
		$('#ListadoPropiedadesRegistro').hide();
		$('#EmailRecupero').focus();
	}
}

/*********************************************************************
Funcion de inicializacion
**********************************************************************/
$(document).ready(function() {
	var oBtnRegistro = $('#btnRegistro');
	var oBtnRecupero = $('#btnRecupero');
	var oListado = $('#ListadoPropiedadSeleccionada');

	if (oListado.length )
	{
		oListado.hide();
		consultarListadoDeUsuario();
		oListado.show();

		oBtnRegistro.click(function() {
			consultarListadoDeUsuario('registrar', null, $('#EmailRegistro').val(), $('#NombreRegistro').val() );
		});

		oBtnRecupero.click(function() {
			consultarListadoDeUsuario('recuperar', null, $('#EmailRecupero').val());
		});
	}

});


if (gbMostrarVersion && console) console.log('listadoUsuario version: ' + gVersion);
