jQuery( document ).ready( function( $ ) {
    var sending = false;

    $( '#contact-form, #contrata_form' ).submit( function( e ) {
        var form_string = $(this).attr('id');
        var form_id = '#'+ form_string;

        e.preventDefault();

        var $form = $( this );
        var incomplete = false;
        var errors = [];

        $form.find( '.req' ).each( function() {
            if ( !$( this ).val() )
                incomplete = true;
        } );

        if ( incomplete ) {
            errors.push( 'Por favor, completa todos los campos obligatorios.' );
        }

        if ( !Utils.email_verify( $( form_id + ' #input-email' ).val() ) ) {
            errors.push( 'Por favor, ingresa un mail válido.' );
        }

        if ( errors.length ) {
            Utils.popup( errors.join( '<br/>' ), 'alert' );
            return false;
        }
        Utils.popup( 'Procesando...' );
        sending = true;
        


        window[ 'get_nearest' ]( {
            street : $( form_id +' #input-calle' ).val(),
            number : $( form_id + ' #input-numext' ).val(),
            city : $( form_id + ' #input-colonia' ).val(),
            callback : function( location ) {
                if ( location == 0 ) {
                    Utils.popup( 'Ocurrió un error buscando tu ubicación. Por favor, verifica los datos ingresado e inténtalo nuevamente', 'alert' );
                    return;
                }
                var form_data = $form.serialize();
                form_data += '&location=' + location;
                $.ajax( {
                    url : '/web/cvalidator/services/contact-submit.php',
                    type : 'post',
                    dataType : 'json',
                    data : form_data,
                    success : function( res ) {
                        if ( !res.success ) {
                            Utils.popup( 'Ocurrió un error. Por favor, verifica los datos ingresados e inténtalo nuevamente.', 'alert' );
                            sending = false;
                            return;
                        }
                        Utils.popup(
                            res.inside
                            ? 'Muchas gracias por completar tus datos. Estás muy cerca de experimentar la máxima velocidad de Totalplay. Te contactaremos a la brevedad.'
                            : 'Lamentablemente todavía no hay cobertura en tu zona. Estamos trabajando para ello. Pronto te contactaremos.',
                            'alert',
                            {
                                click_callback : function() {
                                    submitted = true;
                                    $(form_id).remove();
                                    $('.'+form_string).fadeIn();
                                    Utils.popup('', 'fade', null);
                                }
                            }
                            );
                                
                        conversionSuccess();
                    },
                    error : function() {
                        Utils.popup( 'Ocurrió un error. Por favor, verifica los datos ingresados e inténtalo nuevamente.', 'alert' );
                        sending = false;
                    }
                } );
            }
        } );
    } );

    get_nearest = function( args ) {
        var country = 'Mexico';
        var address = [];
        var callback;
        if ( args.callback )
            callback = args.callback;
        if ( args.street )
            address.push( $.trim( args.street ) );
        if ( args.number )
            address.push( $.trim( args.number ) );
        if ( args.city )
            address.push( $.trim( args.city ) );
        if ( !address.length )
            return false;
        address.push( country );
        address = address.join( ', ' );
        geocoder.geocode( {
            'address': address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                /*var inside = get_inside(
					results[0].geometry.location.lat(),
					results[0].geometry.location.lng(),
					callback
				);*/
                return callback( results[0].geometry.location.lat() + ',' + results[0].geometry.location.lng() );
            } else {
                return callback( -1 );
            }
        } );
    }

    $( 'a[rel=form-trigger]' ).click( function( e ) {
        e.preventDefault();

        var $target = $( $( this ).attr( 'href' ) );
        if ( $target.length )
            $target.trigger( 'submit' );
    } );
} );

var submitted = false;
var geocoder;
var get_nearest = function() {};



function initialize() {
    geocoder = new google.maps.Geocoder();
}

function conversionSuccess() {
    window.location = $('#URLD').val();
}
