﻿// ------------------------------------------------------------------------------------------
// Copyright AspDotNetStorefront.com, 1995-2010.  All Rights Reserved.
// http://www.aspdotnetstorefront.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
function $bindMethod(object, method) {
    return function() {
        return method.apply(object, arguments);
    };
}

function $window_addLoad(handler) {
    if (window.addEventListener) {
        window.addEventListener('load', handler, false);
    }
    else if (document.addEventListener) {
        document.addEventListener('load', handler, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onload', handler);
    }
    else {
        if (typeof window.onload == 'function') {
            var oldload = window.onload;
            window.onload = function() {
                oldload();
                handler();
            }
        }
        else { window.onload = init; }
    }

}

function $getElement(id, handler) {
    var el = document.getElementById(id);
    return el;
}

var Keys = {
    Enter: 13
}

function validateDDD(field) 
{
    var valid = "0123456789"
    var ok = "yes";
    var temp;
    var campo = document.getElementById("ctl00_PageContent_" + field).value;
    for (var i = 0; i < campo.length; i++) {
        temp = "" + campo.substring(i, i + 1);
        if (valid.indexOf(temp) == "-1") ok = "no";
    }
    if (ok == "no") 
    {
        alert("Este campo aceita apenas números. Digite novamente.");
        document.getElementById("ctl00_PageContent_" + field).value = '';
        document.getElementById("ctl00_PageContent_" + field).focus();
    }       
    
    if(ok == "yes")
    {
        var validDDD=["11","12","13","14","15","16","17","18","19","21","22","24","27","28","31","32","33","34","35","37","38","41","42","43","44","45","46","47","48","49","51","53","54","55","61","62","63","64","65","66","67","68","69","71","73","74","75","77","79","81","82","83","84","85","86","87","88","89","91","92","93","94","95","96","97","98","99"];  
        var okDDD = "no";
        var tempDDD;
        var campoDDD = document.getElementById("ctl00_PageContent_" + field).value;
        
        for (var i = 0; i < validDDD.length; i++) {
            tempDDD = campoDDD.indexOf(validDDD[i]);
            if(tempDDD != "-1")
            {
              okDDD = "sim";
              break;
            }    
        }
        if (okDDD == "no") 
        {
            alert("DDD inexistente. Digite um DDD válido.");
            document.getElementById("ctl00_PageContent_" + field).value = '';
            document.getElementById("ctl00_PageContent_" + field).focus();
        }
    }   
}

function $handleSearchEnterKey(id, handler) {
    var el = $getElement(id);
    if (el) {
        var delKeypress = function(e) {

            var keyCode;
            if (e && e.which) {
                keyCode = e.which;
            }
            else if (typeof (event) != 'undefined') {
                keyCode = event.keyCode;
            }

            // we must manually invoke the Page_ClientValidate
            // method here since relying on the normal behavior
            // is not guaranteed to set the appropriate validation flags
            // to stop the postback.
            if (keyCode == Keys.Enter) {
                if (typeof (Page_ClientValidate) != 'undefined') {
                    if (Page_ClientValidate() == false) {
                        return;
                    }
                }

                handler();

                return false;
            }
        }

        el.onkeypress = delKeypress;
    }

}

function MM_formtCep(e, src, mask) {
    if (window.event) { _TXT = e.keyCode; }
    else if (e.which) { _TXT = e.which; }
    if (_TXT > 47 && _TXT < 58) {
        var i = src.value.length; var saida = mask.substring(0, 1); var texto = mask.substring(i)
        if (texto.substring(0, 1) != saida) { src.value += texto.substring(0, 1); }
        return true;
    } else {
        if (_TXT != 8) { return false; }
        else { return true; }
    }
}


var postJSON = function(url, data, callback) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: "POST",
        url: url,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: callback
    });
};

var convert2JSON = function(response) {
    return (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
};
//adiciona uma linha da combo para cada estado.
function addOption(selectbox,text,value )
{
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	document.getElementById(selectbox).options.add(optn);
}
//adiciona estados na combo.
function addOption_list(selectbox)
{
    addOption(selectbox, "Acre","AC");
    addOption(selectbox, "Alagoas","AL");
    addOption(selectbox, "Amapá","AP");
    addOption(selectbox, "Amazonas","AM");
    addOption(selectbox, "Bahia","BA");
    addOption(selectbox, "Ceará","CE");
    addOption(selectbox, "Distrito Federal","DF");
    addOption(selectbox, "Goiás","GO");
    addOption(selectbox, "Espírito Santo","ES");
    addOption(selectbox, "Maranhão","MA");
    addOption(selectbox, "Mato Grosso","MT");
    addOption(selectbox, "Mato Grosso do Sul","MS");
    addOption(selectbox, "Minas Gerais","MG");
    addOption(selectbox, "Pará","PA");
    addOption(selectbox, "Paraíba","PB");
    addOption(selectbox, "Paraná","PR");
    addOption(selectbox, "Pernambuco","PE");
    addOption(selectbox, "Piauí","PI");
    addOption(selectbox, "Rio de Janeiro","RJ");
    addOption(selectbox, "Rio Grande do Norte","RN");
    addOption(selectbox, "Rio Grande do Sul","RS");
    addOption(selectbox, "Rondônia","RO");
    addOption(selectbox, "Rorâima","RR");
    addOption(selectbox, "São Paulo","SP");
    addOption(selectbox, "Santa Catarina","SC");
    addOption(selectbox, "Sergipe","SE");
    addOption(selectbox, "Tocantins","TO");
}
 //Removendo todos os estados da combo, menos o estado que vem selecionado na combo.
function removeAllOptions(selectbox, uf) 
{
    var i;

    for (i = document.getElementById(selectbox).options.length - 1; i >= 0; i--) 
    {
        if (document.getElementById(selectbox).options[i].value != uf)
            document.getElementById(selectbox).remove(i);
    }
}

function getCEP(param, controle) {
    var base = $$(controle).attr("id");

    var params = "{'CEP':'" + $('#' + param).val().replace('-', '') + "'}";
    //postJSON("http://localhost:4380/Web/ConsultarCEP.asmx/getCEP", params, function(response) {
    postJSON("/ConsultarCEP.asmx/getCEP", params, function(response) {
        var cep = convert2JSON(response);

        setEnableFields(base, '_Address1', false);
        setEnableFields(base, '_City', false);
        removeAllOptions(base + '_State', cep.uf);
        addOption_list(base + '_State');
        setEnableFields(base, '_State', true);
        setEnableFields(base, '_Suite', false);
        setEnableFields(base, '_Numero', false);
        setEnableFields(base, '_Address2', false);


        if (cep.erro == "") {
            removeAllOptions(base + '_State', cep.uf);

            setValueFields(base, '_Address1', cep.logradouro);
            setValueFields(base, '_City', cep.cidade);
            setValueFields(base, '_State', cep.uf);
            setValueFields(base, '_Suite', cep.bairro);
            setValueFields(base, '_HDNumeroObrigatorio', cep.numObrigatorio);
            if (cep.numero != "") {
                
                setValueFields(base, '_Numero', cep.numero);
                setValueFields(base, '_Address2', cep.complemento);
                setEnableFields(base, '_Numero', false);
                setEnableFields(base, '_Address2', false);
            }
            else {
                document.getElementById(base + '_Numero').focus();
                setValueFields(base, '_Numero', '')
                setValueFields(base, '_Address2', '')
                setEnableFields(base, '_Numero', true);
                setEnableFields(base, '_Address2', true);
            }

        }
        else {
            //chama função que adiciona todos os elementos da combo.
            removeAllOptions(base + '_State', cep.uf);
            addOption_list(base + '_State');
            if (confirm(cep.erro + ". Deseja continuar ?")) {

                setValueFields(base, '_Address1', '');
                setValueFields(base, '_City', '');
                setValueFields(base, '_State', '');
                setValueFields(base, '_Suite', '');
                setValueFields(base, '_Numero', '');
                setValueFields(base, '_Address2', '');

                //habilita os controles

                setEnableFields(base, '_Address1', true);
                setEnableFields(base, '_City', true);
                setEnableFields(base, '_State', true);
                setEnableFields(base, '_Suite', true);
                setEnableFields(base, '_Numero', true);
                setEnableFields(base, '_Address2', true);
            }

            else {

                setValueFields(base, '_Zip', '');
                setValueFields(base, '_Address1', '');
                setValueFields(base, '_City', '');
                setValueFields(base, '_State', '');
                setValueFields(base, '_Suite', '');
                setValueFields(base, '_Numero', '');
                setValueFields(base, '_Address2', '');

                //habilita os controles

                setEnableFields(base, '_Address1', true);
                setEnableFields(base, '_City', true);
                setEnableFields(base, '_State', true);
                setEnableFields(base, '_Suite', true);
                setEnableFields(base, '_Numero', true);
                setEnableFields(base, '_Address2', true);

            }
        }
    });
};

function $$(id, context) {
    var el = $("#" + id, context);
    if (el.length < 1)
        el = $("[id$=_" + id + "]", context);
    return el;
}

function ShowCep() {

    window.open('http://www.buscacep.correios.com.br/', '', 'menubar=0,location=0,status=0,scrollbars=1,width=746,height=464');

}


function setEnableFields(base, control, enable) {

    if (!enable) {
        $('#' + base + control).attr("disabled", false);
        $('#' + base + control).attr("readOnly", true);
        if (control != '_State') {
            $('#' + base + control).attr("style", "background-color:#EBEBE4;color:#444");
        }
    }
    else {
        $('#' + base + control).attr("disabled", false);
        $('#' + base + control).attr("readOnly", false);
        if (control != '_State') {
            $('#' + base + control).attr("style", "background-color:#FFFFFF;color:#000000");
        }
    }
}
function setValueFields(base, control, value) {

    $('#' + base + control).val(value);

}

