﻿var Utils = function () {
    var ajax = {
        msgAjax: {
            "terror": "Ops! Por favor, tente novamente.",
            "taguarde": "<img src=\"/Images/ajax-loader.gif\" alt=\"Carregando...\" width=\"24\" height=\"24\" /><p>Carregando...</p>"
        },

        init: function (text) {
            $(document).ajaxStart(function () {
                ajax.start(text);
            });
            $(document).ajaxStop(function () {
                ajax.stop();
            });
            $(document).ajaxError(function (e, request, msgAjax) {
                ajax.error(e, request, msgAjax);
            });
        },

        start: function (text) {
            text = text || this.msgAjax.taguarde;
            $('#carregando').html(text);
            $('#carregando').removeClass('hide');
        },

        stop: function () {
            $('#carregando').addClass('hide');
            $('#carregando').addClass('hide');
        },

        error: function (e, request, msgAjax) {
            this.stop();
        }
    };

    return {
        //Valida se é nulo ou empty
        isNullOrEmpty: function (valor) {
            if (!valor || valor == null || valor == "") {
                return true;
            } else {
                return false;
            }
        },

        ajaxText: function (text) {
            ajax.msgAjax.taguarde = text;
        },

        ajaxStart: function (text) {
            ajax.start(text);
        },

        ajaxStop: function () {
            ajax.stop();
        },

        //Remove acentuação em uma string
        removeAcentos: function (string) {
            var r = string.toLowerCase();
            r = r.replace(new RegExp("\\s", 'g'), " ");
            r = r.replace(new RegExp("[àáâãäå]", 'g'), "a");
            r = r.replace(new RegExp("æ", 'g'), "ae");
            r = r.replace(new RegExp("ç", 'g'), "c");
            r = r.replace(new RegExp("[èéêë]", 'g'), "e");
            r = r.replace(new RegExp("[ìíîï]", 'g'), "i");
            r = r.replace(new RegExp("ñ", 'g'), "n");
            r = r.replace(new RegExp("[òóôõö]", 'g'), "o");
            r = r.replace(new RegExp("œ", 'g'), "oe");
            r = r.replace(new RegExp("[ùúûü]", 'g'), "u");
            r = r.replace(new RegExp("[ýÿ]", 'g'), "y");
            r = r.replace(new RegExp("\\W", 'g'), " ");
            return r;
        },

        //Controla enter
        Enter: function (e) {
            var code = e.which || e.keyCode;
            if (code == 13) {
                return true;
            }
            return false;
        },

        //Retorna valor de qualquer parâmetro na url atual
        QueryString: function (param) {
            var valParam = null,
                url = window.location.search.substring(1),
                urlSplit = url.split("&");
            for (i = 0; i < urlSplit.length; i++) {
                valParam = urlSplit[i].split("=");
                if (valParam[0] == param) {
                    return valParam[1];
                }
            }
            return null;
        },

        init: function () {
            ajax.init();
        },

        //Formata url amigável
        Rewrite: function (str) {
            newStr = new String(Utils.removeAcentos(str)).toLowerCase().replace("_", "").replace(/\s/gi, "-").replace(".", "").replace(";", "").replace(":", "").replace("--", "-").replace("/", "-").replace(",", "-");
            return newStr;
        },

        //Funçao de Imprimir
        Print: function (object) {
            $(object).click(function () {
                return window.print();
            });
        },

        //Marca campos vazios com borda vermelha
        ValidaCamposVazios: function (val, args) {
            if (Utils.isNullOrEmpty(args.Value) || args.Value == "0") {
                args.IsValid = false;
                $("#" + val.controltovalidate).css("border", "1px solid #F00");
            } else {
                args.IsValid = true;
                $("#" + val.controltovalidate).css("border", "0px");
            }
        },

        //Marca campos com e-mail inválido com borda vermelha
        ValidaCamposEmail: function (val, args) {
            var regex = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
            if (!Utils.isNullOrEmpty(args.Value)) {
                if (regex.test(args.Value) != true) {
                    args.IsValid = false;
                    $("#" + val.controltovalidate).css("border", "1px solid #F00");
                } else {
                    $("#" + val.controltovalidate).css("border", "0px");
                    args.IsValid = true;
                }
            } else {
                $("#" + val.controltovalidate).css("border", "1px solid #F00")
                args.IsValid = false;
            }
        },

        //Permite somente números
        regIsNumber: function (evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46 && charCode != 44) {
                return false;
            }
            return true;
        },

        //Método usado no initCallback do jcarousel
        MycarouselInitCallback: function (carousel) {
            carousel.buttonNext.bind('click', function () {
                carousel.startAuto(0);
            });

            carousel.buttonPrev.bind('click', function () { carousel.startAuto(0); });

            carousel.clip.hover(function () {
                carousel.stopAuto();
            }, function () {
                carousel.startAuto();
            });
        },

        //Aplica cycle na galeria de imagens do produtos
        ExecCycle: function () {
            $('.pics').cycle({
                fx: 'fade',
                speed: 'slow',
                timeout: 0,
                pager: '.nav',
                pagerAnchorBuilder: function (idx, slide) {
                    return '.nav li:eq(' + (idx) + ') a';
                }
            });
        },

        //Marca root do menu de acordo com a página acessada
        MarcaMenuTopo: function () {
            $(function () {
                var text = $(".titInternas").text().trim(),
                ativar = null,
                itens = $(".menu > li > a");
                var url = window.location.toString();
                url = url.search(/produto/i);
                if (url > 0) {
                    text = $(".titInternasDetalhe").text().trim();
                }


                $.each(itens,
                function (i, item) {
                    if ($(item).text().trim() == text) {
                        ativar = $(".menu > li > a").eq(i);
                    }
                    else {
                        var subItens = $(".menu > li > ul").eq(i);
                        if (subItens.length > 0) {
                            var liSub = $(".menu > li").eq(i);
                            liSub = $(liSub).find("ul");
                            if (liSub.length > 0) {
                                liSub = $(liSub).find("li");
                                $.each(liSub,
                                function (j, itemJ) {
                                    var linhaLi = $(item).text().trim();
                                    var nwUrl = new String(window.location.href);
                                    if ($(itemJ).text().trim() == "Calcinha") {
                                        if (nwUrl.search(linhaLi.toString().toLowerCase()) >= 0) {
                                            ativar = $(".menu > li > a").eq(i);
                                        }
                                    } else if ($(itemJ).text().trim() == text && $(itemJ).text().trim() != "Calcinha") {
                                        ativar = $(".menu > li > a").eq(i);
                                    }
                                });
                            }
                        }
                    }
                });
                $(ativar).addClass("selected");
            });
        }
    };
} ();

$(function () {
    Utils.init();
});
