<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<link type="text/css" rel="stylesheet" href="<c:url value='/css/qtip/jquery.qtip.min.css'/>" />
<script type="text/javascript" src="<c:url value='/js/qtip/jquery.qtip.min.js'/>" ></script>

<script type="text/javascript">
    var waypointsCount = 0;
    $(document).ready(function() {
        waypointsCount = 0;
        $('#wp').qtip({
            content: 'estos puntos intermedios sirven para indicar que además de ir al destino, tambien pasas por estos sitios.',
            position: {
                my: 'right center', 
                at: 'left center'
            },
            show: 'mouseover',
            hide: 'mouseout',
            style: {
                tip: true,
                classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
            }
        });
    
        var field_values = {
            //id : valor
            'origen' : 'origen',
            'destino' : 'destino',
            'hs' : 'Hora de salida',
            'hll' : 'Hora de llegada'
        }; 
        
        $('#next').click(function(){
            //miramos que inputs no estan vacios
            var inputs = $('#datos_viaje input[type=text]');
            var error = false;
            inputs.each(function(){
                var value = $(this).val();
                if( value.length < 4 || value==field_values[$(this).attr('id')] ) {
                    $(this).css('border', "1px solid red");
                    $(this).effect("shake", { times:3 }, 50);
                    error = true;
                } else {
                    $(this).css('border', '1px solid green');
                }
            });
            
            if(!error) {
                var RegExg = /^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}) (am|pm)$/;
                var matchHS = $('#hs').val().match(RegExg);
                var matchHLL = $('#hll').val().match(RegExg);
                
                if (!matchHS){
                    haveErrors("hs");
                    error = true;
                }
                if (!matchHLL){
                    haveErrors("hll");
                    error = true;
                }
                
                if( !error && $("#wp").is(':checked')) {
                    //movemos a la siguiente parte del formulario                    
                    $('#datos_viaje').slideUp();
                    $('#datos_waypoints').slideDown();
                } else {
                    $("#trip").submit();
                }
            }
        });        
    });
    
    function addWaypoint(){
        apprise("Escribe la dirección de este punto intermedio",
        {'input': true, 'animate':true, 'verify':true, 'textOk':'Enviar', 'textCancel':'Cancelar'}, function(ruta){

            if(ruta != false) { 
                $.ajax({
                    type: "POST",
                    url: "trips/addWaypoint",
                    dataType: 'json',
                    data: ({ruta: ruta}),
                    success: function(data){
                        var content = "";
                        content = "<div id=\"wp"+waypointsCount+"\"> Punto nº"+(waypointsCount+1)+ " Ruta: " + ruta + "<input type=\"button\" value=\"borrar\" onclick=\"delWaypoint("+waypointsCount+");\"/></div>";
                        $("#grid").append(content);
                        waypointsCount ++;
                    },
                    failure: function() {
                        apprise("Error");
                    }
                });
            }
        });
    }
    
    function delWaypoint(wpId){
        apprise("Seguro que quieres borrar este punto intermedio",
        {'animate':true, 'verify':true, 'textOk':'Aceptar', 'textCancel':'Cancelar'}, function(ok){

            if(ok != false) { 
                $.ajax({
                    type: "POST",
                    url: "trips/removeWaypoint",
                    dataType: 'json',
                    data: ({wpId: wpId}),
                    success: function(data){
                        $("#wp"+wpId).remove();
                        waypointsCount --;
                    },
                    failure: function() {
                        apprise("Error");
                    }
                });
            }
        });
    }
    
    function haveErrors(id){
        $("#"+id).css('border', "1px solid red");
        $("#"+id).effect("shake", { times:3 }, 50);
    }
    
    function cleanErrors(id){
        $(id).css('border', '1px solid #CCCCCC');
    }
</script>

<style type="text/css">
    #tripForm {
        background: url("/engine/images/tripForm/container.png") no-repeat scroll 0 0 transparent;
        height: 370px;
        margin: 20px auto;
        overflow: hidden;
        padding: 50px 0;
        position: relative;
        width: 754px;
    }

    #tripForm .form {margin: 0 50px 0;}
    #tripForm #first_step {display: block;}

    #tripForm h1, #tripForm h2 {
        font-size: 24px;        
        text-align: center;
        letter-spacing: 2px;
        text-shadow: 1px 1px 2px #222222;
    }

    #tripForm .datos {
        background: url("/engine/images/tripForm/input.png") no-repeat scroll 0 0 transparent;
        font-family: Cantarell,Verdana,sans-serif;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #CCCCCC;        
        font-weight: bold;
        margin: 20px 10px;
        padding: 0 25px;
        font-size: 15px;  
        color: #888888;                      
        height: 35px;        
        width: 300px;
        float: left;
    }

    #tripForm #next {
        background: url("/engine/images/tripForm/button.png") no-repeat scroll 0 0 transparent;
        border: medium none;
        position: relative;
        cursor: pointer;            
        height: 38px;        
        width: 85px;
        bottom: 2px;    
    }

    #tripForm #finalizar{
        background: url("/engine/images/tripForm/send.png") no-repeat scroll 0 0 transparent;
        border: medium none;
        position: relative;
        cursor: pointer;            
        height: 38px;        
        width: 85px;
        bottom: 2px;
    }
</style>

<div style="display:none;">
    <div id="tripForm">
        <form:form id="trip" commandName="trip" method="POST">
            <div class="form">
                <div id="datos_viaje">
                    <center><h1> Nuevo Viaje </h1></center>                
                    <form:input onclick="cleanErrors(this)" cssClass="datos"
                                placeholder="Origen" id="origen" path="origen" type="text" size="40"/>
                    <form:input onclick="cleanErrors(this)" cssClass="datos" 
                                placeholder="Destino" id="destino" path="destino" type="text" size="40"/>
                    <form:input onclick="cleanErrors(this)" cssClass="datos"
                                placeholder="Hora de salida" id="hs" path="hora_salida" type="text" />               
                    <form:input onclick="cleanErrors(this)" cssClass="datos"
                                placeholder="Hora de llegada" id="hll" path="hora_llegada" type="text" />  
                    <form:textarea placeholder="Descripcion, Explica el recorrido, da datos relevantes sobre la ruta, indica sitios donde paras, etc." path="descripcion" rows="7" cols="97"/>

                    <div style="position:relative; margin-top: 10px; margin-left: 10px; color: #545454">
                        <input id="wp" type="checkbox"/> Necesitas puntos intermedios
                    </div>

                    <div style="float:right; margin-right: -30px;">
                        <input id="next" type="button" value=""/>
                    </div>
                </div>
                <div id="datos_waypoints" style="display:none;">
                    <center><h1>Añade puntos</h1></center>
                    <input id="addWp" type="button" value="+" onclick="addWaypoint();" style="margin-bottom: 20px;"/>
                    <div id="grid"></div>
                    
                    <div style="float:right; margin-right: -30px;">
                        <input id="finalizar" type="submit" value=""/>
                    </div>
                </div>
            </div>            
        </form:form>
    </div>
</div>
