
jQuery(document).ready(function(){

var lang
jQuery.lang=jQuery("#lang").html()
         






var target
var fechamin
var fechamax
var timer
var done
var defaultOptions={
url:'index.php',
type:'POST',
data:null,
dataType:'html',
cache:false,
async:false,
beforeSend:null,
success:null,
complete:null,
error:null,
target:null,
parameter:null
}



jQuery.mibojeto={

llamada:function(options){
//url,parameter,form,success,dataType,target,beforeSend,complete


jQuery.extend(defaultOptions, options)

url=$(defaultOptions).url
parameter=$(defaultOptions).parameter
form=$(defaultOptions).data
async=$(defaultOptions).async
target=$(defaultOptions).target
dataType=$(defaultOptions).dataType
beforeSend=$(defaultOptions).beforeSend
complete=$(defaultOptions).complete
success=$(defaultOptions).success



if(target!=null)
jQuery.target=target


 if(jQuery(form)[0].nodeName=='FORM')
datos=jQuery(form).serialize()
else if(typeof datos == 'object')
    datos=form

var nocache=Math.random()

if(async==undefined)
    async=false

jQuery.ajax({
    url:url+'?main='+parameter+'&nocache='+nocache,
    type:'POST',
    data:datos,
    dataType:dataType,
    cache:false,
    async:async,

    beforeSend:beforeSend,
    success:success,
    complete:complete,
    error:function(jqXHR, textStatus, errorThrown){
               if(window.console && window.console.firebug)
                {
                    console.log(jqXHR)
                    console.log(textStatus)
                    console.log(errorThrown)
                }
    }
})

}

}//End object







animatebar=function(metodo){
 var funcion=metodo
var delay
var valor
delay=parseInt(jQuery("#delay").val())

secondManualPB = new JS_BRAMUS.jsProgressBar($('progressbar'), 0,
 {
     animate: true,
     showText: true,
     boxImage	: 'http://www.costarica-rentacar.com/sys/images/bramus/custom1_box.gif',
   barImage	: Array(
										'http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back4.png',
										'http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back3.png',
										'http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back2.png',
										'http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back1.png'
									),
    onTick : function(pbObj) {

                    switch(pbObj.getPercentage()) {
                                    
                                    case 1:funcion()
                                    
                            break;

                    }

                    return true;
            },
    timing:delay*10

        }
        );


for(i=1;i<=(100/delay);i++){
    
   valor=i*delay
//   console.log(valor)
secondManualPB.setPercentage (valor)
}

return true
}

cargando=function(){

var procesando;

if(jQuery.lang=='en')
    procesando='Processing...';
    else
        procesando='Procesando...';
                 jQuery( "#contenedorprogreso" ).dialog({
			height: 80,
			modal: true,
                        title:procesando,
                         draggable: false,
                         resizable:false
		});
                
jQuery('#contenedorprogreso').show();
//jQuery.mibojeto.llamada('controlador/ctrl.reserva.php', 'delay', datafalse={value:null},null,'html',null,null,alert(valor)  )
}




completo=function(){
 
 jQuery('#contenedorprogreso').dialog("close");
jQuery('#contenedorprogreso').hide();
}

valorhtml=function(html){jQuery(jQuery.target).val(html)}

muestrahtml=function(html){jQuery(jQuery.target).html(html)}



jQuery.fechamin=parseInt(jQuery("#fechamin").val())
 jQuery.fechamax=parseInt(jQuery("#fechamax").val())


setCalendar=function (inputfield,trigger,showTime,dateFormat,min,max){

    Calendar.setup({
        inputField : inputfield,
        trigger    : trigger,
        onSelect   : function() {this.hide()},
        showTime   : showTime,
        dateFormat: dateFormat,
        min:min,
        max: max

      });
}

//Set Calendars

setCalendar("fechaentrega","calfechaentrega",false,"%Y-%m-%d",jQuery.fechamin,jQuery.fechamax)

setCalendar("fechaentrega","fechaentrega",false,"%Y-%m-%d",jQuery.fechamin,jQuery.fechamax)

setCalendar("fechadevolucion","calfechadevolucion",false,"%Y-%m-%d",jQuery.fechamin,jQuery.fechamax)

setCalendar("fechadevolucion","fechadevolucion",false,"%Y-%m-%d",jQuery.fechamin,jQuery.fechamax)

        




//Toggle check location
jQuery("#checkdevolucion").attr('checked',false)

            jQuery("#checkdevolucion").click(function(){
                if(jQuery("#checkdevolucion").is(':checked'))
                    jQuery("#divdevolucion").show()
                    else
                        jQuery("#divdevolucion").hide()
})



jQuery("#siguiente").click(function(){
        siguiente()
})



var opcionescombo1={
url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.ubicacion.php',
type:'POST',
data: '#frmprincipal',
dataType:'json',
cache:false,
async:false,
beforeSend:null,
success:combo,
complete:null,
error:null,
target:"select[name=ubicacion]",
parameter:'listar'
}

var opcionescombo2={
url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.categoria.php',
type:'POST',
data: '#frmprincipal',
dataType:'json',
cache:false,
async:false,
beforeSend:null,
success:combo,
complete:null,
error:null,
target:"#categoria",
parameter:'listarcategoria'
}

var opcionesdelay={
url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.reserva.php',
data: datos={data:null},
dataType:'html',
cache:false,
async:false,
beforeSend:null,
success:valorhtml,
complete:null,
error:null,
target:"#delay",
parameter:'delay'
}


//Get ajax in combo
//console.log(combo)
jQuery.mibojeto.llamada(opcionescombo1)
jQuery.mibojeto.llamada(opcionescombo2)
jQuery.mibojeto.llamada(opcionesdelay)



})








valorfecha=function(fecha){
var array = new Array()
var arraytiempo
arrayfecha=fecha.substr(0, 10).split('-')

arraytiempo=fecha.substr(10,6).replace(/^\s*|\s*jQuery/g,"").split(':')

horario=fecha.substr(16,3).replace(/^\s*|\s*jQuery/g,"")
//console.log(horario)
//console.log(arraytiempo)

if(parseInt(arraytiempo[0])==12){
    arraytiempo[0]=parseInt(arraytiempo[0])-12
}

if(horario=='PM'){
    arraytiempo[0]=parseInt(arraytiempo[0])+12
    
}
    

array=arrayfecha.concat(arraytiempo)

return(array)

}

siguiente=function (){
var funcion




   jQuery("#ubicacionentregavalor").val(jQuery("#selectubicacionentrega").val())
            jQuery("#ubicacionentregatexto").val(jQuery("#selectubicacionentrega option:selected").text())


      if(jQuery("#checkdevolucion").is(':checked')){
            jQuery("#ubicaciondevolucionvalor").val(jQuery("#selectubicaciondevolucion").val())
            jQuery("#ubicaciondevoluciontexto").val(jQuery("#selectubicaciondevolucion option:selected").text())
    }
    else
        {
                jQuery("#ubicaciondevolucionvalor").val('')
                jQuery("#ubicaciondevoluciontexto").val('')

        }



   //Especificando datos a enviar porque añadi un select tag
var categoria=jQuery('#categoria').val()
var fechadevolucion=jQuery('#fechadevolucion').val()+' '+jQuery("#tiempodevolucion").val()
var  fechaentrega=jQuery('#fechaentrega').val()+' '+jQuery("#tiempoentrega").val()
var ubicaciondevoluciontexto =jQuery('#ubicaciondevoluciontexto').val()
var ubicaciondevolucionvalor =jQuery('#ubicaciondevolucionvalor').val()
var ubicacionentregatexto =jQuery('#ubicacionentregatexto').val()
var ubicacionentregavalor =jQuery('#ubicacionentregavalor').val()

var fecha1=valorfecha(fechadevolucion)
var fecha2=valorfecha(fechaentrega)

var d1 = new Date(fecha1[0], fecha1[1], fecha1[2], fecha1[3], fecha1[4]);
var d2 = new Date(fecha2[0], fecha2[1], fecha2[2], fecha2[3], fecha2[4]);


//console.log(fecha1)
//console.log(fecha2)




diferenciadias=DateDiff.inDays(d2, d1)

if(diferenciadias<0){
        fechavacia('Las fecha de entrega es menor que la de devolucion')
            return false
}


if(diferenciadias==0){

diferenciatiempo=DateDiff.inHours(d2, d1)

        if(diferenciatiempo<=0){
        fechavacia('El tiempo seleccionado es demasiado corto revise')
            return false
        }
}


 


    datos={
        categoria:categoria,
        fechadevolucion:fechadevolucion,
        fechaentrega:fechaentrega,
        ubicaciondevoluciontexto:ubicaciondevoluciontexto,
        ubicaciondevolucionvalor:ubicaciondevolucionvalor,
        ubicacionentregatexto:ubicacionentregatexto,
        ubicacionentregavalor:ubicacionentregavalor
    }
    jQuery('#paso1').hide()




 funcion  = function(){
     var opciones={
            url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.reserva.php',
            type:'POST',
            data:datos,
            dataType:'html',
            cache:false,
            async:true,
            beforeSend:cargando,
            success:function(html){
                if(html.toUpperCase()=='ERROR'){
                    jQuery("#paso2").hide()
                    //alert('No existen moviles disponibles con estos criterios')             
                    jQuery("#paso1").show()

              doerror()

                    }
                else
                    jQuery(jQuery.target).html(html)
            },
            complete:completo,
            error:null,
            target:"#paso2",
            parameter:'mostrarvehiculo&lang='+jQuery.lang
    }

     return    jQuery.mibojeto.llamada(opciones)
 }

animatebar(funcion)



   jQuery('#paso2').show()


return true

}


mostrardiventrega=function (){

    jQuery("#divupdentrega").show()
    jQuery("#selectubicacionentregamod").html(jQuery("#selectubicacionentrega").html())
setCalendar("fechaentregamod","calfechaentregamod",12,"%Y-%m-%d %I:%M %p",jQuery.fechamin,jQuery.fechamax)
setCalendar("fechaentregamod","fechaentregamod",12,"%Y-%m-%d %I:%M %p",jQuery.fechamin,jQuery.fechamax)
}



mostrardivdevolucion=function (){
    jQuery("#divupddevolucion").show()

    jQuery("#selectubicaciondevolucionmod").html(jQuery("#selectubicaciondevolucion").html())
    
setCalendar("fechadevolucionmod","calfechadevolucionmod",12,"%Y-%m-%d %I:%M %p",jQuery.fechamin,jQuery.fechamax)
setCalendar("fechadevolucionmod","fechadevolucionmod",12,"%Y-%m-%d %I:%M %p",jQuery.fechamin,jQuery.fechamax)



}

fechavacia=function(val){
    
    if(val==undefined)
        val='Ingrese una fecha,'
                              jQuery( "#dialog-modal" ).html(val)

                                     jQuery( "#dialog-modal" ).dialog({
                                            height: 120,
                                            modal: true,
                                            title:'Oops',
                                             draggable: false,
                                             resizable:false
                                    });
                                    jQuery( "#dialog-modal" ).dialog( "option", "buttons", [
                                    {
                                        text: "Ok",
                                                click: function() { jQuery(this).dialog("close"); }
                                    }
                                  ] );
}
doerror=function(){

                jQuery( "#dialog-modal" ).html(' No tenemos un automovil disponible <br/>con el rango de fechas seleccionado.')
                 jQuery( "#dialog-modal" ).dialog({
			height: 120,
			modal: true,
                        title:'Lo sentimos...',
                         draggable: false,
                         resizable:false
		});
                jQuery( "#dialog-modal" ).dialog( "option", "buttons", [
                {
                    text: "Ok",
                            click: function() { jQuery(this).dialog("close"); }
                }
              ] );
}


dosuccess=function(){

                jQuery( "#dialog-modal" ).html('Ha registrado su reservacion correctamente')
                 jQuery( "#dialog-modal" ).dialog({
			height: 120,
			modal: true,
                        title:'Agradecemos su preferencia',
                         draggable: false,
                         resizable:false
		});
                jQuery( "#dialog-modal" ).dialog( "option", "buttons", [
                {
                    text: "Ok",
                            click: function() { jQuery(this).dialog("close");
                        jQuery("#paso3").hide()
                        window.location.reload()
                                }
                }
              ] );
}

moddevolucion=function(){

    var fecha1=valorfecha(jQuery("input[name=fechadevolucionmod]").val())
var fecha2=valorfecha(jQuery("input[name=fechaentrega]").val())
var d1 = new Date(fecha1[0], fecha1[1], fecha1[2], fecha1[3], fecha1[4]);
var d2 = new Date(fecha2[0], fecha2[1], fecha2[2], fecha2[3], fecha2[4]);

diferenciadias=DateDiff.inDays(d2, d1)

if(diferenciadias<0){
        fechavacia('Las fecha de entrega es menor que la de devolucion')
            return false
}


if(diferenciadias==0){

diferenciatiempo=DateDiff.inHours(d2, d1)


        if(diferenciatiempo<=0){
        fechavacia('El tiempo seleccionado es demasiado corto revise')
            return false
        }
}


    if(jQuery("#fechadevolucionmod").val()=='')
      {
          
        fechavacia()
                              return false
      }


     fecha=jQuery("#fechadevolucionmod").val()
     lugar=jQuery("#selectubicaciondevolucionmod").val()
     textolugar=jQuery("#selectubicaciondevolucionmod option:selected").text()
     textofecha=formatofecha(fecha)

    jQuery("input[name=fechadevolucion]").val(fecha)
    jQuery("input[name= sugtextolugardevolucion]").val(textolugar)
    jQuery("input[name=suglugardevolucion]").val(lugar)



        jQuery("#spanlugardevolucion").text(textolugar)
        jQuery("#textolugardevolucion").val(textolugar)
        jQuery("#spanfechadevolucion").text(textofecha)


    jQuery("#divupddevolucion").hide()
    jQuery("#divshowdevolucion").fadeIn(2000)
    //jQuery("#divshowdevolucion").slideUp('slow')

    return true
}


cancelarmoddevolucion=function(){
 jQuery("#divupddevolucion").hide()
    jQuery("#divshowdevolucion").show()
}



modentrega=function(){


var fecha1=valorfecha(jQuery("input[name=fechadevolucion]").val())
var fecha2=valorfecha(jQuery("input[name=fechaentregamod]").val())
var d1 = new Date(fecha1[0], fecha1[1], fecha1[2], fecha1[3], fecha1[4]);
var d2 = new Date(fecha2[0], fecha2[1], fecha2[2], fecha2[3], fecha2[4]);

diferenciadias=DateDiff.inDays(d2, d1)

if(diferenciadias<0){
        fechavacia('Las fecha de entrega es menor que la de devolucion')
            return false
}


if(diferenciadias==0){

diferenciatiempo=DateDiff.inHours(d2, d1)

        if(diferenciatiempo<=0){
        fechavacia('El tiempo seleccionado es demasiado corto revise')
            return false
        }
}




    datos={
categoria:null,
vehiculo:jQuery("input[name=idvehiculo]").val(),
fechadevolucion	:jQuery("input[name=fechadevolucion]").val(),
fechaentrega:jQuery("input[name=fechaentregamod]").val()
    }
    
var entregaerror=false
    jQuery.ajax({
          url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.reserva.php?main=mostrarvehiculo',
           type:'POST',
            data:datos,
            dataType:'html',
            cache:false,
            async:false,
               success:function(html){
                if(html.toUpperCase()=='ERROR'){                                                          

                       jQuery.entregaerror=true
                    }
                    else{
                            jQuery.entregaerror=false
                    }

            }
    })

    if( jQuery.entregaerror==true)
        {
            doerror()
            return false
        }

    if(jQuery("#fechaentregamod").val()==''){
        fechavacia()
        return false
    }
        


         fecha=jQuery("#fechaentregamod").val()
     lugar=jQuery("#selectubicacionentregamod").val()
     textolugar=jQuery("#selectubicacionentregamod option:selected").text()
     textofecha=formatofecha(fecha)
    console.log(textofecha)

    jQuery("form#frmsecond input[name=fechaentrega]").val(fecha)
    jQuery("input[name= sugtextolugarentrega]").val(textolugar)
    jQuery("input[name=suglugarentrega]").val(lugar)
    jQuery("#spanlugarentrega").text(textolugar)
    jQuery("#textolugarentrega").val(textolugar)
    jQuery("#spanfechaentrega").text(textofecha)


    jQuery("#divupdentrega").hide()
    jQuery("#divshowentrega").fadeIn(2000)

    return true
}


cancelarmodentrega=function(){
 jQuery("#divupdentrega").hide()
    jQuery("#divshowentrega").show()
}




formatofecha=function(valor){
       matriz =new Array;
    cal=valor.substr(0,10).split('-')
    arreglo= matriz.concat(cal,valor.substr(11,2),valor.substr(14,2),valor.substr(17,2))


    anio=arreglo[0]
    mes=parseInt(arreglo[1],10)-1
    dia= parseInt(arreglo[2],10)
    hora=parseInt(arreglo[3],10)
    minuto=arreglo[4]

    horario=arreglo[5]

    if(horario=='PM'){
        if(hora==12)
            hora=0
        else
        hora+=12
        }
     var midate = new Date(anio, mes,dia,hora , minuto, 0);
//     console.log(arreglo)
//     console.log(midate)

    return dateFormat(midate, "dddd, mmmm dd, yyyy hh:MM TT");  //TT


}



sugerencia=function(idcategoria,idvehiculo){
jQuery("#paso2").hide()


    fechaentrega=jQuery("input[name=fechaentrega]").val()
    ubicacionentregatexto=jQuery("input[name=sugtextolugarentrega]").val()
    ubicacionentregavalor=jQuery("input[name=suglugarentrega]").val()

    fechadevolucion=jQuery("input[name=fechadevolucion]").val()
    ubicaciondevolucionvalor=jQuery("input[name=suglugardevolucion]").val()
    ubicaciondevoluciontexto=jQuery("input[name=sugtextolugardevolucion]").val()


    datos={
        categoria:idcategoria,
        vehiculo:idvehiculo,
        fechaentrega:fechaentrega,
        ubicacionentregatexto:ubicacionentregatexto,
        ubicacionentregavalor:ubicacionentregavalor,
        fechadevolucion:fechadevolucion,
        ubicaciondevolucionvalor:ubicaciondevolucionvalor,
        ubicaciondevoluciontexto:ubicaciondevoluciontexto
    }




 funcion  = function(){
     var opciones={
            url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.reserva.php',
            type:'POST',
            data:datos,
            dataType:'html',
            cache:false,
            async:true,
            beforeSend:cargando,
            success:muestrahtml,
            complete:completo,
            error:null,
            target:"#paso2",
            parameter:'mostrarvehiculo'
    }

     return    jQuery.mibojeto.llamada(opciones)
 }

animatebar(funcion)


    
       jQuery("#paso2").show()


}

clickseleccion=function (){
//Agrega los accesorios dinamcamente al formulario =)
  


 jQuery("#paso2").hide()


 funcion  = function(){
     var
   opcionesseleccion={
            url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.reserva.php',
            type:'POST',
            data:"#frmsecond",
            dataType:'html',
            cache:false,
            async:true,
            beforeSend:cargando,
            success:muestrahtml,
            complete:completo,
            error:null,
            target:"#paso3",
            parameter:'confirmaseleccion&lang='+jQuery.lang
    }

     return       jQuery.mibojeto.llamada(opcionesseleccion)
 }

animatebar(funcion)



    
    jQuery("#paso3").show()
  
jQuery.timer=setInterval('validarform()',5000)
}


validarform=function(){



if(jQuery.done!=1)
    {


  if(jQuery("#frmprocesareserva").length){
        jQuery.done=1

        jQuery("#buttonprocesar").attr('onclick','')

                jQuery.validator.setDefaults({
                    submitHandler: function() {
            procesar()
                    }
                })


            jQuery("#frmprocesareserva").validate({
                    rules: {
                                nombres:{required:true,minlength: 3},
                                apellidos: {required: true,minlength: 3},
                                telefono:{required:true,minlength:5},
                                email: {required: true,email: true},
                                pais:{required:true},
                                estado:{required:true},
                                ciudad:{required:true},
                                codpostal:{required:true},
                                direccion:{required:true}

                            },
                            messages: {
                                    nombres: {required:(jQuery.lang=='es')?"Digite su nombre":'Type your name' ,minlength:(jQuery.lang=='es')?"Debe tener mas de 3 caracteres":"Should have more than 3 characters"},
                                apellidos: {required: (jQuery.lang=='es')?"Ingrese sus apellidos":"Type your sourname",minlength:(jQuery.lang=='es')?"Debe tener mas de 5 caracteres":"Should have more than 5 characters"},
                                telefono:{required: (jQuery.lang=='es')?"Ingrese su N&uacute;mero de tel&eacute;fono":"Type your phone numbre",digits:(jQuery.lang=='es')?"Ingrese solo digitos":"Type only digits"},
                                email:{required: (jQuery.lang=='es')?"Ingrese su correo electronico":"Type your email",email:(jQuery.lang=='es')?"Formato de correo invalido":"Invalid format"},
                                pais:{required:(jQuery.lang=='es')?"Ingrese pais":"Type your country"},
                                estado:{required:(jQuery.lang=='es')?"Ingrese su estado/canton":"Type your state"},
                                ciudad:{required:(jQuery.lang=='es')?"Ingrese su ciudad":"Type your city"},
                                codpostal:{required:(jQuery.lang=='es')?"Ingrese codigo postal":"Type your zip code"},
                                direccion:{required:(jQuery.lang=='es')?"Ingrese direccion":"Type your address"}

                            }

            });
      }

}else{
clearTimeout(jQuery.timer)
}

}

retroceder=function(v){
    switch (v) {
        case 'irpaso1':jQuery("#paso2").html(''),jQuery("#paso1").show();break;
       case 'irpaso2':jQuery("#paso3").html(''),jQuery("#paso2").show();break;
       case 'irpaso3':jQuery("#paso4").html(''),jQuery("#paso3").show();break;
        default:break;
    }


}


procesareserva=function(json){
//console.info(json.contenido)
    jQuery("ul#error").html('')

   if(json.resultado.toLowerCase()=='error')
    {
            jQuery("div#error").show()
        for (var key in json.contenido) {
          li=document.createElement('li')
         jQuery(li).html(json.contenido[key])
     
            jQuery("ul#error").append(jQuery(li))

                  }
    }else{
//        jQuery("#paso3").hide()
        jQuery("div#error").hide()

            dosuccess()

    }
}


procesar=function(){



 funcion  = function(){
     var
   opcionessproceso={
            url:'http://www.costarica-rentacar.com/sys/controlador/ctrl.reserva.php',
            type:'POST',
            data:"#frmprocesareserva",
            dataType:'json',
            cache:false,
            async:true,
            beforeSend:cargando,
            success:procesareserva,
            complete:completo,
            error:null,
            target:"#paso4",
            parameter:'procesareserva&lang='+jQuery.lang
    }

     return        jQuery.mibojeto.llamada(opcionessproceso)
 }

animatebar(funcion)


   


}


function precarga(){ // v2005-05-22
    var argv=precarga.arguments;
    var argc=precarga.arguments.length
    if(!document.precarga_img){
        document.precarga_img=new Array();
    }

    for(var i=0; i<argc; i++){
        var j=document.precarga_img.length;
        document.precarga_img[j]=new Image();
        document.precarga_img[j].src=argv[i];
    }
}

precarga('http://www.costarica-rentacar.com/sys/libreria/img/up-disabled.gif')
precarga('http://www.costarica-rentacar.com/sys/images/bramus/percentImage.png')
precarga('http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back.png')
precarga('http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back1.png')
precarga('http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back2.png')
precarga('http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back3.png')
precarga('http://www.costarica-rentacar.com/sys/images/bramus/percentImage_back4.png')
