/* MNoguera 2008/10/16
 * Functión que comprueva los valores que se insertan en el campo del CEP
 * solo permite introducir números y además autoañade un guión después del quinto número
 *
 * @params string str - valor del textbox que queremos comprobar
 * @params object textbox - textbox al que se hace referencia
 * @params string loc - string con las posiciones separadas por comas de donde se quiere insertar el separador
 * @params string delim - string con el separador
 * @params evt - evento del keyboard
 *
 */
function checkCEP(str,textbox,loc,delim,evt){
    if (evt.keyCode == 37 || evt.keyCode == 39 || evt.keyCode == 46 || evt.keyCode == 8){
        // para omitir las teclas cursor izquierda / derecha / supr / del en firefox
        return true;
    }
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if (charCode > 31 && charCode < 127 && (charCode < 48 || charCode > 57)) {
        // si no se pasa un numero devuelve false
        return false;
    }

    // comprovamos si tenemos que insertar el separador
    var locs = loc.split(',');
    for (var i = 0; i <= locs.length; i++){
        for (var k = 0; k <= str.length; k++){
            if (k == locs[i]){
                if (str.substring(k, k+1) != delim){
                    str = str.substring(0,k) + delim + str.substring(k,str.length);
                }
            }
        }
    }
    textbox.value = str;
}


/**
 * MNoguera 2008/10/15 adaptado para Brazil
 * Función que comprueba si el CEP introducido corresponde con el del State.
 * el CEP de cada state se distingue por intervalos de sus 3 primeras cifras
 * 			ej: CEP correspondientes a Amazonas state: entre 690xx-xxx - 693xx-xxx y 694xx-xxx - 698xx-xxx
 *
 * Para ello se usa un array auxiliar en la que se establece mediante arrays:
 *      - el nombre del state
 *		- los 3 primeros carácteres del CEP más pequeño del state.
 *		- los 3 primeros carácteres del CEP más grande del state.
 *		- disponibilidad de envío: 1->si, 0->privalia no envía por el momento
 *
 *
 *
 * @params string s_postalCode. CEP con 8 dígitos separados: 12345-678
 * @returns integer 		0 si no se encontrá el código postal (0)
 *							1 si el código postal es de una provincia a la que no se envía
 *
 */

function getProvinceFromPostalCode(s_postalCode)
{
    var bOk = buscaCep(s_postalCode);

    //alert(bOk);

    if (bOk == 0 || s_postalCode.length != 9) {
        return 0;
    }
    else if (!isUnsignedInteger(s_postalCode.substring(0, 5) + s_postalCode.substring(6, 9))) {
        // comprovamos si quitando el guión es un integer
        return 0;
    }

    i_postalCodeThreeDigits = s_postalCode.substring(0, 3);

    var st_postalCodeInit = [
        ['São Paulo', 10, 109, 1],			// São Paulo Metropolitan Region
        ['São Paulo', 110, 199, 1],
        ['Rio de Janeiro', 200, 289, 1],
        ['Espírito Santo', 290, 299, 1],
        ['Minas Gerais', 300, 399, 1],
        ['Bahia', 400, 489, 1],
        ['Sergipe', 490, 499, 1],
        ['Pernambuco', 500, 569, 1],
        ['Alagoas', 570, 579, 1],
        ['Paraíba', 580, 589, 1],
        ['Rio Grande do Norte', 590, 599, 1],
        ['Ceará', 600, 639, 1],
        ['Piauí', 640, 649, 1],
        ['Maranhão', 650, 659, 1],
        ['Pará', 660, 688, 1],
        ['Amapá', 689, 689, 1],
        ['Amazonas', 690, 692, 1],			// Amazonas part 1
        ['Roraima', 693, 693, 1],
        ['Amazonas', 694, 698, 1],			// Amazonas part 2
        ['Acre', 699, 699, 1],
        ['Distrito Federal', 700, 727, 1],	// Distrito Federal part 1
        ['Goiás', 728, 729, 1],				// Goiás part 1
        ['Distrito Federal', 730, 736, 1],	// Distrito Federal part 2
        ['Goiás', 737, 767, 1],				// Goiás part 2
        ['Rondônia', 768, 769, 1],
        ['Rondônia', 789, 789, 1],
        ['Tocantins', 770, 779, 1],
        ['Mato Grosso', 780, 788, 1],
        ['Mato Grosso do Sul', 790, 799, 1],
        ['Paraná', 800, 879, 1],
        ['Santa Catarina', 880, 899, 1],
        ['Rio Grande do Sul', 900, 999, 1]];

    /******OLD*******/
    // try specialPostalCode first, then postalCodeInit, then postalCodeNoShipments (empty for now)
    /*if(typeof(st_specialPostalCode[i_postalCode]) == 'string') {
		return st_specialPostalCode[i_postalCode];
	} else if(typeof(st_postalCodeInit[i_postalCodeTwoDigits]) == 'string') {
		return st_postalCodeInit[i_postalCodeTwoDigits];
	} else if (typeof(st_postalCodeNoShipments[i_postalCodeTwoDigits]) == 'string') {
		return 1;
	} else {
		return 0;
	}
	/*****************/


    var i = 0;

    while (true) {
        if(st_postalCodeInit[i][1] <= i_postalCodeThreeDigits && st_postalCodeInit[i][2] >= i_postalCodeThreeDigits) {
            b_find = true;
            if (st_postalCodeInit[i][3] == 1) {
                // CEP válido, devolvemos la string con el nombre del State
                return st_postalCodeInit[i][0];
            }
            else if (st_postalCodeInit[i][3] == 0) {
                // no se envía, devolvemos 1
                return 1;
            }
        }
        else if (i < st_postalCodeInit.length-1) {
            // no se ha encontrado, seguimos buscando
            i++;
        }
        else {
            // no se ha encontrado el CEP en la array, devolvemos 0
            return 0;
        }
    }

}

function procesarDatos(login) {
    //* los índices para phone_type1 corresponden a:
    //												0: mobile
    //												1: home
    //* los índices para phone_type2 corresponden a:
    //												0: --
    //												1: mobile
    //												2: home
    var phone_type1 = document.getElementById('phone_type1').selectedIndex;
    var phone_type2 = document.getElementById('phone_type2').selectedIndex;
    var phone_1 = document.getElementById('phone_1').value;
    var phone_2 = document.getElementById('phone_2').value;
    // [Xavier Arnaus 12/08/2008]
    // Toma de valores para birth_date check
    var birth_day_idx 	= document.getElementById('birth_day').selectedIndex;
    var birth_month_idx = document.getElementById('birth_month').selectedIndex;
    var birth_year_idx 	= document.getElementById('birth_year').selectedIndex;
    var birth_day 	= document.getElementById('birth_day')[birth_day_idx].value;
    var birth_month = document.getElementById('birth_month')[birth_month_idx].value;
    var birth_year 	= document.getElementById('birth_year')[birth_year_idx].value;
    var now = new Date();
    var isleap = ((birth_year % 4 == 0 && birth_year % 100 != 0) || birth_year % 400 == 0);
    // [Xavier Arnaus 12/08/2008]
    // Check for adult
    if (getTimestamp(birth_day, birth_month, birth_year) > getTimestamp(now.getDate(), now.getMonth()+1, now.getFullYear()-16)) {
        //alert('No puedes ser usuario de Privalia siendo menor de 16 años.');
        alert(s_alert_16age);
    }
    //[Xavier Batlle & Maure Noguera 23/08/08}
    //check for month days
    else if ((birth_month==4 || birth_month==6 || birth_month==9 || birth_month==11) && birth_day==31) {
        //alert("Este mes no tiene 31 días");
        alert(s_alert_31days);
    }

    else if (birth_month == 2 && birth_day>29 || (birth_day==29 && !isleap && birth_month == 2)) { // check for february 29th
        //alert("Febrero del año " + birth_year + " no tuvo " + birth_day + " días");
        alert(s_alert_february + birth_year + s_alert_donthave + birth_day + s_alert_days);
    }
    else if (phone_1 != '' && phone_2 != '') {
        //if (phone_type1 == 0 && phone_type2 == 1) alert('Solo podemos guardar un teléfono movil');
        if (phone_type1 == 0 && phone_type2 == 1) alert(s_alert_onecell);
        //else if (phone_type1 == 1 && phone_type2 == 2) alert('Solo podemos guardar un teléfono fijo');
        else if (phone_type1 == 1 && phone_type2 == 2) alert(s_alert_onetlp);
        else enviar(login);

    }

    else {
        enviar(login);
    }
}

function procesarDatosTelf(login, phone_dir) {
    //* los ï¿½ndices para phone_type1 corresponden a:
    //												0: mobile
    //												1: home
    //* los ï¿½ndices para phone_type2 corresponden a:
    //												0: --
    //												1: mobile
    //												2: home

	if (document.getElementById('phone_type1') != null && document.getElementById('phone_type2') != null) {
		var phone_type1 = document.getElementById('phone_type1').selectedIndex;
	    var phone_type2 = document.getElementById('phone_type2').selectedIndex;
	    var phone_1 = document.getElementById('phone_1').value;
	    var phone_2 = document.getElementById('phone_2').value;
	
	    if (phone_1 != '' && phone_2 != '') {
	        //if (phone_type1 == 0 && phone_type2 == 1) alert('Solo podemos guardar un teléfono movil');
	        if (phone_type1 == 0 && phone_type2 == 1) alert(s_alert_onecell);
	        else if (phone_type1 == 1 && phone_type2 == 2) alert(s_alert_onetlp);
	        //else if (phone_type1 == 1 && phone_type2 == 2) alert('Solo podemos guardar un teléfono fijo');
	        else enviar(login);
	    }else {
	        enviar(login);
	    }
	} else if (document.getElementById(phone_dir) != null) {
		enviar(login);
	}
}
function buscaCep(cep){

    resp = 0;


    url = "/ceps/?cep="+cep;

    // Action in start and final
    //
    Ajax.Responders.register({
      onCreate: function(){
        $('loading').className = 'ativo';
      },
      onComplete: function(){
        $('loading').className = 'oculto';
      }
    });

    // A chamada AJAX propriamente dita
    new Ajax.Request(url,
    {
        method:'get',
        parameters: $('registerform').serialize(true),
        asynchronous: false,

        //onSuccess: function(transport) {
        onComplete: function(){},
        onSuccess: function(transport) {

          var response = transport.responseText;
          resp = response;

          //alert(response);
        },
        onFailure: function(){ alert('Conexão falhou…') }
    });

   if(resp == 0){
        return 0;
   }else{
        return 1;
   }
}
