﻿//.s.

//.s. Constantes
var bDebug = true; 

/*******************************************************
* .s. Extends de Prestige de JQUERY
* 
*******************************************************/

var PrestigeJS =
{
    /**************************************/
    //.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. Control del val para IE
    /**************************************/
    getVal: function() {
        
        var value = $(this).val();
        if (typeof value == "undefined") {
            return "";
        }
        
        return value;
    },
    /**************************************/
    //.s.valor para elemtos CB
    /**************************************/
    cbVal : function(pval) {
        
        if (pval != undefined) {
            $(this).attr("selectedValue",pval)
            return;
        }
        else {
            var val = $(this).attr("selectedValue");
            return (val == undefined ? "" : val);
        }
    }
};

//.s. Aplico Extends
(function($){ $.fn.extend(PrestigeJS) })(jQuery);

/*******************************************************
* 
* 
*******************************************************/
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); //.s. La 'd' la pone asp.net
            }
            catch (e) {
            
                SendClientError("BE", pMetodo, "ERROR AL EVALUAR JSON:<br/>" + e.description + "<br/>dataSend:" + dataEnvio + "<br/>dataResult:" + dataResult.d);
                if (bDebug) { throw e; }
                return;
            }
            try {
                //.s. Invocación del callback
                pCallBack(result);
            }
            catch (e) {
                SendClientError("BE", pMetodo, "ERROR AL INVOCAR EL 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 = ERROR_CONEXION;
                }
            }

            if (bDebug) { alert(strError); }
            Error(strError);
        },
        complete: function() {
            
        }
    });
}

/*******************************************************
* .s. Error en el script
* .s. No utilizar acentos en los mensajes
*******************************************************/

function Error(pMsg)
{
	if (typeof pMsg == "object")
	{
	    sError = "";
	    if (pMsg.get_exceptionType)
		    sError += "Excep:" + pMsg.get_exceptionType() + "@@";
	
	    if (pMsg.get_message)
		    sError += "Mensanje:" + pMsg.get_message() + "@@";
		
		pMsg = sError;
	}
	
	Params = "";
	Params += "msg=" + pMsg + "&";
	Params += "channelkey=" + GetUrlParam("channelkey") + "&";
	Params += "refer=" + escape(window.location.href) + "&";
	
	window.location.href = "Error.aspx?" + Params;
	return;
}

/*******************************************************
* 
*******************************************************/
function SendClientError(pOrginen, pMetodo, pDescripcion) 
{
    var oError = {};
    oError.Origen                  = pOrginen;
    oError.Metodo                  = pMetodo;
    oError.Descripcion             = pDescripcion;
    oError.RequestHeader_Host      = RequestHeader_Host;
    oError.RequestHeader_Referer   = RequestHeader_Referer;    
    oError.Request_Address         = Request_Address;
    oError.Request_UserAgent       = Request_UserAgent;
    
    var Request = {};
        Request.rqError = $.toJSON(oError);
    
    var dataEnvio = $.toJSON(Request);
    
    $.ajax({
        async: true,
        beforeSend: function() {

        },
        type: "POST",
        url: "_Services/WebApp.asmx/ClientError",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: dataEnvio,
        success: function(dataResult) {

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

        }
    });
}
/*******************************************************
 * 
 *******************************************************/
function GetUrlParam(param,url)
{
	if (!url)
		url = window.location.href;
	
	param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+param+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(url);
	if( results == null )
		return "";
	else
		return results[1];
}
/*******************************************************
 * 
 *******************************************************/
function getDomain(pUrl) {
    if (pUrl == ""){ return "localhost" }
    if (pUrl.indexOf("localhost") > -1){ return "localhost" }
	var host = pUrl;
	host = host.split("/");
	host = host[2];
	var domain = host.split(".");
    domain = domain[domain.length - 2] + "." + domain[domain.length - 1];
	return domain;	
}

/*******************************************************
 * .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. Devuelve dd enero aa
 *******************************************************/
function Str2StrMonth(fDate)
{
	var result = "";
    try
	{
		result += fDate.substr(0, 2);
		result += " " + vMeses[parseInt(fDate.substr(3, 2)-1)] + " ";
		result += fDate.substr(6, 2);
	}
	catch (Exception)
	{ }

	return result;
}
/*******************************************************
 * .s. 
 *******************************************************/
function DateAddDays(pFecha,pDias)
{
	var d = Str2Date(pFecha);
	var d2 = new Date(d.getFullYear(),d.getMonth(),d.getDate() + pDias);
	return Date2Str(d2);
}
/*******************************************************
* 
*******************************************************/
function GetFecha(iDias)
{
	var dFecha = new Date();
	
	dFecha = new Date(dFecha.getFullYear(),dFecha.getMonth(),dFecha.getDate() + iDias);
	
	return Date2Str(dFecha);
}
/*******************************************************
* .s. Incrementa una fecha segun sección
* .s. sFecha = dd/mm/aa
* .s. sSeccion	= d -> dia m -> mes a -> año
* .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;
	}

}
/*******************************************************
* Diferencia de Días
* la devolución son d
*******************************************************/
function DiffFecha(sDesde,sHasta)
{
	var dDesde = Str2Date(sDesde);
	var dHasta = Str2Date(sHasta);
	
	return parseInt((dHasta.getTime()- dDesde.getTime())/(86400000),0);	
}

/*******************************************************
* 
*******************************************************/
var progressCount = 0;
function ProgressOn(sMensaje)
{
	if (!document.body){ return; }
	
	progressCount++;
	
	if ($("#winProgress").size() > 0) {
	    var $progress = $("#winProgress");
	}
	else {
	    var $progress = $("<div id='winProgress'></div>");
	    $("body").append($progress);
	}
	
	shtml = "<div class='content'><div class='head'>Booking Engine</div>";
	shtml += "<div class='body'>";
	shtml += "<img src='_imagestemplate/clock4.png' align='absmiddle' />" + sMensaje;
	shtml += "</div></div>";

	$progress.html(shtml);
}
/*******************************************************
* 
*******************************************************/
function ProgressOff()
{
    $("#winProgress").remove();
}
/*******************************************************
* 
*******************************************************/
function iVal(pVal)
{
    try{
        return parseInt(pVal);
    }
    catch(e){
        return 0;  
    }
}
/*******************************************************
* 
******************************************************/
function PuntoComa(pNum)
{
	try {
		m_PuntoComa = (1/2).toString().substring(1,2);
		return parseFloat(pNum.replace(".",m_PuntoComa).replace(",",m_PuntoComa));
	}
	catch(e) {
		//.s. Si el número no tiene ni punto ni coma
		return pNum
	}
}
/*******************************************************
* 
*******************************************************/
function Round(pNum)
{
	return Math.round(pNum * 100) / 100;
}
/*******************************************************
* .o.
*******************************************************/
function ValidarFechas(pIdDesde, pIdHasta)
{
    if ($(pIdDesde).val().indexOf("/") == -1 || $(pIdHasta).val().indexOf("/") == -1) {
        $(pIdDesde).val(GetFecha(0));
        $(pIdHasta).val(GetFecha(1));
        return;
    }
    
    if($(pIdDesde).val().length != 8 || $(pIdHasta).val().length != 8){
        $(pIdDesde).val(GetFecha(0));
        $(pIdHasta).val(GetFecha(1));
        return;
    }
    var sDifFecha = DiffFecha($(pIdDesde).val(), $(pIdHasta).val());
    if(isNaN(sDifFecha)){
        $(pIdDesde).val(GetFecha(0));
        $(pIdHasta).val(GetFecha(1));
        return;
    }
    if(sDifFecha <= 0){
        $(pIdDesde).val(GetFecha(0));
        $(pIdHasta).val(GetFecha(1));
        return;
    }
}

/*******************************************************
* 
*******************************************************/
function CompruebaTarjeta(sTarjeta)
{
	ln_sum = 0;
	ln_peso = 2;
	ln_digito = 0;
	ln_longitud = sTarjeta.length;
	ln_contador = ln_longitud - 1;

	try{
		parseInt(sTarjeta);
	}
	catch (e){
		return true;
	}

	if (ln_longitud <= 0) { return true; }

	while (ln_contador > 0)
	{
		ln_digito = ln_peso * (parseInt(sTarjeta.substr((ln_contador - 1), 1)));
		if (ln_digito == 0)	{
			ln_sum = ln_sum + ln_digito % 10;
		}
		else {
			x = (Math.log(ln_digito) / Math.log(10));
			n = Math.floor(x);
			ln_sum = ln_sum + parseInt(n.toString()) + ln_digito % 10;
		}

		if (ln_peso == 2){
			ln_peso = 1;
		}
		else {
			ln_peso = 2;
		}
		ln_contador--;
	}

	lAux = ln_sum % 10;
    lAux = (10 - lAux) % 10;

	if (lAux == parseInt(sTarjeta.substr(sTarjeta.length - 1)))	{
		return false;
	}
	else {   
		return true;
	}
}
/*******************************************************
* 
*******************************************************/
function validarEmail(pMail) 
{
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(pMail);

}
/*******************************************************/
///	<summary>
/// .s. rellena un array con enteros para combo
///	.s. []{'text' : i,'value' : i}
///	</summary>
///	<returns type="Array" />
function cbCreateValues(pMin,pMax) {
    
    
    var arr = []; var pos = 0;
    for (i = pMin;i <= pMax;i++) {
        arr[pos] = {'text' : i,'value' : i};
        pos++;
    }
    return arr;
}
/*******************************************************/
///	<summary>
/// .s. Devuelve el tipo de tarjeta apartir del número
/// .s. Return: Obj.id, Obj.nombre
///	</summary>
///	<param name="pNumeroTarjeta" type="String">El número de tarjeta</param>
///	<returns type="Object"/>
//.s. Basado en http://en.wikipedia.org/wiki/Bank_card_number
function getTipoTarjeta(pNumeroTarjeta) {
    
    var VISA            = {"nombre" : "Visa",           "id" : "1", "prefix" : ["4"]};
    var MASTERCARD      = {"nombre" : "Mastecard",      "id" : "2", "prefix" : ["51","52","53","54","55"]};
    var VISAELECTRON    = {"nombre" : "Visa Electro",   "id" : "3", "prefix" : ["4175","4917","4913","4508","4844","4026"]};
    var MAESTRO         = {"nombre" : "Maestro",        "id" : "4", "prefix" : ["5018","5020","5038","6304","67592","6761","6763"]};
    var AMEX            = {"nombre" : "Amex",           "id" : "5", "prefix" : ["34","37"]};
    var DINNERS         = {"nombre" : "Dinners",        "id" : "6", "prefix" : ["300","301","302","303","304","305","2014","2149","36","54","55"]};

    //.s. el orden importa.Visa electron tambien empieza por 4 como visa.
    var tarjetas = [VISAELECTRON,VISA,MAESTRO,AMEX,DINNERS];
    
    var result      = {};
    result.id       = "";
    result.nombre   = "";
    
    $(tarjetas).each(function(i,tarjeta){
        $(tarjeta.prefix).each(function(j,prefix){
            var posPrefix = pNumeroTarjeta.indexOf(prefix);
            if (posPrefix == 0) {
                result.id       = tarjeta.id;
                result.nombre   = tarjeta.nombre;
                return false;
            }
        });
        //.s. ya tengo la tarjera
        if (result.id != "") { return false };
    });
    
    if (result.id == "") {
        result.id       = "1";
        result.nombre   = "Visa";
    }
    return result;
}
/*******************************************************
 * .s. funciones de tracking
 *******************************************************/
function bookingTrack(msg){

	if (!mFullIntegration){ return; }
	
	try{
		var datos = getFiltros();
		var _msg = {
			source			: "",
			action			: "",
			from			: datos.Desde,
			to				: datos.Hasta,
			country			: datos.Pais,
			state			: datos.Zona,
			destination		: datos.Destino,
			hotel			: datos.Establecimiento,
			product			: "",
			amount			: ""
		};
		//.s. extends del lo que paso
		for (var propiedad in _msg) {
			if (msg.hasOwnProperty(propiedad)){				
				_msg[propiedad] = msg[propiedad];
			}
		}
   	
		parent.psBookingTrack(_msg);
	}
	catch(e){ 
	}
}
/*******************************************************
 * .s. funciones de tracking
 *******************************************************/
function bookingTrackReservation(reserva,localizador) {
	if (!mFullIntegration){ return; }
	
	try{
	
		var _reserva = {};
		_reserva.customerDNI		= reserva.Titular.DNI;
		_reserva.customerEmail		= reserva.Titular.Email;
		_reserva.customerName		= reserva.Titular.Nombre;
		_reserva.customerSurname	= reserva.Titular.Apellido1;
		_reserva.customerCountry	= reserva.Titular.Pais;
		_reserva.customerTelephone	= reserva.Titular.Telefono;
		_reserva.observations		= reserva.Observaciones;
		_reserva.mailing			= reserva.Mailing;
		_reserva.total				= $("#totalReservaFinal").html();
		_reserva.locator			= localizador;
		_reserva.products			= [];
		
		for (i = 0; i < reserva.Paquetes.length; i++) {
			var item    = mCesta.Paquetes[i];
			var product = {};
			product.from		= item.Desde;
			product.to			= item.Hasta;
			product.id			= item.Id;
			product.name		= item.Nombre;
			product.amount		= getTotal(item.Total);
			product.hotel		= item.Establecimiento;
			product.adults		= item.Adultos;
			product.childrens	= item.Nenes;
			product.infants		= item.Bebes;
			
			_reserva.products.push(product);
		}
		
		for (i = 0; i < reserva.Servicios.length; i++) {
			var item    = mCesta.Servicios[i];
			var product = {};
			product.from		= item.Intervalo;
			product.to			= "";
			product.id			= item.Id;
			product.name		= item.Nombre;
			product.amount		= getTotal(item.Total);
			product.hotel		= item.Establecimiento;
			product.adults		= item.Adultos;
			product.childrens	= item.Nenes;
			product.infants		= item.Bebes;
			
			_reserva.products.push(product);
		}
	
		parent.psBookingTrackReservation(_reserva);
	}
	catch(e){		
	}
	
}