﻿function showZipLookup(sLookupDivName, objBtn, bVisible) {
    var zipLookup = document.getElementById(sLookupDivName);
    var sStyle = "none";

    if (zipLookup) {
        if (bVisible)
            sStyle = "block";
        else
            cleanBasketLookup();
        zipLookup.style.display = sStyle;
        if (document.getElementById("divModalBgFilterLv2"))
            document.getElementById("divModalBgFilterLv2").style.display = sStyle;

        if (sStyle == "block") {
            if (!dropdownsFetched)
                fetchDropdowns();

            if (document.getElementById('txtLookupAddress')) {
                document.getElementById('txtLookupAddress').focus();
            }
        }
        if (document.getElementById('resultDNE')) {
            document.getElementById('resultDNE').style.visibility = 'hidden';
        }
        if (document.getElementById('divZipExpand')) {
            document.getElementById('divZipExpand').style.height = '200px';
        }
    }

    return false;
}

var dropdownsFetched = false;
function fetchDropdowns() {
    $.ajax({
        type: "POST",
        url: $.browser.rootUrl + "/FastshopAjaxMethod.aspx/GetZipLookupDropdowns",
        data: "{'dsAddress':'null'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            fillDropdowns({ value: result.d });
        }
    });
}

function fillDropdowns(ret) {
    // Result Validation
    if (ret == null || ret.value == null || ret.value.length != 2)
        alert("Falha ao carregar informações de endereço!\nPor favor, feche e abra esta popup novamente.");
    dropdownsFetched = true;

    // Variable Initialization
    var oAddressTypeList = ret.value[0];
    var oAddressStateList = ret.value[1];
    var iCounter = 0;
    var sText = "", sValue = "";
    var bIsSelected = false;

    // Fills the AddressType Dropdown
    var ddAddressType = $get("txtAddressType");
    if (ddAddressType != null) {
        ddAddressType.options.length = 0;
        for (iCounter = 0; iCounter < oAddressTypeList.length; iCounter++) {
            bIsSelected = false;
            sText = oAddressTypeList[iCounter].Text;
            sValue = oAddressTypeList[iCounter].Value;

            if (sValue == "R")
                bIsSelected = true;

            ddAddressType.options[ddAddressType.options.length] = new Option(sText, sValue, bIsSelected);
        }
    }

    // Fills the AddressState Dropdown
    var ddAddressState = $get("txtLookupState");
    if (ddAddressState != null) {
        ddAddressState.options.length = 0;
        for (iCounter = 0; iCounter < oAddressStateList.length; iCounter++) {
            bIsSelected = false;
            sText = oAddressStateList[iCounter].Text;
            sValue = oAddressStateList[iCounter].Value;

            if (sValue == "SP")
                bIsSelected = true;

            ddAddressState.options[ddAddressState.options.length] = new Option(sValue, sValue, bIsSelected);
        }
    }
}

function cleanBasketLookup() {
    document.getElementById("resultDNE").innerHTML = "";
    document.getElementById('txtLookupAddress').value = "";
    document.getElementById('txtLookupQuarter').value = "";
    document.getElementById('txtLookupCity').value = "";
    document.getElementById('txtLookupState').value = "SP";

    if (document.getElementById('errEmptyAddress'))
        document.getElementById('errEmptyAddress').style.visibility = 'hidden';

    if (document.getElementById('errEmptyCity'))
        document.getElementById('errEmptyCity').style.visibility = 'hidden';
}

function basketDoZipLookup() {
    var bError = false;

    sAddress = document.getElementById('txtLookupAddress').value;
    sQuarter = document.getElementById('txtLookupQuarter').value;
    sCity = document.getElementById('txtLookupCity').value;
    sState = document.getElementById('txtLookupState').value;

    if (sAddress.length < 1) {
        if (document.getElementById('errEmptyAddress')) {
            document.getElementById('errEmptyAddress').style.visibility = 'visible';
            if (document.getElementById('resultDNE')) {
                document.getElementById('resultDNE').style.visibility = 'hidden';
            }
            if (document.getElementById('divZipExpand')) {
                document.getElementById('divZipExpand').style.height = '200px';
            }
        }
        bError = true;
    }
    else {
        if (document.getElementById('errEmptyAddress'))
            document.getElementById('errEmptyAddress').style.visibility = 'hidden';
    }

    if ((sCity.length < 1) | (sState.length < 2)) {
        if (document.getElementById('errEmptyCity')) {
            document.getElementById('errEmptyCity').style.visibility = 'visible';
            if (document.getElementById('resultDNE')) {
                document.getElementById('resultDNE').style.visibility = 'hidden';
            }
            if (document.getElementById('divZipExpand')) {
                document.getElementById('divZipExpand').style.height = '200px';
            }
        }
        bError = true;
    }
    else {
        if (document.getElementById('errEmptyCity'))
            document.getElementById('errEmptyCity').style.visibility = 'hidden';
    }

    if (bError) {
        document.getElementById('txtLookupAddress').focus();
        return false;
    }

    loadingElement = document.getElementById("lpgClientSideProgress");
    loadingTimeout = window.setTimeout("showLoadingProgress();", 500);

    //FastShop2008Web.FastShopAjax.GetListShipAddress(sAddress, sQuarter, sCity, sState, basketShowZipLookupResult);
    $.ajax({
        type: "POST",
        url: $.browser.rootUrl + "/FastshopAjaxMethod.aspx/GetListShipAddress",
        data: "{'dsAddress':'" + sAddress + "', 'dsQuarter':'" + sQuarter + "', 'dsCity':'" + sCity + "', 'dsState':'" + sState + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            basketShowZipLookupResult({ value: result.d });
        }
    });
}

function basketShowZipLookupResult(ret) {
    if (loadingTimeout) {
        clearTimeout(loadingTimeout);
        loadingTimeout = null;
    }

    if (loadingElement)
        loadingElement.style.display = "none";

    if (ret.value != null) {
        var oDNEAddress;
        var table;
        var iAddress;
        iAddress = 0;
        table = "<table width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" border=\"0\" style=\"*width: 96%;\">\n";
        oDNEAddress = ret.value;

        if (oDNEAddress.length <= 0) {
            alert("Nenhum endereço encontrado.");
            document.getElementById("resultDNE").innerHTML = "";
            if (document.getElementById('resultDNE')) {
                document.getElementById('resultDNE').style.visibility = 'hidden';
            }
            if (document.getElementById('divZipExpand')) {
                document.getElementById('divZipExpand').style.height = '200px';
            }

            return;
        }
        if (document.getElementById('resultDNE')) {
            document.getElementById('resultDNE').style.visibility = 'visible';
        }
        if (document.getElementById('divZipExpand')) {
            document.getElementById('divZipExpand').style.height = '340px';
        }

        if (oDNEAddress.length > 299) {
            table = "";
            table = "<div style='color: red; padding: 10px;'>Sua pesquisa retornou " + oDNEAddress.length + " ou mais endereços.<br />Para obter um melhor resultado, refine sua busca.</div>";
            table = table + "<table width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" border=\"0\" style=\"*width: 96%;\">\n";
        }

        for (iAddress = 0; iAddress < oDNEAddress.length; iAddress++) {
            if ((iAddress % 2) == 0)
                sColor = "#ddd";
            else
                sColor = "#fff";

            table = table + "<tr style='background-color: " + sColor + ";'>\n<td width='60' style='text-align: center; height: 35px;cursor:pointer;text-decoration: underline;' onclick='basketPopulateZipCode(\"" + oDNEAddress[iAddress].dsZip + "\", \"" + oDNEAddress[iAddress].dsZipCompl + "\", \"" + oDNEAddress[iAddress].dsAddressType + "\", \"" + oDNEAddress[iAddress].dsStreet + "\", \"" + oDNEAddress[iAddress].dsQuarter + "\", \"" + oDNEAddress[iAddress].dsCity + "\", \"" + oDNEAddress[iAddress].dsState + "\")'>" + oDNEAddress[iAddress].dsZip + "-" + oDNEAddress[iAddress].dsZipCompl + "</td>\n";
            table = table + "<td width='50' style='text-align: center;'>" + oDNEAddress[iAddress].dsAddressType + "</td>\n";
            table = table + "<td width='90'>" + oDNEAddress[iAddress].dsStreet + "</td>\n";
            table = table + "<td style='text-align: center;'>" + oDNEAddress[iAddress].dsCompl + "</td>\n";
            table = table + "<td width='90'>" + oDNEAddress[iAddress].dsQuarter + "</td>\n";
            table = table + "<td width='80' style='text-align: center;'>" + oDNEAddress[iAddress].dsCity + "</td>\n";
            table = table + "<td width='30' style='text-align: center;'>" + oDNEAddress[iAddress].dsState + "</td>\n</tr>\n";
        }
        table = table + "</table>"
        document.getElementById("resultDNE").innerHTML = table;
    }
    else {
        alert("Nenhum endereço encontrado.");
        document.getElementById("resultDNE").innerHTML = "";
    }
}

function basketPopulateZipCode(sZip, sZipCompl, sAddressType, sStreet, sQuarter, sCity, sState)
{

    var zipField = document.getElementById(zipFieldId);
    var zipCompl = document.getElementById(zipComplFieldId);
    
    var addressTypeField = document.getElementById(addressTypeFieldId)
    var addressField = document.getElementById(addressFieldId);
    var quarterField = document.getElementById(quarterFieldId);
    var cityField = document.getElementById(cityFieldId);
    var stateField = document.getElementById(stateFieldId);
    var numberField = numberFieldId ? document.getElementById(numberFieldId) : null;
    var complField = complFieldId ? document.getElementById(complFieldId) : null;
    
    isDisabled = true;
    RegisterData(null);
    
    if (zipField && zipCompl)
    {
        zipField.value = sZip;
        zipCompl.value = sZipCompl;
        
        if (document.getElementById('ctl00_body_ucProductsList_cmdUpdateList'))
            __doPostBack('ctl00$body$ucProductsList$cmdUpdateList', '');

        if (document.getElementById('ctl00_body_btnShipDelivery'))
            __doPostBack('ctl00$body$btnShipDelivery', '');            
    }
    
    if (addressField && sStreet)
    {
        if (addressTypeField)
        {
            for (i=0; i < addressTypeField.options.length; i++)
                if (addressTypeField.options[i].text == sAddressType)
                    addressTypeField.options[i].selected = true;
        }
        
        addressField.value = sStreet;
        quarterField.value = sQuarter;
        cityField.value = sCity;
        
        for (i=0; i < stateField.options.length; i++)
            if (stateField.options[i].value == sState)
                stateField.options[i].selected = true;
        
        if (numberField) numberField.value = "";
        if (complField) complField.value = "";
    }
    
    isDisabled = false;
    RegisterData(null);
    
    showZipLookup("dvZipLookup", null, false);
}

function showLoadingProgress()
{
    if (loadingElement)
        loadingElement.style.display = "block";
        
    if (loadingTimeout)
    {
        clearTimeout(loadingTimeout);
        loadingTimeout = null;
    }
}

// ******** Preenchimento automático **************
var isDisabled = true;
var lastZipRequest = "";
var defaultAddressType = "";
if (!isAddressTypeSelected)
    var isAddressTypeSelected = false;
function SetReadOnly(bStatus)
{
    var opt = null;
    var isReadOnly = false;
    if (!this.addressField)
        return;
    
    // Define o estado de edição dos controles de tela
    
    isReadOnly = (bStatus && this.addressField.value.trim().length > 0);
    this.addressField.readOnly = isReadOnly;
    
    isReadOnly = (bStatus && this.quarterField.value.trim().length > 0);
    this.quarterField.readOnly = isReadOnly;
    
    isReadOnly = (bStatus && this.cityField.value.trim().length > 0);
    this.cityField.readOnly = isReadOnly;
    
    // Altera o estado de edição dos DropDowns (AddressType e State)
    if (bStatus)
    {
        // Somente Leitura
        if (isAddressTypeSelected)
        {
            opt = null;
            if (!this.addressTypeField.oldOptions)
            {
                this.addressTypeField.oldOptions = new Array(this.addressTypeField.options.length);
                for (k in this.addressTypeField.options)
                {
                    if ((typeof(k) == "string" && parseInt(k.trim(), 10) >= 0) ||
                        (typeof(k) == "number" && parseInt(k, 10) >= 0))
                    {
                        if (this.addressTypeField.options[k].selected)
                            opt = this.addressTypeField.options[k];
                        
                        this.addressTypeField.oldOptions[k] = new Option(this.addressTypeField.options[k].text, this.addressTypeField.options[k].value);
                    }
                }
                
                if (opt)
                {
                    this.addressTypeField.options.length = 0;
                    this.addressTypeField.options[0] = opt;
                }
            }
        }
        
        if (this.stateField.selectedIndex > 0)
        {
            opt = null;
            if (!this.stateField.oldOptions)
            {
                this.stateField.oldOptions = new Array(this.stateField.options.length);
                for (k in this.stateField.options)
                {
                    if ((typeof(k) == "string" && parseInt(k.trim(), 10) >= 0) ||
                        (typeof(k) == "number" && parseInt(k, 10) >= 0))
                    {
                        if (this.stateField.options[k].selected)
                            opt = this.stateField.options[k];
                            
                        this.stateField.oldOptions[k] = new Option(this.stateField.options[k].text, this.stateField.options[k].value);
                    }
                }
                
                if (opt)
                {
                    this.stateField.options.length = 0;
                    this.stateField.options[0] = opt;
                }
            }
        }
    }
    else
    {
        // Editável/Selecionável
        if (this.addressTypeField.oldOptions)
        {
            this.addressTypeField.options.length = this.addressTypeField.oldOptions.length;
            for(k in this.addressTypeField.oldOptions)
            {
                if ((typeof(k) == "string" && parseInt(k.trim(), 10) >= 0) ||
                    (typeof(k) == "number" && parseInt(k, 10) >= 0))
                    this.addressTypeField.options[k] = new Option(this.addressTypeField.oldOptions[k].text, this.addressTypeField.oldOptions[k].value);
            }
            this.addressTypeField.oldOptions = null;
            isAddressTypeSelected = false;
        }
        if (this.stateField.oldOptions)
        {
            this.stateField.options.length = this.stateField.oldOptions.length;
            for(k in this.stateField.oldOptions)
            {
                if ((typeof(k) == "string" && parseInt(k.trim(), 10) >= 0) ||
                    (typeof(k) == "number" && parseInt(k, 10) >= 0))
                    this.stateField.options[k] = this.stateField.oldOptions[k];
            }
            this.stateField.oldOptions = null;
        }
    }
    
    // Limpa os campos, no caso de estar permitindo que os mesmos sejam editados novamente
    if (isDisabled && !bStatus)
    {
        this.addressField.value = "";
        this.quarterField.value = "";
        this.cityField.value = "";
        this.numberField.value = "";
        this.complField.value = "";
        this.addressTypeField.value = defaultAddressType;
        this.stateField.selectedIndex = 0;
    }
    
    // Atualiza o status de edição dos controles de tela
    isDisabled = bStatus;
}

function ReadOnlyAll() {
    this.addressField.readOnly = true;
    this.quarterField.readOnly = true;
    this.cityField.readOnly = true;
    this.addressTypeField.readOnly = true;
}

function LoadAll()
{
    var Zip = document.getElementById(zipFieldId).value.trim();
    var ZipCompl = document.getElementById(zipComplFieldId).value.trim();
    if (Zip.length == 5 && ZipCompl.length == 3 && lastZipRequest != Zip + ZipCompl)
    {
        lastZipRequest = Zip + ZipCompl;
        //FastShop2008Web.FastShopAjax.GetShipAddress(Zip, ZipCompl, RegisterData);
        $.ajax({
            type: "POST",
            url: $.browser.rootUrl + "/FastshopAjaxMethod.aspx/GetShipAddress",
            data: "{'dsZip':'" + Zip + "', 'dsZipCompl':'" + ZipCompl + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
              RegisterData({value:result.d});
            }
        });
    }
}

function RegisterData(ret)
{
    // Retorna uma referência aos controles de tela
    this.zipField = document.getElementById(zipFieldId);
    this.zipCompl = document.getElementById(zipComplFieldId);
    this.addressTypeField = document.getElementById(addressTypeFieldId);
    this.addressField = document.getElementById(addressFieldId);
    this.quarterField = document.getElementById(quarterFieldId);
    this.cityField = document.getElementById(cityFieldId);
    this.stateField = document.getElementById(stateFieldId);
    this.numberField = numberFieldId ? document.getElementById(numberFieldId) : null;
    this.complField = complFieldId ? document.getElementById(complFieldId) : null;
            if (document.getElementById("ctl00_ContentPlaceHolder1_lblZipError") != null) {
                document.getElementById("ctl00_ContentPlaceHolder1_lblZipError").style.display="none";
            }
            else if (document.getElementById("ctl00_body_lblZipError") != null) {
                document.getElementById("ctl00_body_lblZipError").style.display="none";
            }
            if (document.getElementById("ctl00_ContentPlaceHolder1_lblZipErrorCompany") != null) {
                document.getElementById("ctl00_ContentPlaceHolder1_lblZipErrorCompany").style.display = "none";
            }


    if (ret && ret.value && ret.value.dsCity.trim() != "")
    {
        oDNEAddress = ret.value;

        // Popula os controles de tela com as informações retornadas
        this.zipField.value = oDNEAddress.dsZip ;
        this.zipCompl.value = oDNEAddress.dsZipCompl; 
        this.addressField.value = oDNEAddress.dsStreet;
        this.quarterField.value = oDNEAddress.dsQuarter;
        this.cityField.value = oDNEAddress.dsCity;
        this.stateField.value = oDNEAddress.dsState;
        this.addressTypeField.value = oDNEAddress.dsAddressTypeId;
        if (this.numberField) this.numberField.value = "";
        if (this.complField) this.complField.value = "";
        
        if (oDNEAddress.dsAddressTypeId.trim() != "")
            isAddressTypeSelected = true;
        else
        {
            isAddressTypeSelected = false;
            this.addressTypeField.value = defaultAddressType;
        }
        
        if (typeof(Page_ClientValidate) == "function")
            Page_ClientValidate();
        
        // Desabilita os controles de tela que não poderão ser alterados
        SetReadOnly.call(this, true);
    }
    else
    {
        if (ret === false)
            isDisabled = false;
        
        SetReadOnly.call(this, !isDisabled);
        
        if (ret)
        {
            if (document.getElementById("ctl00_ContentPlaceHolder1_lblZipError") != null) {
                document.getElementById("ctl00_ContentPlaceHolder1_lblZipError").style.display="block";
            }
            else if (document.getElementById("ctl00_body_lblZipError") != null) {
                document.getElementById("ctl00_body_lblZipError").style.display="block";
            }
            if (document.getElementById("ctl00_ContentPlaceHolder1_lblZipErrorCompany") != null) {
                document.getElementById("ctl00_ContentPlaceHolder1_lblZipErrorCompany").style.display = "block";
            }

            //alert("Não existe cadastro");
            ReadOnlyAll();
        }
        else
            if (!isDisabled)
                lastZipRequest = "";
    }
    
    return true;
}

function initRegisterData()
{
    RegisterData(false);
}

$(initRegisterData);
