﻿/*******************************************************
* 
*******************************************************/
var bDebug = false;
var glData;

var PRIVILEGIOSINACCESO = "0";
var PRIVILEGIOCONSULTAR = "1";
var PRIVILEGIOGRABAR    = "2";

//.s. intento instanciar el engine
try
{
	glData = parent.vEngine;
	if (!glData) {
	    window.location.href = "Error.aspx";
	}
}
catch(e)
{
	window.location.href = "Error.aspx";
}

/*******************************************************
* 
*******************************************************/
$(document).bind("contextmenu",function(e){
	if (e.shiftKey) {
		return true;					
	}
		
	if (e.ctrlKey) {
		QueryLog.showLog();
		return false;
	}
	return false;
});

/*******************************************************
* 
*******************************************************/
var QueryLog = {

    querys: [],
    _draging: false,
    add: function(pMetodo, pParametros, pResponse) {
        var query = {};
        query.metodo = pMetodo;
        query.parametros = pParametros;
        query.response = pResponse;
        this.querys.push(query);

        if (this.querys.length > 5) {
            this.querys = this.querys.splice(1, 5);
        }
    },
    showLog: function() {
        if ($("#queryLog").size() > 0) {
            $div = $("#queryLog");
        } else {
            $div = $("<div id='queryLog'></div>");
            $("body").append($div);
        }
        $div.show();
        str = "<h1 class='lb'><b>[X]</b>&nbsp;Query Log</h1>";
        $(this.querys).each(function(i, query) {
            str += "<ul>";
            str += "<li class='method'>Method:" + query.metodo + "</li>";
            str += "<ul style='display:none'>";
            str += "<li>Params:<br><textarea>" + query.parametros + "</textarea></li>";
            str += "<li>Response:<br><textarea>" + query.response + "</textarea></li>";
            str += "</ul></ul>";
        });
        $div.html(str);

        //.s. DRAG
        $("#queryLog h1").mousedown(function(e) {
            this._draging = true;
        })
        .mousemove(function(e) {
            if (this._draging) {
                x = e.clientX - 25;
                y = e.clientY - 20;
                $div.css({ "left": x, "top": y });
            }
        })
        .mouseout(function(e) {
            if (this._draging) {
                x = e.clientX - 25;
                y = e.clientY - 20;
                $div.css({ "left": x, "top": y });
            }
        })
        .mouseup(function(e) {
            this._draging = false;
        });

        $("#queryLog h1 b").click(function() { $div.hide(); });
        $("#queryLog ul li").toggle(function() { $(this).siblings("ul").show(); },
                                    function() { $(this).siblings("ul").hide(); });
        return false;

    }
};

/*******************************************************
* 
*******************************************************/
function Query(pMetodo, pParametros, pCallBack, pMsgEspera) {

    var dataEnvio = $.toJSON(pParametros);
    
    $.ajax({
        async: true,
        beforeSend: function() {
            if ((pMsgEspera) && (pMsgEspera != "")) {
                ProgressOn(pMsgEspera);
            }
        },
        type: "POST",
        url: "_Services/" + pMetodo,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: dataEnvio,
        success: function(dataResult) {
            ProgressOff();

            try {
                var result = $.evalJSON(dataResult.d);
                QueryLog.add(pMetodo,dataEnvio,dataResult.d);
            }
            catch (e) {
                SendClientError("CM", pMetodo, "Error al evaluar JSON:<br/>" + e.description + "<br/>dataSend:" + dataEnvio + "<br/>dataResult:" + dataResult);
                if (bDebug) { throw e; }
                return;
            }

            try {
                pCallBack(result);
            }
            catch (e) {
                SendClientError("CM", pMetodo, "Error al invocar CALLBACK:<br/>" + pCallBack + "<br/>dataSend:" + dataEnvio + "<br/>dataResult:" + dataResult + "<br/>description:" + e.description);
                if (bDebug) { throw e; }
            }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

            ProgressOff();
            try {
                var error = $.evalJSON(XMLHttpRequest.responseText);
                strError = error.Message + "\n" + error.StackTrace + "\n" + error.ExceptionType;
            }
            catch (e) {
                strError = XMLHttpRequest.responseText;
            }

            //.s. Error de conexión
            if (XMLHttpRequest.responseText == "") {
                //.s. Recuperables: Dropped connection & Connection closed by server
                if ((XMLHttpRequest.status >= 12029 && XMLHttpRequest.status <= 12031) || XMLHttpRequest.status == 12152) {
                    //.s. Reintentando	               
                    Query(pMetodo, pParametros, pCallBack, pMsgEspera);
                    return;
                }
                else {
                    strError = "Se ha producido un error en la conexión.\nRevisa que tu conexión sea correcta";
                }
            }
            
            if (bDebug) { alert(strError); }
        },
        complete: function() {

        }
    });
}
/*******************************************************
* .s. Extends de Prestige de JQUERY
* 
*******************************************************/

var PrestigeJS = 
{
	//.s. Dialogo en medio doc
	dialog : function(speed)
	{
		$(this).centerInDocument();
		$(this).show(speed);
	},
	
	/**************************************/
	//.s. Centra obj en doc
	/**************************************/
	
    centerInDocument : function()
    {
		$(this).css("position","absolute");
		$(this).css("left",(document.body.clientWidth / 2) - ($(this).outerWidth() / 2));
		$(this).css("top",(document.body.clientHeight / 2) - ($(this).outerHeight() / 2));	
		return $(this);
    },
    
    /**************************************/
	//.s. Para los checkbox
	/**************************************/
    
    checked : function (pbool)
    {
		if (pbool == null)
			return $(this).is(":checked");
		
		$(this).attr("checked",pbool);
		return $(this);
    },
    
     /**************************************/
	//.s. Ed's disabled
	/**************************************/
	disabled : function (pbool)
	{
		if (pbool == null)
			return $(this).is(":disabled");
		
		if (pbool)
			$(this).attr("disabled",true);
		else
			$(this).removeAttr("disabled");
		return $(this);
	}
};
//.s. Aplico Extends
(function($){ $.fn.extend(PrestigeJS) })(jQuery);

/*****************************************************
*
******************************************************/
///.s. Monta y gestiona la seleccion de hotel
///.s. Uso: HotelSearch("NombreContendor",NumeroPixelWidthEd);
///.s. Eventos pub: HotelSearch_Change(nombre,id)
//					HotelSerach_Clear()

var _HotelSearch = {
	
	_Timer		    : null,
	oLb			    : null,
	oEdId		    : null,
	oEd			    : null,
	oBt			    : null,
	
	/*****************************************************
	*.s.
	******************************************************/
	
	Ini : function (ContenedorId,Width)
	{
		Width = Width == null ? "150" : Width;
		oContenedor = $("#" + ContenedorId);
	
		oLb			= $("<label for='edHotel' class='tx'>"+ rsEd_Name +"&nbsp;</label>");
		oEdId		= $("<input type='hidden' id='edIdHotel' />");
		oEd			= $("<input type='text' id='edHotel' class='ed' style='width:" + Width + "px' />");
		oBt			= $("<div class='btVisor'><img src='_Images/BtVisor16x16.gif' align='texttop'/></div>");
		oBtClear	= $("<div id='dvBtClearHotel' style='display:none;position:absolute;cursor:pointer'><img src='_Images/Delete16x16.png' /></div>");
		
		oContenedor.append(oLb).append(oEdId).append(oEd).append(oBt).append(oBtClear);
		
		if (glData.IdHotel != "0")
		{
			oEdId.val(glData.IdHotel);
			oEd.val(glData.Hotel);
			oEd.disabled(true);
			oBt.remove();
			if (typeof HotelSearch_Change != "undefined"){
			    HotelSearch_Change(oEd.val(),oEdId.val());
			}
			return;
		}
		
		oBt.click(function(){ _HotelSearch.DoQuery(); });
			
		oEd.keyup(function()
		{ 
			if (_HotelSearch._Timer > 0)
				window.clearInterval(_HotelSearch._Timer);
	
			_HotelSearch._Timer = window.setTimeout(function(){
				_HotelSearch.DoQuery();
				window.clearInterval(_HotelSearch._Timer);
			},500);
		})
		.mouseover(function()
		{
			if ($(this).val() == ""){ return; }
			
			oBtClear.css("left",(oEd.position().left + oEd.width()) - 14);
			oBtClear.css("top",oEd.position().top + 1);
			oBtClear.show();
		})
		.mouseout(function() { oBtClear.hide() });
		
		oBtClear.mouseover(function(){ $(this).show() })
				.mouseout(function(){ $(this).hide() })
				.click(function(){ 
					if (oEd.disabled()){ return; }
					oEd.val(""); oEdId.val(""); 
					if (typeof HotelSearch_Clear != "undefined")
						HotelSearch_Clear();
		});
	},
	
	/*****************************************************
	*.s.
	******************************************************/
	
	DoQuery : function ()
	{
		oRequest           = {};
		oRequest.pNombre   = oEd.val();
		oRequest.pIdCadena = glData.IdCadena;
		
		Query("SV_Establecimientos.asmx/HotelSearch",oRequest,_HotelSearch.OnQuery,"Consultando Hoteles ...");
	},
	
	/*****************************************************
	*.s.
	******************************************************/
	
	OnQuery : function (result)
	{
		ProgressOff();
		var oVisor;
		var oGrid;
		var vResultado = result.Response;
		
		if ($("#dvVisorHotelSearch").length != 0)
			oVisor	= $("#dvVisorHotelSearch")
		else
		{
			oVisor	= $("<div id='dvVisorHotelSearch' class='WndBack' style='position:absolute;display:none;width:400px'></div>");
			oVisor.append("<div class='WndTitle'>" + rsEd_Name + "</div>");
			oVisor.append("<div id='dvGridHotelSearch' class='dvGrid' style='width:385px;height:250px;overflow:auto;padding:2px;margin:3px'></div>");
			
			oBt = $("<a href='' class='button' style='width:90px;float:right'><span><img src='_Images/Salir.gif' />Cerrar</span></a>");
			oBt.click(function(){
				oVisor.hide("fast");	
				return false;
			});
			
			oVisor.append(oBt);
			
			$("body").append(oVisor);
		}
			
		oGrid	= oVisor.find("#dvGridHotelSearch");
		
		str = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";
		for (i = 0;i < vResultado.length;i++)
		{
			str += "<tr><td class='tr1' onclick=\"_HotelSearch.SelHotel('" + vResultado[i].Text + "','" + vResultado[i].Value + "');\">" + vResultado[i].Text + "</td></tr>";
		}
		str += "</table>";
		
		oGrid.html(str);
	
		var Pos = oEd.offset();
		
		oVisor.css("left",Pos.left);
		oVisor.css("top",(Pos.top + oEd.outerHeight()));
		oVisor.show("fast")
	},
	
	/*****************************************************
	*.s.
	******************************************************/
	
	SelHotel : function(pNombre,pId)
	{
		oEd.val(pNombre);
		oEdId.val(pId);
		$("#dvVisorHotelSearch").hide("fast");

		if (typeof HotelSearch_Change != "undefined")
			HotelSearch_Change(oEd.val(),oEdId.val());
	}
};
window.HotelSearch = _HotelSearch.Ini;

/*******************************************************
* 
*******************************************************/

function SendClientError(pOrginen,pMetodo,pDescripcion)
{
    var oError = {};
    oError.rqOrigen         = pOrginen;
    oError.rqMetodo         = pMetodo;
    oError.rqDescripcion    = pDescripcion;
    
    var dataEnvio = $.toJSON(oError);

	$.ajax({
		async: true,
		beforeSend: function() {
		
		},
		type: "POST",
		url: "_Services/SV_Configuracion.asmx/ClientError",
		contentType: "application/json; charset=utf-8",
		datatype: "json",
		data: dataEnvio,
		success: function(dataResult) {
		    
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
		
		}
	});	           
    
}

/*******************************************************
* 
*******************************************************/

function MaxInput(oImput,iSize)
{
	if(oImput != ""){
		if($(oImput)!=null){
			iSize = parseInt(iSize);
			sText = $(oImput).value;
 	
			if (sText.length >iSize)
				$(oImput).value = sText.substr(0,iSize)
		}
	}
}

/*******************************************************
* .s Es un número. Admite decimales
* 
*******************************************************/

function IsNumber(pValor)
{
	if (pValor == "") {return false; }
	
	return 	isNaN(iVal(pValor)) ? false : true
}

/*******************************************************
* .s Establece el decimal
* 
*******************************************************/

function iVal(pValor)
{
	if (pValor == "") {return 0;}
	
	PuntoComa = (1 / 2);
	PuntoComa = String(PuntoComa).substr(1,1);
	
	pValor = String(pValor).replace(/[,.]/,PuntoComa);
	
	return pValor;
}

/*******************************************************
 * 
 * .s. Convierte en datetime fechas string en formato dd/mm/aa
 * 
 *******************************************************/

function Str2Date(sDate)
{
    
	iYear	= 2000 + parseFloat(sDate.substr(6,2));
	iMes	= sDate.substr(3,2) - 1;
	iDia	= parseFloat(sDate.substr(0,2))
	
	return new Date(iYear,iMes,iDia);
}

/*******************************************************
 * 
 * .s. Devuelve dd/mm/aa
 * 
 *******************************************************/

function Date2Str(fDate)
{
	var sDia;
	sDia = fDate.getDate() > 9 ? fDate.getDate() : "0" + fDate.getDate();

	var sMes;
	sMes = fDate.getMonth()+1 > 9 ? fDate.getMonth()+1 : "0" + (fDate.getMonth()+1);
	
	var sAno;
	sAno = fDate.getFullYear().toString().substr(2, 2);
	
	return sDia + "/" + sMes + "/" + sAno;

}

/*******************************************************
 * 
 * .s. 
 * 
 *******************************************************/
 
function InfoShow(sTxt)
{
	if (document.getElementById("divInfo"))
	{
		document.body.removeChild(document.getElementById("divInfo"));
	}	
	
	shtml = "<div class='InfoShow_Title'>&nbsp;Información</div>";
	shtml += "<table border='0' cellpadding='5' cellspacing='0' align='left'>";
	shtml += "<tr><td><img src='_Images/Warning32x32.png' /></td>";
	shtml += "<td class='InfoShow_Txt'>" + sTxt + "</td></tr>";
	shtml += "</table>";
	shtml += "<br /><br /><br />";
	
	var oDivInfo = document.createElement("DIV");
	document.body.appendChild(oDivInfo);
	oDivInfo.style.position	= "absolute";
	oDivInfo.id				= "divInfo";
	oDivInfo.className		= "InfoShow_Dv";
	oDivInfo.style.width	= "350px";
	oDivInfo.innerHTML = shtml;
	
	oDivInfo.style.left		= (document.body.clientWidth / 2) - (oDivInfo.offsetWidth / 2) + "px";
	oDivInfo.style.top		= (document.body.clientHeight / 2) - (oDivInfo.offsetHeight / 2) + "px";
	
	oDivInfo.onmousedown = function()
	{
		document.body.removeChild(document.getElementById("divInfo"));
		document.onmousedown = null;
	}
	
	document.onmousedown = function()
	{
		document.body.removeChild(document.getElementById("divInfo"));
		document.onmousedown = null;
	}
}


/*******************************************************
* 
* 
*******************************************************/

function ProgressOn(sMensaje)
{
	if (!document.body){ return; }
	
	if ($("#dvProgress").length > 0)
		var oDivProgress = $("#dvProgress");
	else
	{
		var oDivProgress  = $("<div id='dvProgress'></div>");
		$("body").append(oDivProgress);
	}
	
	shtml = "<div class='content'><div class='head'>Espera...</div>";
	shtml += "<div class='body'>";
	shtml += "<img src='_images/loadinfo.net.gif' align='absmiddle' />" + sMensaje;
	shtml += "</div></div>";
	
	oDivProgress.html(shtml);
	//oDivProgress.centerInDocument();
}

/*******************************************************
* 
* 
*******************************************************/

function ProgressOff()
{
	if ($("#dvProgress").length > 0)
		$("#dvProgress").remove();
}

/*******************************************************
* 
* 
*******************************************************/

function GetFecha(iDias)
{
	var dFecha = new Date();
	dFecha = new Date(dFecha.getFullYear(),dFecha.getMonth(),dFecha.getDate() + iDias);
	return Date2Str(dFecha);
}

/*******************************************************
* 
* 
*******************************************************/

function GetHora()
{
    var dFecha = new Date();
    return (dFecha.getHours() < 10 ? "0" + dFecha.getHours() : dFecha.getHours()) + ":" 
         + (dFecha.getMinutes() < 10 ? "0" + dFecha.getMinutes() : dFecha.getMinutes());
}

/*******************************************************
* .s. Incrementa una fecha segun sección
* .s. sFecha = dd/mm/aa
* .s. sSeccion	= d -> dia
* .s.			  m -> mes
* .s.			  a -> año
* .s.
* .s. la devolución es dd/mm/aa
*******************************************************/

function AddFecha(sFecha,sSeccion,iIncremento)
{
	iIncremento = parseInt(iIncremento);  	
	var dFecha = Str2Date(sFecha);
				
	switch (sSeccion)
	{
		case "d":
			dFecha = new Date(dFecha.getFullYear(),dFecha.getMonth(),dFecha.getDate() + iIncremento);
			return Date2Str(dFecha);
			break;
		case "m":
			dFecha = new Date(dFecha.getFullYear(),dFecha.getMonth() + iIncremento,dFecha.getDate());
			return Date2Str(dFecha);
			break;
		case "a":
			dFecha = new Date(dFecha.getFullYear() + iIncremento,dFecha.getMonth(),dFecha.getDate());
			return Date2Str(dFecha);
			break;
	}

}

/*******************************************************
* .s. Diferencia de Días
* .s. la devolución son d
*******************************************************/

function DiffFecha(sDesde,sHasta)
{
	var dDesde = Str2Date(sDesde);
	var dHasta = Str2Date(sHasta);
	return parseFloat((dHasta.getTime()- dDesde.getTime())/(86400000),0).toFixed();	
}

/*******************************************************
*
*.s. Dependencia: DiffFecha
*******************************************************/

function CompruebaDesdeHasta(pDesde,pHasta)
{
	if (pDesde == "" || pHasta == "")
		return false;

	if (DiffFecha(pDesde,pHasta) < 0)
		return false;
	
	return true;
}

/*******************************************************
* .s. Recoge el value de los checks seleccionados.
* .s. Requiere q se establezca el value.
* .s. El partialid de los checks valido
* .s. Dependencias JQuery
*******************************************************/

function GetChChurro(PartialId)
{
	sChurro = "";
	$(":checkbox[id^='" + PartialId + "']:checked").each(function()
	{
		sChurro += $(this).attr("value") + "#";
	});
	return sChurro;
}

/*******************************************************
* .s. Comprueba que no hayan más días de los especificados entre 2 fechas.
* .s. Dependencias: JQquery,diffFechas
*******************************************************/
function CheckMaxDiffDias(p$Desde,p$Hasta,pIDias)
{
    if (p$Desde.val() == ""){ return true };
    if (p$Hasta.val() == ""){ return true };
    
    if (DiffFecha(p$Desde.val(),p$Hasta.val()) < 0) {
        p$Hasta.val(AddFecha(p$Desde.val(),"d",1));
    }
    
    if (DiffFecha(p$Desde.val(),p$Hasta.val()) > pIDias) {
        alert("El margen de fechas no puede superar los " + pIDias + " días.");
        p$Hasta.val(AddFecha(p$Desde.val(),"d",365));
    }
}
/*******************************************************
* .o. Comprueba el permiso de acceso a la forma
*******************************************************/
function ComprobarPrivilegioAcceso(pIdForma) {
    if (glData.Privilegio[pIdForma] == PRIVILEGIOSINACCESO) {
        alert(glData.PermisoSinAcceso );
        history.back();
        return false;
    }
    return true;
}
/*******************************************************
* .o. Comprueba el permiso de grabar
*******************************************************/
function ComprobarPrivilegioGrabar(pIdForma) {  
    if (glData.Privilegio[pIdForma] == PRIVILEGIOCONSULTAR) {
        alert(glData.PermisoNoGrabar);
        return false;
    }
    return true;
}