// Funcion que se ejecuta antes de enviar los datos
//
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement	 = jqForm[0]; 
	
	//Obtiene los valores de los input del formulario
	var name = $("input#nombre").val();
	var direc = $("input#direccion").val();
	var tel = $("input#telefono").val();
	var email = $("input#mail").val();
	var suma = $("input#suma").val();	
	var coment = $("#mensaje").val();
	var sum = $("input#sum").val();
	var sistema = $("input#sistema").val();		
	
	//Si estan vacio cualquiera de ellos detiene el script y avisa para llenarlo
 	if (name==''||direc==''||tel==''||email==''||coment==''||suma!=sum)
	{
    	//alert('Por favor complete el formulario adecuadamente'); 
		return false; //el false detiene el script
 	}else{
		//Avisa que pronto atenderan el mensaje
		$("#cotiza").fadeOut('slow',function(){
				$('#cotizacion').html('<div id="loader" style="text-align:center;"><img src="images/loading.gif" alt="Enviando..." /></div>')
				if(sistema=='demo')
				{
					window.open('descargas/DataCross_Demo.rar');
					$("#cotizacion").append('<p>Si la descarga no inicia, da <a href="descargas/DataCross_Demo.rar">Clic aquí</a></p>');
				}
				else if (sistema=='guia')
				{
					window.open('descargas/DataCross_Guia_Uso.rar');
					$("#cotizacion").append('<p>Si la descarga no inicia, da <a href="descargas/DataCross_Guia_Uso.rar">Clic aquí</a></p>');					
				}
				else if (sistema=='instala')
				{
					window.open('descargas/DataCross_Instalación.rar');
					$("#cotizacion").append('<p>Si la descarga no inicia, da <a href="descargas/DataCross_Instalación.rar">Clic aquí</a></p>');										
				}
		});
		return true; //el true permite seguir con el envio de datos
	}
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 

} 
 
// post-submit callback 
function showResponse(responseText, statusText, xhr, $form){ 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 	$("#loader").fadeOut('slow', function(){
		$("#cotizacion").append('<p>Datos enviados correctamente</p>');
	});
} 

$(document).ready(function() {	
	// validate signup form on keyup and submit
	var sumas = $("input#sum").val();		
	$("#cotiza").validate({
		rules: {
			nombre: {
			     required: true,
                 minlength: 5
            },     
			direccion: "required",
			mail: {
				required: true,
				email: true
			},
			telefono: "required",
			mensaje:"required",
			suma:{
				required:true,
				number:true,
				equal: sumas
			}
		},
		messages: {
			nombre:{ 
				required:"Por favor registra tu Nombre",
				minlength: "Su nombre no puede tener menos de 5 caracteres"
			},
			direccion: "Por favor registra tu Dirección",
			telefono: "Por favor registra tu Teléfono",
			mail: {
				required:"Por favor registra tu Email",
				email:"Por favor registra un e-mail válido"
			},
			mensaje:"Por favor escribe tu mensaje",
			suma:{
				required:"La suma es requerida",
				number:"Lo que escribiste no es un número",
				equal: "La suma no es correcta"
			}
			
		}
	});
	    var options = { 
        //target:        '#result',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse,  // post-submit callback 
 
        // other available options: 
        url:			'envio.php',         // override for form's 'action' attribute 
        type:      		'post',        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }
 
    // bind to the form's submit event 
    $('#cotiza').submit(function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit(options); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 
	$('input#limpiar').click(function(event){
		event.preventDefault();
		$('label.error').hide;
	});

});

