/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    LD
*  @copyright 2018 LD
*  @version   1.0.0
*  @link      http://www.ld.com.br/
*  @license
*
*  Based on the following version
* 
*  @author    DJTAL
*  @copyright 2017 DJTAL
*  @version   1.0.0
*  @link      http://www.djtal.com.br/
*
* Don't forget to prefix your containers with your own identifier
* to avoid any conflicts with others containers.
*/

var id_country_br = 58;

$(document).on('ready', function(){
    var initiated = false;
    var id_country = $('select[name=id_country] option:selected').val();
    if($('input[name=postcode]').length == 1 && (parseInt(id_country) == id_country_br || $('select[name=id_country]').length == 0)) {
        initiated = true;
        initAdressBehavior();
    } else { //This part maybe useless in PS 1.7, because the address form is not ajax loded anymore
        var inter = setInterval(function(){
            if(!initiated && $('input[name=postcode]').length == 1 && $('select[name=id_country] option:selected').length == 1){
                if(parseInt($('select[name=id_country] option:selected').val()) == id_country_br) {
                    initiated = true;
                    initAdressBehavior();
                    clearInterval(inter);
                }
            }
        }, 200);
    }
    
    $('select[name=id_country]').on('change', function(){
        var id_country = $(this).val();
        if(parseInt(id_country) == id_country_br){
            initiated = true;
            initAdressBehavior();
        } else {
            cleanAdressBehavior();
        }
    });
});

function cleanAdressBehavior() {
    var postCode = $('input[name=postcode]');
    if(typeof postCode.mod_unmask == 'function') {
        postCode.mod_unmask();
    }
    postCode.parent().parent().find('#cepSearchButton').remove();
    postCode.parent().parent().find('#cepDontKnowButton').remove();
    postCode.attr('data-validate', 'isPostCode');
    $('input[name=phone]').mod_unmask();
    $('input[name=phone_mobile]').mod_unmask();
    if(street_compl != 'no'){
        $('input[name=complement_js]').parent().parent().remove();
    }
    if(street_num != 'no'){
        $('input[name=number_js]').parent().parent().remove();
    }
}

function initAdressBehavior() {
    var postCode = $('input[name=postcode]');
	$('input[name=address2]').parent().parent().find('label.form-control-label').text('Bairro')
    
    if(typeof postCode.mod_unmask == 'function') {
        postCode.mod_unmask();
    }
    postCode.mod_mask('00000-000');
    
    //Search button
    if(cep_search_mode == 'manual'){
        postCode.parent().append('<a id="cepSearchButton" class="btn btn-primary"><span><i class="material-icons">&#xE8B6;</i></span></a>');
    }
    //Don't know my CEP button
    if(cep_dk_button){
        postCode.parent().append('<a class="btn btn-primary" target="blank" href="http://www.buscacep.correios.com.br/servicos/dnec/index.do" id="cepDontKnowButton"><span>Não sei meu CEP</span></a>');
    }
    
    postCode.attr('data-validate', 'isCEP');
    
    //Validate events:
    var postVal = '';
    if(typeof postCode != 'undefined'){
        if(typeof postCode.mod_cleanVal == 'function') {
            postVal = postCode.mod_cleanVal();
        } else {
            postVal = postCode.val();
        }
		postCode.on('keyup', function(){
			if($(this).mod_cleanVal().length == 8){
				validate_isCEP($(this).mod_cleanVal(), true);
			}
		});
		
		
    } else {
        postVal = $('input[name=postcode]').val();
    }
	
    if(cep_search_mode == 'manual'){
        $('#cepSearchButton').on('click', function() {
            postVal = $('input[name=postcode]').val();
            validate_isCEP(postVal, true);
        });
    } else {
        if(postVal.length > 0){
            validate_isCEP(postVal, true);
        }
    }
    
    //Phone Mask
    if(phones_mask === true){
        $('input[name=phone]').mod_mask('(00) 0000-0000');
        $('input[name=phone_mobile]').mod_mask('(00) 00000-0000');
    }
    
    
    //See if adress has Number and Or Complement
    var address = $('input[name=address1]').val();
    var num = '';
    var compl = '';
    var address_final = '';
    
    if(address && address != ''){
        //var numAddressArray = address.match(/\d+$/);
        var numAddressArray = address.split(',');
        if(numAddressArray.length == 2){ // Adress AND Num or Complement
            if(!isNaN(numAddressArray[1])){
                num = numAddressArray[1].trim();
            } else {
                compl = numAddressArray[1].trim();
            }
            address_final = numAddressArray[0].trim();
            
        } else if (numAddressArray.length == 3){ // Adress AND Num AND Complement
            if(!isNaN(numAddressArray[1])){
                num = numAddressArray[1].trim();
                compl = numAddressArray[2].trim();
                address_final = numAddressArray[0].trim();
            } else if(!isNaN(numAddressArray[2])){
                num = numAddressArray[2].trim();
                compl = numAddressArray[1].trim();
                address_final = numAddressArray[0].trim();
            }
            
        } else {
            address_final = address;
        }
        $('input[name=address1]').val(address_final);
    }
    
    
    // Street Complement add
    if(street_compl != 'no'){
        if($('.form-group:has(input[name=address1])').length > 0){
            var html = $('.form-group:has(input[name=address1])').prop('outerHTML').replace(/address1/g, 'complement_js');
            $(html).insertAfter('.form-group:has(input[name=address1])');
            var comment = 'Opcional';
            var required = false;
            if(street_compl == 'yes_mand'){
                comment = '';
                required = true;
            }
            var comp_js = $('input[name=complement_js]');
            comp_js.attr('required', required);
            comp_js.parent().parent().find('label.form-control-label').text(translated_comp);
            comp_js.parent().parent().find('.form-control-comment').text(comment);
            comp_js.val('');
            comp_js.attr('data-validate', 'isAddressComplement');
            comp_js.parent().removeClass('form-error').removeClass('form-ok');
            
            comp_js.val(compl);
        }
    }
    
    // Street number add
    if(street_num != 'no'){
        if($('.form-group:has(input[name=address1])').length > 0){
            var html = $('.form-group:has(input[name=address1])').prop('outerHTML').replace(/address1/g, 'number_js');
            $(html).insertAfter('.form-group:has(input[name=address1])');
            var comment = 'Opcional';
            var required = false;
            if(street_num == 'yes_mand'){
                comment = '';
                required = true;
            }
            var num_js = $('input[name=number_js]');
            num_js.attr('required', required);
            num_js.parent().parent().find('label.form-control-label').text(translated_num);
            num_js.parent().parent().find('.form-control-comment').text(comment);
            num_js.val('');
            num_js.attr('data-validate', 'isAddressNumber');
            num_js.parent().removeClass('form-error').removeClass('form-ok');
            
            num_js.val(num);
        }
    }
    
    $('form[data-id-address], #checkout-addresses-step form').on('submit', function(){
        submitAddressAccount();
    });
}

function submitAddressAccount() {
    var address1 = $('input[name=address1]').val();
    address1 = address1.replace(/, /g, ' ');
    address1 = address1.replace(/,/g, ' ');
    var num = '';
    var compl = '';
    
    if(street_num != 'no'){
        num = $('input[name=number_js]').val().trim();
        num = num.replace(/,/g, '');

        if(validate_isAddressNumber(num) || (street_num == 'yes' && num == '')){
            $('input[name=number_js]').parent().removeClass('form-error');
            $('input[name=number_js]').parent().addClass('form-ok');
        } else {
            $('input[name=number_js]').parent().removeClass('form-ok');
            $('input[name=number_js]').parent().addClass('form-error');
            $('html, body').animate({
                scrollTop: $('input[name=number_js]').offset().top - 30
            }, 500);
            return false;
        }
    }
    
    if(street_compl != 'no'){
        compl = $('input[name=complement_js]').val().trim();;
        compl = compl.replace(/,/g, '');
        
        if(validate_isAddressComplement(compl) || (street_compl == 'yes' && compl == '')){
            $('input[name=complement_js]').parent().removeClass('form-error');
            $('input[name=complement_js]').parent().addClass('form-ok');
        } else {
            $('input[name=complement_js]').parent().removeClass('form-ok');
            $('input[name=complement_js]').parent().addClass('form-error');
            $('html, body').animate({
                scrollTop: $('input[name=complement_js]').offset().top - 30
            }, 500);
            return false;
        }
    }
    
    var adressInfos = '';
    if(num != ''){
        adressInfos = num;
        if(compl != '') {
            adressInfos = num+', '+compl;
        }
    } else if(compl != '') {
        adressInfos = compl;
    }
    
    if(adressInfos != '') {
         $('input[name=address1]').val(address1+', '+adressInfos);
    }
    
    if(cep_search_mode == 'auto_prevent'){
        $('input[name=address1]').attr('disabled', false);
        $('input[name=address2]').attr('disabled', false);
        $('input[name=city]').attr('disabled', false);
        $('select[name=id_state]').attr('disabled', false);
    }
    
    return true;
}

function validate_isAddressNumber(s)
{
    return s != null && s != '' && !isNaN(s);
}

function validate_isAddressComplement(s)
{
    return s != null && s != '';
}

function validate_isAddressNumberAndComplement(s)
{
    return s != null && s != '';
}

function addWarning(div, custom_text) {
	custom_text = typeof custom_text !== 'undefined' ? custom_text : 'CEP invalido';
	div.addClass('warning').html(custom_text);
}

function removeWarning(div) {
	div.removeClass('warning').html('');
}


function validate_isCEP(s, do_search)
{
    var cep = s.replace(/[^\d]+/g,'');
    var commentDiv = $('input[name=postcode]').parents('.form-group').find('.form-control-comment');
	removeWarning(commentDiv);
	
    if(cep.length == 8) {
        if(do_search == true || (cep_search_mode != 'manual' && cep_search_mode != 'none')){
            
            $('input[name=postcode]').addClass('wait-check');
            $.getJSON( cep_ws_url, {cep: cep}, function( data ) {
                $('input[name=postcode]').removeClass('wait-check');
                if(data['found'] == 1){
                    
					if(data['address'] == '' && data['neighborhood'] == '' && data['city'] == '' && data['state_id'] == '') {
						$('input[name=postcode]').parent().removeClass('form-ok');
						$('input[name=postcode]').parent().addClass('form-error');
						addWarning(commentDiv, 'CEP não encontrado');
						return;
					}
					
                    $('input[name=address1]').val(data['address']);
                    if(!!$('input[name=address1]').attr('data-validate')){
                        validate_field($('input[name=address1]'));
                        if(cep_search_mode == 'auto_prevent' && $('input[name=address1]').parent().hasClass('form-ok')){
                            $('input[name=address1]').attr('disabled', 'disabled');
                        }
                    }
                    
                    $('input[name=address2]').val(data['neighborhood']);
                    if(!!$('input[name=address2]').attr('data-validate')){
                        validate_field($('input[name=address2]'));
                        if(cep_search_mode == 'auto_prevent' && $('input[name=address2]').parent().hasClass('form-ok')){
                            $('input[name=address2]').attr('disabled', 'disabled');
                        }
                    }
                    
                    $('input[name=city]').val(data['city']);
                    if(!!$('input[name=city]').attr('data-validate')){
                        validate_field($('input[name=city]'));
                        if(cep_search_mode == 'auto_prevent' && $('input[name=city]').parent().hasClass('form-ok')){
                            $('input[name=city]').attr('disabled', 'disabled');
                        }
                    }
                    
                    $('select[name=id_state]').val(data['state_id']);
                    var state_name = $('select[name=id_state] option[value='+data['state_id']+']').text();
                    $('select[name=id_state]').parent().find('span').html(state_name);
                    if(cep_search_mode == 'auto_prevent' && typeof state_name !== 'undefined' && state_name.length !== 0){
                        $('select[name=id_state]').attr('disabled', 'disabled');
                    }
                    
                    $('input[name=postcode]').parent().removeClass('form-error');
                    $('input[name=postcode]').parent().addClass('form-ok');
                }else{
                    $('input[name=postcode]').parent().removeClass('form-ok');
                    $('input[name=postcode]').parent().addClass('form-error');
					addWarning(commentDiv, 'CEP não encontrado');
					
                    if(cep_search_mode == 'auto_prevent'){
                        $('input[name=address1]').attr('disabled', false);
                        $('input[name=address2]').attr('disabled', false);
                        $('input[name=city]').attr('disabled', false);
                        $('select[name=id_state]').attr('disabled', false);
                    }
                }
            });
        }
        return true;
    } else {
		addWarning(commentDiv);
	}
}
