/*
Funciu00F3n utilizada por el archivo "autoestrene.jsp".
Valida la informacion proporcionada por el cliente en la forma "autoestrene".
*/

function validateForm(porcEng,porcCom) {
	var	aditionalPayment, bisiesto, carPrice, day, month, year;

	var ivaDesc = document.autoestrene.IVA[document.autoestrene.IVA.selectedIndex].text; 
    document.autoestrene.ivaDesc.value = ivaDesc; 


    //Inicio Quita formato currency 
	carPrice = parseFloat(trim(document.autoestrene.VALUE.value));	
	document.autoestrene.VALUE.value = carPrice;	
	//Fin Quita formato currency 

	if(carPrice < 20000) {
		alert("Por favor proporciona el valor de la factura con IVA");
		return false;
	}

    //Inicio Quita formato currency 
	aditionalPayment = parseFloat(trim(document.autoestrene.ADDITIONALPAYMENT.value));	
	document.autoestrene.ADDITIONALPAYMENT.value = aditionalPayment;	
	//Fin Quita formato currency 

	if(aditionalPayment < 0) {
		alert("Por favor proporciona cifras correctas");
		return false;
	}
	if (document.autoestrene.ADDITIONALPAYMENT.value==0){
		document.autoestrene.ADDITIONALPAYMENT.value = 0;
	}

	day = document.autoestrene.DATE.selectedIndex + 1;
	month = document.autoestrene.MONTH.selectedIndex + 1;
	if(day > 30 && (month == 4 || month == 6 || month == 9 || month == 11)) {
		alert("Por favor proporciona una fecha v\u00E1lida");
		return false;
	}

	bisiesto = 0;
	year = document.autoestrene.YEAR.selectedIndex + 1998;
	if(year % 4 == 0 && (!(year % 100 == 0) || year % 400 == 0))
		bisiesto = 1;

	if(day >28 && month == 2 && !bisiesto) {
		alert("Por favor proporciona una fecha v\u00E1lida");
		return false;
	}

	if(day >29 && month == 2 && bisiesto) {
		alert("Por favor proporciona una fecha v\u00E1lida");
		return false;
	}


	
	if(document.autoestrene.PORCENTAJE_ENGANCHE != null){
	
		if(Number(document.autoestrene.PORCENTAJE_ENGANCHE.value) < Number(porcEng)){
			if(confirm("Una tasa de enganche menor al " + porcEng +"% requiere autorizaci\u00F3n especial")){
			
			}else{
				document.autoestrene.PORCENTAJE_ENGANCHE.value = porcEng;
			}
		}
	}
	
	if(document.autoestrene.PORCENTAJE_COMISION_APERTURA != null){
		if(Number(document.autoestrene.PORCENTAJE_COMISION_APERTURA.value) < Number(porcCom)){
			if(confirm("Una tasa de comisi\u00F3n menor al " + porcCom +"% requiere autorizaci\u00F3n especial")){
			
			}else{
				document.autoestrene.PORCENTAJE_COMISION_APERTURA.value = porcCom;
			}
		}
	}
        if(!isAlphabetic(document.autoestrene.CLIENTNAME.value)){
           alert("Por favor proporciona un Nombre del cliente v\u00E1lido");
           return false;
        }
        if(!isPhoneNumber(document.autoestrene.CLIENTPHONE.value)){
           alert("Por favor proporciona un Tel\u00E9fono v\u00E1lido");
           return false;
        }
        if(!isPhoneNumber(document.autoestrene.AGENCY.value)){
           alert("Por favor proporciona una Agencia automotriz v\u00E1lido");
           return false;
        }
        if(!isAlphabetic(document.autoestrene.SALESEXECUTIVE.value)){
           alert("Por favor proporciona un Ejecutivo de ventas v\u00E1lido");
           return false;
        }
        if(!isPhoneNumber(document.autoestrene.SALESEXECUTIVEPHONE.value)){
           alert("Por favor proporciona un Tel\u00E9fono del ejecutivo v\u00E1lido");
           return false;
        }
        if(!isPhoneNumber(document.autoestrene.BRANCH.value)){
           alert("Por favor proporciona una Sucursal Banorte v\u00E1lido");
           return false;
        }
        if(!isAlphabetic(document.autoestrene.BRANCHEXECUTIVE.value)){
           alert("Por favor proporciona un Ejecutivo de cuenta v\u00E1lido");
           return false;
        }
        if(!isPhoneNumber(document.autoestrene.BRANCHEXECUTIVEPHONE.value)){
           alert("Por favor proporciona un Tel\u00E9fono del ejecutivo v\u00E1lido");
           return false;
        }
	document.autoestrene.submit();
}

	function submit(payment, rate, tableTerm, midPayment, creditInsurance) {
		var form = document.autoestreneDetail;
		form.MIDPAYMENT.value = midPayment;
		form.PAYMENT.value = payment;
		form.RATE.value = rate;
		form.TABLETERM.value = tableTerm;
		form.CREDITINSURANCE.value = creditInsurance;
		//window.open('','amortization','width=800,height=450,left=0,top=0,scrollbars=yes');		
		//window.resizeTo(820,595);		
		form.submit();
	}

	function validaCampo(valor) {
		if (valor == null || valor == "" || valor <=0 || isNaN(valor)){
			valor = 0;
		}else{
			valor = currencyFormat(valor);
		}
		return valor;
	}
	
	function validateAdvancePay(field){
	field.value = validaCampo(trim(field.value));
	}
	
	function validateOpeningExpensesPercentage(field){
	field.value = validaCampo(trim(field.value));
	}
	
	function validateDownpaymentPercentage(field){
	field.value = validaCampo(trim(field.value));
	}
	
	function validateValue(field){
	field.value = validaCampo(trim(field.value));
	}
	function loadPage(){
	document.autoestrene.serviceName.value = "autoestreneHomeAction";
	document.autoestrene.submit();
	}
	
	function validateValorFactura(field){
	field.value = validaCampo(trim(field.value));
	}	

	function validateEnganche(field){
		field.value = validaCampo(field.value);
	}
	
	function trim(str) {
		return str.replace("$","");
	}
	
	function trim(str) {
		str = str.replace(",","");
		str = str.replace(",","");		
		str = str.replace("$","");		
		return str
	}
	
	
	function currencyFormat(amount) {
        amount = amount.toString();
        amount = amount.replace(/\,/g,"");
        if(isNaN(amount))
                    return "";
        while(amount.charAt(0) == "0")
                    amount = amount.substring(1);
        var decimalLength;
        if(amount.indexOf(".") > -1) {
            decimalLength = amount.indexOf(".");
            var decimals = amount.length - decimalLength - 1;
            if(decimals < 2) {
                while(decimals < 2) {
                    amount = amount + "0";
                    decimals++;
                }
            } else {
                amount = amount.substring(0, amount.length - (decimals - 2));
            }
        } else {
            decimalLength = amount.length;
            amount = amount + ".00";
        }
        var numberOfCommas = Math.floor(decimalLength / 3);
        if(decimalLength % 3 == 0)  numberOfCommas --;
        while(numberOfCommas > 0) {
            amount = amount.substring(0, decimalLength - 3) + "," + amount.substring(decimalLength - 3);
            decimalLength -= 3;
            numberOfCommas --;
        }
        return amount;
	}
	//RECALCULA LA TABLA DE AMORTIZACION DEPENDIENDO DE LOS PAGOS ADELANTADOS
	function recalculatePayment(){
		var rows = parseInt(document.recalculate.rows.value);
		for (var i=1;i<=rows;i++){
			advancePayment = document.getElementById("advancePayment_" + i).value;
			advancePayment = trim(advancePayment);
			document.getElementById("advancePayment_" + i).value = advancePayment;
		}
		document.recalculate.submit();
	}
        
// Valida Texto
function isAlphabetic (valor){
    var i;    
    for (i = 0; i < valor.length; i++)
    {   
        var c = valor.charAt(i);
        if (!isLetter(c)){            
            return false;
        }
    }
    return true;
}

//Valida Telefono
function isPhoneNumber (valor){
    var i;
    for (i = 0; i < valor.length; i++)
    {   
        var c = valor.charAt(i);
        if (!isNumTel(c) && !isLetter(c)){
            return false;
        }
    }
    return true;
}
function isNumTel (c){
    var patron = "0123456789 ()-/+,";
    return( ( patron.indexOf( c ) != -1 ))
}

function isLetter (c){
    var patron = "abcdefghijklmnopqrstuvwxyzáéíóúñü ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ.";
    return( ( patron.indexOf( c ) != -1 ))
}	
