var _campoError = null;
var _errores    = "";

function appendErrorMessage(msgError) {
    _errores += ((_errores != "") ? "\n":"") + "        " + msgError
}

function rtrim(cadena) {
    cadena += "";
    for (var i = cadena.length -1; (i >= 0) && ((cadena.charAt(i) == ' ')); i--)
        ;
    return cadena.substring(0, i+1);
}

function ltrim(cadena) {
    cadena += "";
    for (var i = 0; (i < cadena.length) && ((cadena.charAt(i) == ' ')); i++)
        ;
    if (i == cadena.length) {
        return "";
    }
    return cadena.substring(i);
}

function trim(cadena) {
    return ltrim(rtrim(cadena));
}

function validarLista(lista, msgError, indiceInicial) {
    if (!indiceInicial) {
        indiceInicial = 1;
    }
    if (lista.selectedIndex < indiceInicial) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = lista;
        }
        return false;
    }
    return true;
}

function validarCampo(campo, msgError, longitudMinima, longitudMaxima, funcion) {
    if (!longitudMinima) {
        longitudMinima = 1
    }
    if (!longitudMaxima ) {
		longitudMaxima = Number.MAX_VALUE
    }
    var value = trim(campo.value)
    if (value.length < longitudMinima || value.length > longitudMaxima ||
        (funcion ? !eval("funcion(campo.value)") : false)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = campo;
        }
        return false;
    }
    return true;
}

function validarBusquedaHomeMotor(laForma) {
	_campoError = null;
	_errores = "";

	if(laForma.preciominimo[laForma.preciominimo.selectedIndex].value != "" && laForma.preciomaximo[laForma.preciomaximo.selectedIndex].value != "") {
		if(parseInt(laForma.preciomaximo[laForma.preciomaximo.selectedIndex].value) <= parseInt(laForma.preciominimo[laForma.preciominimo.selectedIndex].value)) {
			_errores += "\n        El precio máximo debe ser mayor que el mínimo";
			if (_campoError ==  null) {
				 _campoError = laForma.preciomaximo;
			}
		}
		else {
			laForma.precioventa.value = "entre(" + laForma.preciominimo[laForma.preciominimo.selectedIndex].value + "," + laForma.preciomaximo[laForma.preciomaximo.selectedIndex].value + ")";
		}
	}
	else {
		if(laForma.preciominimo[laForma.preciominimo.selectedIndex].value != "" && laForma.preciomaximo[laForma.preciomaximo.selectedIndex].value == "") {
			_errores += "\n        Debe seleccionar el precio máximo";
			if (_campoError ==  null) {
				 _campoError = laForma.preciomaximo;
			}
		}
		if(laForma.preciominimo[laForma.preciominimo.selectedIndex].value == "" && laForma.preciomaximo[laForma.preciomaximo.selectedIndex].value != "") {
			_errores += "\n        Debe seleccionar el precio mínimo";
			if (_campoError ==  null) {
				 _campoError = laForma.preciominimo;
			}
		}
    }

	if (_errores != "") {
		alert("Por favor verifique la siguiente información: \n\n" + _errores)
		if (_campoError !=  null) {
			_campoError.focus();
		}

		return false;
	}
	return true;
}

function validarBusquedaCodigo(laForma) {
	_campoError = null;
	_errores = "";

	validarCampo(laForma.idVehiculo, "Código", 1);
	if (_errores != "") {
		alert("Por favor verifique la siguiente información: \n\n" + _errores)
		if (_campoError !=  null) {
			_campoError.focus();
		}
		return false;
	}
	return true;
}

function validarFormaBusquedaHome(forma){
	var marcas = "";
	for(i=0;i<forma.length;i++) {
	   	if(forma.elements[i].type == "checkbox") {
	   		if(forma.elements[i].name == "marcas") {
	   			if(forma.elements[i].checked) {
					marcas = marcas + forma.elements[i].value + ",";
				}
			}
		}
	}
	if(marcas != "") {
		forma.totalmarcas.value = marcas.substring(0,marcas.length - 1);
	}
	if(forma.esnuevo.value == "S"){
		if(forma.esblindado.checked == true){
			alert("Lo sentimos pero no tenemos vehículos nuevos blindados.");	
			return false;
		}else if(forma.esdecoleccion.checked == true){
			alert("Lo sentimos pero no tenemos vehículos nuevos de colección.");
			return false;
		}
	}
	return true;
}
function validarFormaBusquedaHomeNuevo(forma){
	var marcas = "";
	for(i=0;i<forma.length;i++) {
	   	if(forma.elements[i].type == "checkbox") {
	   		if(forma.elements[i].name == "marcas") {
	   			if(forma.elements[i].checked) {
					marcas = marcas + forma.elements[i].value + ",";
				}
			}
		}
	}
	if(marcas != "") {
		forma.totalmarcas.value = marcas.substring(0,marcas.length - 1);
	}
	if(forma.esnuevo.value == "S"){
		/*if(forma.esblindado.checked == true){
			alert("Lo sentimos pero no tenemos vehículos nuevos blindados.");	
			return false;
		}else */if(forma.esdecoleccion.checked == true){
			alert("Lo sentimos pero no tenemos vehículos nuevos de colección.");
			return false;
		}
	}
	window.open('','popUp','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,width=320 ,height=160,top=300,left=400');
	return true;
}
function cambiarFormaTipoCatalogo(forma,tipo){
	if(tipo=="nuevos"){
		forma.esnuevo.value = "S";
		forma.tipoFuente.value = "3";
	}else{
		forma.esnuevo.value = "N";
		forma.tipoFuente.value = "1";
	}
}

function cambiarEstado (url, forma, estatus) {
	forma.action = url;
	forma.estado.value = estatus;
	forma.submit();
}

function rollOver(idBoton, clase){
	if(document.getElementById){
		var btn = document.getElementById(idBoton);
		btn.className = clase;
	}	
}
function borrar(obj,valor) {
	if (obj.value == valor) {
		obj.value = "";
	}
}
function validarFormaBusquedaHomeCodigo(form){
	if(form.idVehiculo.value.length == 0 || form.idVehiculo.value == ""){
		alert("Debe digitar el código, por favor inténtelo de nuevo");
		return false;
	}	
	return true;
}
function abrirCapturarDemanda() {
	mWindow = window.open("/servlet/co.com.motor.servlet.demanda.MostrarCapturar","demanda","resizable=no,scrollbars=yes,top=100,left=100,width=370,height=500");
}
/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
FUNCIONES UTILIZADAS PARA EL HOME (FACELIFT)
**/
function armarPrecioFormato(laForma){
	precioMinimo = 0;
	precioMaximo = 0;
	if ( laForma.preciominimo.value == "" && laForma.preciomaximo.value == "" ){
		return true;
	}
	else if ( isNaN(Delete_miles(laForma.preciominimo.value)) || isNaN(Delete_miles(laForma.preciomaximo.value)) ){
		alert( "Formato de Precio Incorrecto" );
		return false;
	}
	precioMinimo = Delete_miles(laForma.preciominimo.value);
	precioMaximo = Delete_miles(laForma.preciomaximo.value);
	if ( parseInt(precioMaximo) >= parseInt(precioMinimo) )  {
		laForma.precioventa.value = "entre(" + precioMinimo + "," + precioMaximo + ")";
	}else{
			alert ("El precio inicial no puede ser mayor que el precio final");
			return false;
	}
	return true;
}

function cambiarTipoVehiculoBusqueda(divActualLink,divDestinoLink,divActual,divDestino){
		document.getElementById(divActualLink).className = '';
		document.getElementById(divDestinoLink).className = 'tabsBuscadoractive';
		document.getElementById(divActual).className = 'desactivar';
		document.getElementById(divDestino).className = 'activar';
}

var forma = null;
var xmlHttp = null;
function cambiarModeloHome(laForma){
	xmlHttp = obtenerXMLHTTPObject();
	forma=laForma;
	if ( laForma.id_marca.selectedIndex > 0 ){
		  var urlServlet = "/servlet/co.com.motor.servlet.ajax.TraerCriterioSegunTipo?tipo=3&criterio=" + laForma.id_marca[laForma.id_marca.selectedIndex].value;
		  urlServlet += "&esNuevo="+laForma.esnuevo.value;
		  if ( laForma.moto.value == "S" ){
			urlServlet +="&tipoVehiculo="+laForma.id_tipovehiculo.value;
		  }
		try{				
			if(xmlHttp){
				xmlHttp.open("POST",urlServlet,true);
				xmlHttp.onreadystatechange = actualizarModelo;
				xmlHttp.send(null);
			}				
		}catch(e){
			alert("Error: "+e);		
		}	
	}else{
		limpiarSelect(forma.id_linea);
		opcion = new Option("Todos los Modelos","");
		forma.id_linea.options[0] = opcion;
	}
}
		
function actualizarModelo() {
	if (xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200){
			var respuesta = xmlHttp.responseText;
			var arreglo = respuesta.split(";")
			limpiarSelect(forma.id_linea);
			opcion = new Option("Todos los Modelos","");
			forma.id_linea.options[0] = opcion;
			for ( i = 0; i<arreglo.length; i++ ){
				var opciones = arreglo[i].split(",");
				if ( i+1 < arreglo.length ){
					opcion = new Option(opciones[1],opciones[0]);
					forma.id_linea.options[i+1] = opcion;
				}
			}
		}else{
			alert(parseErrorCode("ocurrio un error: "+xmlHttp.status+" "+xmlHttp.responseText));
		}   
   }
}

function validarBusquedaHomeFaceLift(laForma){
	if ( armarPrecioFormato(laForma) == true ){
		window.open('','popUp','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,width=320 ,height=160,top=300,left=400');
	}else{
		return false;
	}
}