//Script general para Nosotros Turismo

$(document).ready(function() {

	//incluir todo codigo JQuery que se tiene que ejecutar a refresco de la página
	//ajustarCamposFechas();
	//altConfirm();
	
	chequearBotonAgregar();
});

function verDetalle(id_pac)
{
	cargarFormularioPorURL( "Detalles", "detalle.php?id_pac="+id_pac );
}

function cargarFormularioPorURL( titulo, strurl )
{
	processingStart()
	$.ajax({
		url: strurl,
		async: true,
		success: function(data) {
			
			str='<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">';
			str+='<div class="modal-dialog modal-lg">';
			str+='<div class="modal-content">';
			str+='<div class="modal-header">';
			//str+='        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
			str+='        <h4 class="modal-title" id="myModalLabel">'+titulo+'</h4>';
			str+='      </div>';
			str+='      <div class="modal-body">';
			str+=data;
			str+='      </div>';
			str+='      <div class="modal-footer">';
			str+='        <button type="button" class="btn btn-primary" data-dismiss="modal">Cerrar</button>';
			//str+='        <button type="button" class="btn btn-primary">Save changes</button>';
			str+='      </div>';
			str+='    </div>';
			str+='  </div>';
			str+='</div>';
			
			
			processingStop();
			$("body").append(str);
			$('#myModal').modal('show').on('hidden.bs.modal', function( event ) { $(this).remove(); });
		}
	});
}

function respuestaViaje(data)
{
	//data devolverá el ok o el dato de error
	var obj = JSON.parse(data);
	
	if(obj.status == "OK")
	{//alert('working');
		//window.location.href="listadoviajes.php";
		window.location=window.location;
		return;
	}
	error(obj.message);
	//$("#error").html(obj.message).show();
}

function processingStart() 
{
	//Si no est\E1 definido, lo agrego
	
	var opts = {
		lines: 11, // The number of lines to draw
			length: 15, // The length of each line
			width: 5, // The line thickness
			radius: 15, // The radius of the inner circle
			corners: 1, // Corner roundness (0..1)
			rotate: 0, // The rotation offset
			direction: 1, // 1: clockwise, -1: counterclockwise
			//color: '#000', // #rgb or #rrggbb or array of colors
			color: '#dd4814', // #rgb or #rrggbb or array of colors
			speed: 1, // Rounds per second
			trail: 60, // Afterglow percentage
			shadow: false, // Whether to render a shadow
			hwaccel: false, // Whether to use hardware acceleration
			className: 'spinner', // The CSS class to assign to the spinner
			zIndex: 2e9, // The z-index (defaults to 2000000000)
			top: 'auto', // Top position relative to parent in px
			left: 'auto' // Left position relative to parent in px
		};

	if( ! $("#spinner-div"). length )
	{
		div="<div id=\"spinner-div\" style=\"width:100px; height:100px\"></div>";	
		$("body").append(div);
	}
	$.blockUI({ message: $("#spinner-div"),  noHide: true, 
						   css: {
							   top:  ($(window).height() - 100) /2 + 'px', 
							   left: ($(window).width() - 100) /2 + 'px',
							   width: '100px',
							   cursor: 'auto', border: 'none', background:'none'
							   } 
	});

	// Reference: http://fgnass.github.io/spin.js
	$("#spinner-div").spin(opts);
}

function processingStop()
{
	if( $("#spinner-div"). length ) 
		$('#spinner-div').spin(false);
	$.unblockUI();
}



function ajustarCamposFechas(parent)
{
	aux=(parent)?(parent+" "):"";
	
	$(aux+' div .date-pick-past').each( function(index) {
		//if( $(this).attr('readonly')!="readonly" && $(this).attr('disabled')!="disabled" )
		{
			$(this).datetimepicker({
                    locale: 'es',
					format: 'L',
					maxDate: new Date
                });
			$(this).data('DateTimePicker').maxDate(new Date);
		}
		if( $(this).attr('readonly')=="readonly" || $(this).attr('disabled')=="disabled" )
			$(this).data('DateTimePicker').disable();
	});
	
	$(aux+' div .date-pick').each( function(index) {
		//if( $(this).attr('readonly')!="readonly" && $(this).attr('disabled')!="disabled" )
		{
			$(this).datetimepicker({
                    locale: 'es',
					format: 'L',
					minDate: new Date
                });
			$(this).data('DateTimePicker').minDate(new Date);
		}
		if( $(this).attr('readonly')=="readonly" || $(this).attr('disabled')=="disabled" )
			$(this).data('DateTimePicker').disable();
	});
	$(aux+' div .date-pick-all').each( function(index) {
		//if( $(this).attr('readonly')!="readonly" && $(this).attr('disabled')!="disabled" )
		//{
			$(this).datetimepicker({
                    locale: 'es',
					format: 'L'
                });
		//}
		if( $(this).attr('readonly')=="readonly" || $(this).attr('disabled')=="disabled" )
			$(this).data('DateTimePicker').disable();
	});
}

function AjaxForm( form, respuesta, precondicion )
{
	//if(!respuesta) respuesta=respuestaFiltro;
	
	$(form).ajaxForm({ beforeSubmit: function(arr, $form, options){
										if(precondicion){
											if(!precondicion()) return false;
										}
										processingStart();
									},
							success: function(data){
										processingStop();
										//alert("ppp");
										if(respuesta) respuesta(data);
									}
					});
}



function altConfirm()
{
    var box = '<div class="modal" id="confirm" data-backdrop="static" tabindex="-1" role="dialog">';
        box += '<div class="modal-dialog">';
            box += '<div class="modal-content">';
                box += '<div class="modal-body"> </div>';
                box += '<div class="modal-footer">';
                    box += '<button type="button" class="btn btn-default" data-dismiss="modal">No</button>';
                    box += '<button type="button" class="btn btn-primary">S&iacute;</button>';
                box += '</div>';
            box += '</div>';
        box += '</div>';
    box += '</div>';
    $("body").append(box);

    window.confirm = function () {
alert( $("#confirm").length );
        $("#confirm .modal-body").html( arguments[0].replace(/\n/, "<br />") );
        $("#confirm").modal();
        $("#confirm .btn-default").on('click', function() {
            $(this).modal('hide');
        });
        $("#confirm .btn-primary").on('click', function() {
            return true; // this is where I need the caller's HREF, 
                         // to make it actually proceed.
                         // Return true, obviously, does nothing.
        });
    };
};

function imprimir()
{
	window.print();
}
var __ajaxForm = null;

function chequearBotonAgregar()
{
	if($("#botonera").length==0) return;
	if($("#botonagregar").length==0) return;

	$("#botonagregar input").attr("style","");
	titulo=$("#botonagregar input").attr("value");
	formulario=$("#botonagregar").attr("formulario");
	if($("#"+formulario).length==0) return;
	
	obj=$("#"+formulario);
	onclickq=$("#"+formulario+" #guardar").attr("onclick");
	valor=$("#"+formulario+" #guardar").attr("value");

	//$("#botonera").append( $("#botonagregar input"));
	
	$("#botonagregar").remove();
	
	dialog='<div id="modalForm" class="modal fade" tabindex="-1" role="dialog">';
	dialog+='<div class="modal-dialog">';
	dialog+='<div class="modal-content">';
	dialog+='<div class="modal-header">';
	dialog+='<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
	dialog+='<h4 class="modal-title">'+titulo+'</h4>';
	dialog+='</div>';
	dialog+='<div class="modal-body">';
	//dialog+='<p>One fine body&hellip;</p>';
	dialog+=$("#"+formulario).clone().wrap('<p>').parent().html(); //.html();
	dialog+='<div id="error" align="center">';
	dialog+='&nbsp';
	dialog+='</div>';
	dialog+='</div>';
	dialog+='<div class="modal-footer">';
	dialog+='<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>';
	//dialog+='<button type="button" class="btn btn-primary" onclick="'+onclickq+'">'+valor+'</button>';
	dialog+='<button type="button" class="btn btn-primary" onclick="javascript:FormSubmit()">'+valor+'</button>';
	dialog+='</div>';
	dialog+='</div><!-- /.modal-content -->';
	dialog+='</div><!-- /.modal-dialog -->';
	dialog+='</div><!-- /.modal -->';
	$("body").append(dialog);
	$("#botonera").append('<button type="button" id="qwerty" class="btn btn-primary" data-toggle="modal" data-target="#modalForm">'+titulo+'</button>');
	$( "#modalForm #"+formulario).attr("style","");
	
	$("#modalForm #"+formulario+" #guardar").closest("tr").remove();
	AjaxForm( $( "#modalForm #"+formulario), respuestaViaje );
	obj.remove();
	__ajaxForm = "#modalForm #"+formulario;
	
	//Al mostrarse el dialogo modal, resetea los datos del formulario
	$('#modalForm').on('show.bs.modal', function() {
        $("#modalForm #error").removeClass("alert alert-danger").html("&nbsp");
        $("#modalForm form").trigger("reset");

    })
	
	if(formulario="add_form_reserva") agregarFuncionalidadReservas();
	if(formulario="add_form_persona_reserva") agregarFuncionalidadPasajero();
}

function agregarFuncionalidadReservas()
{
	$('#modalForm #add_form_reserva #documento').keyup( cambioTextoDocumentoReservas );
}

function agregarFuncionalidadPasajero()
{
	$('#modalForm #add_form_persona_reserva #documento').keyup( cambioTextoDocumentoPasajeros );
}

function cambioTextoDocumentoReservas()
{
	cambioTextoDocumento('#modalForm #add_form_reserva');
}

function cambioTextoDocumentoPasajeros()
{
	cambioTextoDocumento('#modalForm #add_form_persona_reserva');
}

function cambioTextoDocumento(formulario)
{
	doc = $(formulario+' #documento').val();
	if(doc.length<3) return;
	id = $(formulario+' #id_tipo_doc option:selected').val();

	$.ajax({
		method: "POST",
		url: "obtener_datos_persona.php",
		data: { id_tipo_doc: id, documento: doc },
		success: function( data )
		{
			//alert( "Data Saved: " + data );
			obj = JSON.parse(data);
			$(formulario+' #nombre').val(obj.nombre);
			$(formulario+' #apellido').val(obj.apellido);

			$(formulario+' #domicilio').val(obj.domicilio);
			$(formulario+' #mail').val(obj.mail);
			$(formulario+' #tel').val(obj.tel);
			$(formulario+' #celu').val(obj.celu);
			$(formulario+' #nacionalidad').val(obj.nacionalidad);
			$(formulario+' #fecha_nac').val(obj.fecha_nac);
			$(formulario+' #id_persona').val(obj.id_persona);
			if(obj.id_ciudad.length>0)
				$(formulario+' #id_ciudad option[value='+obj.id_ciudad+']').attr('selected','selected');
		}
});

}

function error(mensaje)
{
	if( __ajaxForm == null ) return;
	//alert($( __ajaxForm+" #error").length);
	$( "#modalForm  #error").addClass("alert alert-danger").html("<strong>Error: </strong>"+mensaje);
}
function FormSubmit()
{
	if( __ajaxForm != null )
		$(__ajaxForm).submit();
}
var __id=null, __table=null, __pk=null;
function AjaxConfirm(mensaje, id, table, pk)
{	
	__id=id;
	__table=table;
	__pk=pk;
	
	dialog='<div id="modalFormConfirm" class="modal fade" tabindex="-1" role="dialog">';
	dialog+='<div class="modal-dialog">';
	dialog+='<div class="modal-content">';
	dialog+='<div class="modal-header">';
	dialog+='<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
	dialog+='<h4 class="modal-title">Borrar</h4>';
	dialog+='</div>';
	dialog+='<div class="modal-body">';
	dialog+='<p>'+mensaje+'</p>';
	dialog+='</div>';
	dialog+='<div class="modal-footer">';
	dialog+='<button type="button" class="btn btn-default" data-dismiss="modal" onclick="javascript:ConfirmNo()">No</button>';
	dialog+='<button type="button" class="btn btn-primary" onclick="javascript:ConfirmYes()">S&iacute;</button>';
	dialog+='</div>';
	dialog+='</div><!-- /.modal-content -->';
	dialog+='</div><!-- /.modal-dialog -->';
	dialog+='</div><!-- /.modal -->';
	$("body").append(dialog);
	$('#modalFormConfirm').modal("show");
}

function ConfirmNo()
{
	__id=null;
	__table=null;
	__pk=null;
	$('#modalFormConfirm').modal("hide");
	//$('#modalFormConfirm').remove();
}

function ConfirmYes()
{
	$('#modalFormConfirm').modal("hide");
	//$('#modalFormConfirm').remove();
	ajax_deleteRow(__id, __table, __pk);
	__id=null;
	__table=null;
	__pk=null;
}

var __field=null; __id=null;
function AjaxConfirmFile(field, id)
{	
	__field=field;
	__id=id;
	
	dialog='<div id="modalFormConfirm" class="modal fade" tabindex="-1" role="dialog">';
	dialog+='<div class="modal-dialog">';
	dialog+='<div class="modal-content">';
	dialog+='<div class="modal-header">';
	dialog+='<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
	dialog+='<h4 class="modal-title">Borrar</h4>';
	dialog+='</div>';
	dialog+='<div class="modal-body">';
	dialog+='<p>¿Est&aacute; seguro que quiere borrar este archivo?</p>';
	dialog+='</div>';
	dialog+='<div class="modal-footer">';
	dialog+='<button type="button" class="btn btn-default" data-dismiss="modal" onclick="javascript:ConfirmNo()">No</button>';
	dialog+='<button type="button" class="btn btn-primary" onclick="javascript:ConfirmDeleteFileYes()">S&iacute;</button>';
	dialog+='</div>';
	dialog+='</div><!-- /.modal-content -->';
	dialog+='</div><!-- /.modal-dialog -->';
	dialog+='</div><!-- /.modal -->';
	$("body").append(dialog);
	$('#modalFormConfirm').modal("show");
}
/*
function ConfirmNo()
{
	__id=null;
	__table=null;
	__pk=null;
	$('#modalFormConfirm').modal("hide");
	//$('#modalFormConfirm').remove();
}
*/
function ConfirmDeleteFileYes()
{
	$('#modalFormConfirm').modal("hide");
	//$('#modalFormConfirm').remove();
	//alert(location.href);
	//location.href="?action=delete_file&field_name=" + __field + "&id=" + __id;
	url=UpdateQueryString("action", "delete_file", location.href);
	url=UpdateQueryString("field_name", __field, url);
	url=UpdateQueryString("id", __id, url);
	
	//alert(url);
	location=url;
	__id=null;
	__field=null;
}

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
        else
            return url;
    }
}
