var LINK_KALUNGA = "index.html";
var LINK_PAGE = window.location.href.toLowerCase();

this.Validate = function(id)
{
    if (typeof(Page_Validators) == "undefined")  return;
    obj = GetByID(id);
    if(obj)
    {
        ValidatorValidate(obj);
    }

}

this.AbreDuvidas = function()
{
	window.open('/Lojavirtual.aspx?Reduzido=true',"pop","width=785,height=500,status=no,scrollbars=yes,top=80,left=80");
}

this.AbreChat = function()
{
	var Top  = (screen.availHeight - 390) / 2;
	var Left = (screen.availWidth  - 430) / 2;	

	var Params = "scrollbars=no,height=540,width=430,location=no,menubar=no,resizable=no,titlebar=no,toolbar=no,left=" + Left + ",top=" + Top;		
	window.open('http://suporte.revistakalunga.com.br/chat/chat.php', 'pop', Params);
}


function SetCookie(c_name, value, exdays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);

    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function GetCookie(c_name)
{
    var i, x, y, ARRcookies = document.cookie.split(";");

    for (i = 0; i < ARRcookies.length; i++)
    {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        
        if (x == c_name)
        {
            return unescape(y);
        }
    }
}


function formataValor(campo) 
{
	campo.value = filtraCampo(campo);
	vr = campo.value;
	tam = vr.length;

	if ( tam <= 2 )
    {
 		campo.value = vr ; 
    }
 	if ( (tam > 2) && (tam <= 5) )
    {
 		campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
    }
 	if ( (tam >= 6) && (tam <= 8) ){
 		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
 	if ( (tam >= 9) && (tam <= 11) ){
 		campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
 	if ( (tam >= 12) && (tam <= 14) ){
 		campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
 	if ( (tam >= 15) && (tam <= 18) ){
 		campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
}

function filtraCampo(campo){
	var s = "";
	var cp = "";
	var CaracValidos = /[-0123456789]/;
	vr = campo.value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {
		if(CaracValidos.test(vr.substring(i,i+1))){
		 	s = s + vr.substring(i,i + 1);}
	}
	campo.value = s;
   return cp = campo.value;
}


    var ScrollPosition = 0;
    var ScrollHandler  = null;

    this.SelectImage = function(image)
    {
        var newImage = Framework.GetElementByID('imgProduto');

        if(newImage)
        {
            newImage.src = '/_images/FotosdeProdutos/' + image;
        }
    }


    this.ViewList = function(id)
    { 
        ShadowBoxClose();

        Redirect("/minha-conta/lista-de-desejos/visualizar/"+id);
    }

    this.MoveScroll = function ()
    {
        if (ScrollPosition <= 0)
        {
            window.clearInterval(ScrollHandler);
        }
        else
        {
            ScrollPosition = ScrollPosition - 50;
            window.scrollTo(0, ScrollPosition);
        }
    }

    this.AddItem = function (Codigo, Nome, Preco)
    {
        var TXT = Framework.GetElementByID('txtQtd' + Codigo);

        if (TXT)
        {
            var Quantidade = parseInt(TXT.value);

            if (isNaN(Quantidade))
            {
                alert('A quantidade deve ser um valor numerico.');
                return false;
            }

            Quantidade = parseInt(Quantidade);

            if (Quantidade <= 0)
            {
                alert('A quantidade deve ser maior que zero (0).');
                return false;
            }

            AddToBasket(Codigo, Quantidade, Nome, Preco,false);
         
        }
    }

    this.AddItemShadowBox =  function (Codigo, Nome, Preco)
    {
        var TXT = Framework.GetElementByID('txtQtd' + Codigo);

        if (TXT)
        {
            var Quantidade = parseInt(TXT.value);

            if (isNaN(Quantidade))
            {
                alert('A quantidade deve ser um valor numerico.');
                return false;
            }

            Quantidade = parseInt(Quantidade);

            if (Quantidade <= 0)
            {
                alert('A quantidade deve ser maior que zero (0).');
                return false;
            }
            var URL = "/prod/tradein/"+ Nome+ "/" + Codigo + "/" + Quantidade;
            ShadowBoxOpenURLHidClose(URL, 520, 550, true);
        }
    }

    this.ShowBasketPopup = function (Codigo)
    {
        var TXT = Framework.GetElementByID('txtQtd' + Codigo);

        if (TXT)
        {
            var Quantidade = parseInt(TXT.value);

            if (isNaN(Quantidade))
            {
                alert('A quantidade deve ser um valor numerico.');
                return false;
            }

            Quantidade = parseInt(Quantidade);

            if (Quantidade <= 0)
            {
                alert('A quantidade deve ser maior que zero (0).');
                return false;
            }

            ShadowBoxOpenURL('/BasketItem.aspx?ID=' + Codigo + '&Quantidade=' + Quantidade, 520, 500, true);

        
        }
    }

    this.ShadowBoxOpenURL = function (URL, Width, Height, HideClose)
    {
        //HideScrollbars();

        Shadowbox.open
        (
            {
                content: URL,
                player: "iframe",
                title: "",
                height: Height,
                width: Width
            }
        );
    }

    this.ShadowBoxOpenHTM = function (HTML, Width, Height)
    {
        //HideScrollbars();

        Shadowbox.open
        (
            {
                content: HTML,
                player: "html",
                title: "",
                height: Height,
                width: Width
            }
        );
    }

    this.ShadowBoxOpenHTMHidClose = function (HTML, Width, Height,modal)
    {
        HideCloseButton();
        Shadowbox.open
        (
            {
                content: HTML,
                player: "html",
                title: "",
                height: Height,
                width: Width,
                options:   {modal: modal}
            }
        );
    }

    this.ShadowBoxOpenURLHidClose = function (URL, Width, Height, modal)
    {
        HideCloseButton();
        Shadowbox.open
        (
            {
                content: URL,
                player: "iframe",       
                title: "",
                height: Height,
                width: Width,
                options: { modal: modal }
            }
        );
    }

    this.ShadowBoxClose = function ()
    {
        Shadowbox.close();
    }

    this.ShowScrollbars = function ()
    {
        document.body.style.overflow = '';
    }

    this.HideScrollbars = function()
    {
        document.body.style.overflow = 'hidden'; 
    }

    this.HideCloseButton = function()
    {
        var close = $('#sb-nav-close');
        if(close)
        {
            close[0].style.visibility='hidden';
        }
    }

    this.ShowBasket = function (show)
    {

        if (GetByID('barraCarrinho') && GetByID('barraCarrinho').style.display == 'none')
        {
            var DIV_BASKET = Framework.GetElementByID('box_carrinho');
            var DIV_AVISO = Framework.GetElementByID('dvAviso');

            if (DIV_BASKET)
            {
                DIV_BASKET.style.display = show ? '' : 'none';
            }

            if (DIV_AVISO)
            {
                DIV_AVISO.style.display = 'none';
            }
        }
    }


    this.OpenCenteredWindow = function (url, width, heigth, features)
    {
        var win = null;
        
        var winl = (screen.width - width) / 2;
        var wint = (screen.height - heigth) / 2;

        if (winl < 0) winl = 0;
        if (wint < 0) wint = 0;

        var settings = 'height=' + heigth + ',';
        settings += 'width=' + width + ',';
        settings += 'top=' + wint + ',';
        settings += 'left=' + winl + ',';
        settings += features;

        win = window.open(url, 'popup', settings);
        win.window.focus();
        
    }

    this.trim = function(stringToTrim) 
    {
	    return stringToTrim.replace(/^\s+|\s+$/g,"");
    }

    this.ltrim = function(stringToTrim) 
    {
	    return stringToTrim.replace(/^\s+/,"");
    }

    this.rtrim = function(stringToTrim) 
    {
	    return stringToTrim.replace(/\s+$/,"");
    }

	this.autoTab = function(input, len, e) 
    {
        this.containsElement = function (arr, ele) 
        {
            var found = false, index = 0;

            while (!found && index < arr.length)
                if (arr[index] == ele)
                    found = true;
                else
                    index++;
            return found;
        }

        this.getIndex = function (input) 
        {
            var index = -1, i = 0, found = false;
            while (i < input.form.length && index == -1)
                if (input.form[i] == input) index = i;
                else i++;
            return index;
        }
        
        var isNN = (navigator.appName.indexOf("Netscape") != -1);

        var keyCode = (isNN) ? e.which : e.keyCode;
        var filter = (isNN) ? [0, 8, 9] : [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];
        if (input.value.length >= len && !containsElement(filter, keyCode)) 
        {
            input.value = input.value.slice(0, len);

            var control = input.form[(getIndex(input) + 1) % input.form.length];

            if (control.disabled && control.id == "txtIE") 
            {
                control = Framework.GetElementByID('dropRamoAtividade');

                if(control)
                {
                    control.focus();
                }

            }
            else if (control.id == "txtLogradouro") 
            {
                control = Framework.GetElementByID('txtNumero');

                if(control)
                {
                    control.focus();
                }

            }
            else if ((control.disabled || control.readonly) && control.id == "txtNumero") 
            {
                control = Framework.GetElementByID('txtComplemento');

                if(control)
                {
                    control.focus();
                }

            }
            else if (control.id == "txtTipoLogradouro") 
            {
                var controlNumber = Framework.GetElementByID('txtNumero');

                if(controlNumber)
                {
                    if (controlNumber.disabled) 
                    {
                        control = Framework.GetElementByID('txtComplemento');
                        control.focus();
                    }
                    else 
                    {
                        controlNumber.focus();
                    }
                }

            }
            else if(control.id.indexOf("hdnPrecoProduto") > -1)
            {
                var i = control.id.replace("hdnPrecoProduto", "");
                control = Framework.GetElementByID('txtQtd'+i);
                if(control)
                {
                    control.focus(); 
                }
            }
            else 
            {
                control.focus();
            }

        }


        return true;
    }




    this.FormatField = function (campo, Mascara, evento) 
    {
        var boleanoMascara;

        var Digitato = evento.keyCode;
        exp = /\-|\.|\/|\(|\)| /g
        campoSoNumeros = campo.value.toString().replace(exp, "");

        var posicaoCampo = 0;
        var NovoValorCampo = "";
        var TamanhoMascara = campoSoNumeros.length; ;

        if (Digitato != 8) {
            for (i = 0; i <= TamanhoMascara; i++)
            {
                boleanoMascara = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".") || (Mascara.charAt(i) == "index.html"))
                boleanoMascara = boleanoMascara || ((Mascara.charAt(i) == "(") || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))
                
                if (boleanoMascara) 
                {
                    NovoValorCampo += Mascara.charAt(i);
                    TamanhoMascara++;
                }
                else 
                {
                    NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);
                    posicaoCampo++;
                }
            }

            campo.value = NovoValorCampo;

            return true;
        }
        else 
        {
            return true;
        }
    }

    this.MaskDate = function(Data) 
    {    
        if (MaskInteger(Data) == false) 
        {
            event.returnValue = false;
        }

        return FormatField(Data, '00/00/0000', event);
    }

    this.MaskInteger = function () 
    {
        if (event.keyCode < 48 || event.keyCode > 57) 
        {
            event.returnValue = false;
            return false;
        }
        return true;
    }

    this.ValidateData = function (data) 
    {
        var objRegExp = new RegExp(/\d{2}\/\d{2}\/\d{4}/);
        return objRegExp.test(data);
    }

    this.isNum = function(caractere) 
    {
        var strValidos = "0123456789";

        if (strValidos.indexOf(caractere) == -1)
            return false;

        return true;
    }


    this.validaTecla = function (campo, event) 
    {
        var BACKSPACE = 8;
        var key;
        var tecla;

        CheckTAB = true;

        if (navigator.appName.indexOf("Netscape") != -1)
            tecla = event.which;
        else
            tecla = event.keyCode;

        key = String.fromCharCode(tecla);

        if (tecla == 13)
            return false;

        if (tecla == BACKSPACE)
            return true;


        return (isNum(key));
    }

    this.UpDown = function (Direction, Produto, sender)
    {
        var TXT = null;

        if(sender ==null)
        {
            var TXT = Framework.GetElementByID('txtQtd' + Produto);
        }
        else 
        {
            TXT = sender;
        }

        if (!isNaN(TXT.value))
        {
            var QTD = parseInt(TXT.value);

            if (Direction == 'UP')
            {
                QTD = QTD + 1;
            }
            else
            {
                if (QTD >= 2)
                {
                    QTD = QTD - 1;
                }
                else
                {
                    QTD = 1;
                }
            }

            TXT.value = QTD;
        }
    }

    // Exibe a popup de suprimentos
    this.ShowSuprimentos = function (Codigo, Nome)
    {
        Redirect('/busca-de-cartuchos/' + Nome.toLowerCase() + '/' + Codigo);
    }

    this.Redirect = function (url) 
    {
        window.location.href = url;
    }

    this.IsNumeric = function (elem)
    {
        var keynum;
        var e = window.event;
        var shift = e.shiftKey;
        var ctrl = e.ctrlKey;

        if (window.event)
        {
            keynum = e.keyCode;
        }
        else if (e.which)
        {
            keynum = e.which;
        }

        if (ctrl)
        {
            if (keynum == 67 || keynum == 86)
            {
                return true;
            }
        }
        return (keynum >= 96 && keynum <= 105) || keynum == 9 || keynum == 35 || keynum == 36 || keynum == 37 || keynum == 38 || keynum == 39 || keynum == 40 || keynum == 46 || (keynum >= 48 && keynum <= 57) || (keynum == 45 && currentText == '') || (keynum == 8) || (keynum == 127);
    }

    this.IsEmail = function (email) 
    {
        var objRegExp = new RegExp(/^[0-9A-Za-z]([\w0-9-_\.]*)@([A-Za-z0-9-_\.]*)\.(([A-Za-z]{3}\.[A-Za-z]{2}$)|([A-Za-z]{3}$)|([a-z]{2}$))/i);
        return objRegExp.test(email);
    }


    try 
    {

        HTMLElement.prototype.__defineGetter__.length;
        (
            function (body, removeChild) 
            {
                HTMLElement.prototype.__defineGetter__
                (
                    "outerHTML",
                    function () 
                    {
                        var self = body.appendChild(this.cloneNode(true)), outerHTML = body.innerHTML;
                        body.removeChild(self);
                        return outerHTML;
                    }
                );

                HTMLElement.prototype.__defineSetter__
                (
                    "outerHTML",
                    function (String) 
                    {
                        if (!String) 
                        {
                            removeChild(this);
                        }
                        else if (this.parentNode) 
                        {
                            body.innerHTML = String;
                            while (body.firstChild)
                                this.parentNode.insertBefore(body.firstChild, this);
                            removeChild(this);
                            body.innerHTML = "";
                        };
                    }
                );
            }
        )
        (
            document.createElement("body"),
            function (HTMLElement) 
            {
                if (HTMLElement.parentNode) HTMLElement.parentNode.removeChild(HTMLElement);
            }
        );
    }
    catch (e)
    {

    };

    //altera a css da qtd para amarelo quando a quantidade digitada for maior que a quantidade em estoque
    this.CheckQtd = function (codigo,qtdEstoque)
    {
        qtd = Framework.GetElementByID('txtQtd' + codigo);
        if ((qtd) && (qtd.value > qtdEstoque))
        {
            qtd.className = "campo2";
        }
        else
        {
            qtd.className = "campo";
        }
    }

this.alphaNumeric = function(obj) 
                    {
                        if (obj.value.match(/[^a-zA-Z0-9 áàâãéêíóõôúüçÁÀÂÃÉÊÍÓÕÔÚÜÇ]/g)) 
                        {
                            obj.value = obj.value.replace(/[^a-zA-Z0-9 áàâãéêíóõôúüçÁÀÂÃÉÊÍÓÕÔÚÜÇ]/g,'');
                        }
                        else 
                        {
                            return true;
                        }
                    }

/*Permite Hifen e ponto*/
this.alphaNumeric2 = function(obj) 
                    {
                        if (obj.value.match(/[^a-zA-Z0-9 áàâãéêíóõôúüçÁÀÂÃÉÊÍÓÕÔÚÜÇ.-]/g)) 
                        {
                            obj.value = obj.value.replace(/[^a-zA-Z0-9 áàâãéêíóõôúüçÁÀÂÃÉÊÍÓÕÔÚÜÇ.-]/g,'');
                        }
                        else 
                        {
                            return true;
                        }
                    }

this.numeric = function(obj) 
                    {
                        if (obj.value.match(/[^0-9]/g)) 
                        {
                            obj.value = obj.value.replace(/[^0-9]/g,'');
                        }
                        else 
                        {
                            return true;
                        }
                    }

this.ValidaNomeRazao = function(obj)
{
    if(obj)
    {
        var Nome = obj.value;
        var imgErro = GetByID('erroNome');
        // Valida o nome do titular do cartão
        if (Nome.indexOf(' ') == -1 || (Nome.indexOf(' ') != -1 && Nome.length == Nome.indexOf(' ') + 1))
        {
            alert('O Nome ou Razão Social deve possuir pelo menos duas palavras.');
            
            if(imgErro)
            {
                imgErro.style.display = "";
            }
            obj.focus();
            return false;
        }
        else
        {
            if(imgErro)
            {
                imgErro.style.display = "none";
            }
        }
    }
}

this.RedirectCadastro = function(URL)
{
    var LINK_KALUNGA = "index.html";
    if (URL.indexOf("url=basket") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/carrinho");
        }
        else
        {
            Redirect("/carrinho");
        }
    }
    else if (URL.indexOf("url=meuspedidos") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/minha-conta/meus-pedidos");
        }
        else
        {
            Redirect("/minha-conta/meus-pedidos");
        }
    }
    else if (URL.indexOf("url=minhaslistas") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/minha-conta/lista-de-desejos");
        }
        else
        {
            Redirect("/minha-conta/lista-de-desejos");
        }
    }
    else if (URL.indexOf("url=cadastropf") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Web.Response.Redirect(LINK_KALUNGA + "/minha-conta/cadastro/PessoaFisica");
        }
        else
        {
            Redirect("/minha-conta/cadastro/PessoaFisica");
        }
    }
    else if (URL.indexOf("url=meuscreditos") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/minha-conta/creditos");
        }
        else
        {
            Redirect("/minha-conta/creditos");
        }
    }
    else if (URL.indexOf("url=entrega") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/minha-conta/entrega");
        }
        else
        {
            Redirect("/minha-conta/entrega");
        }
    }
    else if (URL.indexOf("url=minhaconta") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/minha-conta");
        }
        else
        {
            Redirect("/minha-conta");
        }
    }
    else if (URL.indexOf("lojas/disponibilidade-estoque") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/lojas/disponibilidade-estoque");
        }
        else
        {
            Redirect("/lojas/disponibilidade-estoque");
        }
    }
    else if (URL.indexOf("url=cotacoes") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/cotacoes");
        }
        else
        {
            Redirect("/cotacoes");
        }
                        
    }
    else if (URL.indexOf("url=minhascotacoes") != -1)
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA + "/minha-conta/cotacoes");
        }
        else
        {
            Redirect("/minha-conta/cotacoes");
        }
    }
    else
    {
        if (URL.indexOf("localhost") == -1)
        {
            Redirect(LINK_KALUNGA);
        }
        else
        {
            Redirect("/home");
        }
    }
}
