1;
var gVersion = 'v1.2.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: "POST",
				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[0].onclick = (function(event){});
			if (bEsAgregar)
			{
				if (oCaja.hasClass('GI_ListadoTituloDepartamento_ListaAgregar') )
				{
					oCaja.removeClass('GI_ListadoTituloDepartamento_ListaAgregar');
				}

				if (!oCaja.hasClass('GI_ListadoTituloDepartamento_ListaQuitar') )
				{
					oCaja.addClass('GI_ListadoTituloDepartamento_ListaQuitar');
				}

				oCaja.one( 'click', iID,
							function (event){
								consultarListadoDeUsuario('quitar', event.data);
								event.cancelBubble = true; if(event.stopPropagation) event.stopPropagation();
								$(this).unbind('click');
								});
			}
			else
			{
				if (oCaja.hasClass('GI_ListadoTituloDepartamento_ListaQuitar') )
				{
					oCaja.removeClass('GI_ListadoTituloDepartamento_ListaQuitar');
				}

				if (!oCaja.hasClass('GI_ListadoTituloDepartamento_ListaAgregar') )
				{
					oCaja.addClass('GI_ListadoTituloDepartamento_ListaAgregar');
				}

				oCaja.one( 'click', iID,
							function (event){
								consultarListadoDeUsuario('agregar', event.data);
								event.cancelBubble = true; if(event.stopPropagation) event.stopPropagation();
								$(this).unbind('click');
								});
			}
		}
	}
	catch(e)
	{
    	mostrarMensaje(oMensaje, e.message, true, false);
		alert('Error(imagenListadoPropiedad): ' + e.message);
	}
}

/*********************************************************************
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
		}
    }
	catch(e)
	{
    	mostrarMensaje(oMensaje, e.message + '\n' + responseText, true, false);
		alert('Error(resultado): ' + e.message);
	}
}

/*********************************************************************
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 = '';

		oCajaLista.empty();

		if (iCantidad === false || isNaN(parseInt(iCantidad)))
		{
			sHTML = $('#ListadoPropiedadSeleccionadaNOEXISTE').html();
		}
		else
		{
			/////////////////////////////////////////////////////////////////////////////////////////
			// Cantidad de propiedades en la lista
			/////////////////////////////////////////////////////////////////////////////////////////
			if (gsLang == 'in')
			{
				var sCantidad = 'There ' + (iCantidad == 1 ? 'is <b>1</b> property' : 'are <b>' + iCantidad + '</b> properties') + ' on your list.';
				var sVerMiLista = 'View my list';
				var sSuLista = 'THIS IS YOUR LIST';
				var sRegistro = 'Save my selection';

				if (sWelcome) sWelcome = 'Welcome, ' + sWelcome + '!';
			}
			else
			{
				var sCantidad = 'Hay <b>' + iCantidad + '</b> propiedad' + (iCantidad == 1 ? '' : 'es' ) + ' es su lista.';
				var sVerMiLista = 'Ver mi lista';
				var sSuLista = 'ESTA ES SU LISTA';
				var sRegistro = 'Guardar selecci&oacute;n';

				if (sWelcome) sWelcome = '&iexcl;Bienvenido, ' + sWelcome + '!';
			}

			sHTML += '<div class="GI_propiedadSeleccionadaCantidad">';

			var bCustomList = ((!isNaN(parseInt($('#customlist').val())) && parseInt($('#customlist').val())) ? true : false );
			if (bCustomList)
			{
				sHTML += '<span style="float: left;">' + sSuLista + '</span>';
				sHTML += '<span style="color: black; float: right; margin-right: 3px;">' + sCantidad + '</span>';
			}
			else
			{
				sHTML += '<span style="float: left;">' + sCantidad + '</span>';
			}
			sHTML += '</div>';

			if (!bRegistered)
				sHTML += '<div class="GI_propiedadSeleccionadaRegistro" onclick="javascript: formularioRegistro();" style="background-image: url(./images/template/button_save_' + gsLang + '.gif);" title="' + sRegistro + '"></div>';

			if (sWelcome)
			{
				sHTML += '<div class="GI_propiedadSeleccionadaBienvenido">' + sWelcome + '</div>';
			}

			sHTML += '<div id="VerListadoPersonalizado" class="GI_propiedadSeleccionadaVerLista" href="./?d=-2" style="background-image: url(\'images/template/button_view_' + gsLang + '.gif\');" title="' + sVerMiLista + '"></div>';
		}

		sHTML += (gbMostrarVersion ? gVersion : '');
		$('#ListadoPropiedadSeleccionada').append(sHTML);
		$('#VerListadoPersonalizado').click(function(){
				if (this.getAttribute('href'))
					location.href = this.getAttribute('href');
				return false;
			});
		destacarCuadrosDeTexto();

	}
	catch(oError)
	{
		alert('Error(resultadoEnviarMisDatosError):' + oError.message);
		mostrarMensaje(oCajaLista, oError.message + ':<br><br>' + oHTML.responseText, true, 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 oListado = $('#ListadoPropiedadSeleccionada');
	var oBtnRegistro = $('#btnRegistro');
	var oBtnRecupero = $('#btnRecupero');

	if (oListado.length )
	{
	//////////////////////////////////
	// Language
	//////////////////////////////////

		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) alert(gVersion);
});
