//F5-Componente
(function($) {
    //var Versao: '1.0',
    $.EmptyMessage = function(string) {
        $("input[" + string + "]").each(function() {
            if ($(this).val() == '')
                $(this).val($(this).attr(string));
            $(this).focus(function() {
                if ($(this).val().toLowerCase() == $(this).attr(string).toLowerCase())
                    $(this).val('');
            });
            $(this).blur(function() {
                if ($(this).val() == '')
                    $(this).val($(this).attr(string));
            });
        });
    },

    $.Alerta = function(options) {
        var dialogClass = options.dialogClass != undefined ? options.dialogClass : 'ui-dialog-alerta';
        $dialog = $('<div id="' + dialogClass + '"> ' +
                            '    <div class="topo"> </div>' +
                            '    <div class="miolo">' +
                            '        <p class="texto">' + options.Mensagem + '        </p>' +
                            '        <p class="btnOk"><a href="javascript:void(0);">Ok</a></p>' +
                            '    </div>' +
                            '    <div class="rodape"></div>' +
                            '</div>');
        $dialog.dialog({
            dialogClass: dialogClass,
            resizable: options.resizable != undefined ? options.resizable : false,
            title: options.title != undefined ? options.title : 'Confirmar!',
            closeOnEscape: options.closeOnEscape != undefined ? options.closeOnEscape : false,
            stack: options.stack != undefined ? options.stack : false,
            modal: options.modal != undefined ? options.modal : true
        });

        $('.' + dialogClass + ' .ui-icon-closethick').html(options.closeText != undefined ? options.closeText : '').click(function() { $dialog.dialog('destroy') });
        $('p.btnOk', $dialog).click(function() { if (options.Evento != undefined) { options.Evento() }; $dialog.dialog('destroy'); });
        $dialog.dialog('open');
    },

    //Request em variaveis queryString 
    $.RequestQueryString = function(key, url) {
        var parametros = (url != undefined ? url : location.search).split("&");
        for (var i = 0; i < parametros.length; i++)
            if (parametros[i].split('=')[0] == key)
            return parametros[i].split('=')[1];
    }

    //Substring com texto de incremento e limitação de palavras 
    $.SubstringTexto = function(textsubstring, lengthText, textoIncremento) {
        if (textsubstring.length > lengthText && lengthText > 0) {
            textsubstring = textsubstring.substring(0, lengthText - textoIncremento.length);
            return textsubstring.substring(0, (textsubstring.lastIndexOf(' ') != -1 ? textsubstring.lastIndexOf(' ') : textsubstring.length)) + textoIncremento;
        } else
            return textsubstring;
    },

    /*Ex: 
    $.SexySelectOption({element:'#segurasltTipo' , oldValue:'02' , newValue:'15', newText:'fabio Uhhhhhh'})
    $.SexySelectOption({ element: '#segurasltTipo', indice: 1  });
    $.SexySelectOption({ element: '#segurasltTipo', indice: -1  }); //Mensagem default
    */
    $.SexySelectOption = function(options) {
        var $element = typeof (options.element) == 'string' ? $(options.element) : options.element;
        if (options.value != undefined) {
            var text = $('div.sexy select:first option:[value="' + options.value + '"]', $element).attr('text');
            if (text != undefined)
                $('div.sexy ul li:contains(\'' + text + '\')', $element).addClass('active').click();
            else {
                $('div.sexy input:first', $element).val('');
                $('div.sexy input:first', $element).focus();
            }
            return;
        }

        if (!isNaN(options.indice)) {
            var $element = $(options.element);
            if (options.indice == -1) {
                $('div.sexy input:first', $element).val('').blur();
                $('div.sexy select:first option', $element).removeAttr('selected');
                return;
            }
            var text = $('div.sexy select:first option:nth(' + options.indice + ')', $element).attr('selected', 'selected').html();
            if (options.newValue != undefined) {
                if (text != null) {
                    $('div.sexy ul li:contains(\'' + text + '\')', $element).html(options.newValue);
                    $('div.sexy select:first option:contains(\'' + text + '\')', $element).attr('text', options.newValue);
                    if ($('div.sexy ul li.active', $element).size() == 0) $('div.sexy ul li:contains(\'' + text + '\')', $element).addClass('active').click();
                } else {
                    $('div.sexy ul li:first', $element).html(options.newValue);
                    $('div.sexy select:first option:first', $element).attr('text', options.newValue);
                    if ($('div.sexy ul li.active', $element).size() == 0) $('div.sexy ul li:first', $element).addClass('active').click();
                }
                if ($('div.sexy ul li.active', $element).size() == 0)
                    $('div.sexy input:first', $element).val(options.newValue);
            } else {
                $('div.sexy ul li:contains(\'' + text + '\')', $element).addClass('active').click();
            }
            return;
        }
        var oldText = $('div.sexy select:first option:[value="' + options.oldValue + '"]', $element).html();
        $('div.sexy select:first option:[value="' + options.oldValue + '"]', $element).attr('value', options.newValue);
        $('div.sexy select:first option:[value="' + options.newValue + '"]', $element).attr('text', options.newText);
        $('div.sexy ul li:contains(\'' + oldText + '\')', $element).html(options.newText);
        $('div.sexy input:first', $element).val(options.newText);
    },

    //Retornar o item selecionado no sexyCombo
     $.SexySelectedOption = function(selector) {
         var $combo = $(selector);
         var $input = $('.combo input:readonly', $combo);
         var $option = $('select option:contains("' + $input.val() + '")', $combo);
         return {
             Value: $option.attr('value'),
             Text: $option.attr('text'),
             Selected: $option.attr('selected')
         };
     },

    //Retorna os valores selecionados em CheckBoxList,RadioButtonList
    //Return: 'textOption1,textOption2,textOption12'
     $.PrettyCheckBoxSelectedOptions = function(selector) {
         $object = $(selector);
         var items = '';
         $('input:checked', $object).each(function() {
             items += ((items != '') ? ',' : '') + $(this).next().text();
         });
         return items;
     },

    //Selecionar determinados items em um CheckBoxList,RadioButtonList
    //Ex:$.PrettyCheckBoxSelectOptions({ selector: '#element', items: 'textOption 1,textOption 2,textOption 14'});
     $.PrettyCheckBoxSelectOptions = function(options) {
         $object = $(typeof (options) == 'object' ? options.selector : options);
         $items = options.items != undefined ? options.items.split(',') : null;

         $('span:has(input[type=' + (options.type != undefined ? options.type : 'radio') + '])', $object).each(function() {
             var $text = $('label[for]', $(this));
             var text = options.attribute != undefined ? $(this).attr(options.attribute) : $text.text();
             if ($.inArray(text, $items) != -1) {
                 $text.addClass('checked');
                 $('input[id="' + $text.attr('for') + '"]', $object).attr('checked', 'checked');
             } else {
                 $text.removeClass('checked');
                 $('input[id="' + $text.attr('for') + '"]', $object).removeAttr('checked');
             }
         });
     },

    ///Transformar texto em XML
    $.ToXmlDocument = function(string) {
        var browserName = navigator.appName;
        var xmlDocument;
        if (browserName == 'Microsoft Internet Explorer') {
            xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
            xmlDocument.async = 'false'
            xmlDocument.loadXML(string);
        } else {
            xmlDocument = (new DOMParser()).parseFromString(string, 'text/xml');
        }
        return xmlDocument;
    },

    /*Criar flash em determinado elemendo
    Ex:
    --------$.CreateFlash({ Container: '.segurareceita', Local: 'icobuscando' , TimeToRemove:2000 });
    --------$.CreateFlash({ Local: 'icobuscando' });
    */
    $.CreateFlash = function(options) {
        if (options.Container != undefined) {
            var $container = typeof (options.Container) == 'string' ? $(options.Container) : options.Container;
            if ($('div.buscando', $container).size() == 0) {
                $container.append('<div class="buscando"><span class="icobuscando" id="' + options.Local + '"></span><p class="buscando">Buscando, aguarde</p></div>')
            }
            if (options.TimeToRemove != undefined)
                setTimeout(function() { $('div.buscando:last', $container).remove(); }, options.TimeToRemove);

        }

        var params = {};
        params.menu = options.Menu != null ? options.Menu : 'false';
        params.quality = options.Quality != null ? options.Quality : 'high';
        params.scale = options.Scale != null ? options.Scale : 'noscale';
        params.wmode = options.Wmode != null ? options.Wmode : 'transparent';
        params.allowscriptaccess = options.Allowscriptaccess != null ? options.Allowscriptaccess : 'always';
        swfobject.embedSWF(
              (options.Url != null ? options.Url : '/site/images/swf/buscando.swf')
            , (options.Local != undefined ? options.Local : '')
            , (options.Width != undefined ? options.Width : '18')
            , (options.Height != undefined ? options.Height : '18')
            , (options.Versao != null ? options.Versao : '8.0.0'), false, null, params, null);
    },

    $.vIE = function() {
        return (navigator.appName == 'Microsoft Internet Explorer') ? parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]) : -1;
    },

    //Tecla pressionada
    $.KeyPressed = function(e) {
        try { return event.keyCode; } catch (erro) { return e.keyCode; }
    },

    ///Obter o conteudo de um webMethod
    $.ObterWebMethod = function(options) {

        var conteudo;
        $.ajax({
            async: options.Async != null ? options.Async : false,
            type: options.Method != null ? options.Method : 'POST',
            url: options.Url,
            data: options.Parametros,
            contentType: 'application/json; charset=utf-8',
            dataType: options.DataType != null ? options.DataType : 'html',
            cache: options.Cache != null ? options.Cache : false,
            success: function(xml) {
                if (options.onSucess != undefined)
                    options.onSucess(xml);

                if (options.Formato == 'xml')
                    conteudo = $.ToXmlDocument(xml.d);
                else if (options.Formato == 'json')
                    conteudo = xml.d;
                else
                    conteudo = xml;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (window.location.href.indexOf('http://www.') == -1)
                    alert(textStatus + '\n' + XMLHttpRequest.responseText);
            }
        });
        return conteudo;
    },

    ///Replace All
     $.ReplaceAll = function(modelo, de, para) {
         while (modelo.indexOf(de, 0) != -1)
             modelo = modelo.replace(de, para);
         return modelo;
     },

    $.PesquisarTermosToolTip = function(SrvFiltro) {

        replaceInElement = function(element, find, replace) {
            for (var i = element.childNodes.length; i-- > 0; ) {
                var child = element.childNodes[i];
                if (child.nodeType == 1) {
                    var tag = child.nodeName.toLowerCase();
                    if (tag != 'style' && tag != 'script')
                        replaceInElement(child, find, replace);
                } else if (child.nodeType == 3) {
                    replaceInText(child, find, replace);
                }
            }
        };

        replaceInText = function(text, find, replace) {
            var caracPermit = [9, 10, 13, 32, 33, 34, 40, 41, 44, 46, 58, 59, 60, 62, 65, 91, 93, 97, 123, 125, 8220, 8221];
            var match;
            var matches = [];
            while (match = find.exec(text.data))
                matches.push(match);
            for (var i = matches.length; i-- > 0; ) {
                match = matches[i];

                var palavra = text.data.substr(match.index - 1, match[0].length + 2);
                //if(palavra.search('studo')>= 0) alert(palavra.charCodeAt(0) + '|' + palavra);

                if (caracPermit.join().indexOf(palavra.charCodeAt(0)) >= 0 && caracPermit.join().indexOf(palavra.charCodeAt(palavra.length - 1)) >= 0) {
                    text.splitText(match.index);
                    text.nextSibling.splitText(match[0].length);
                    text.parentNode.replaceChild(replace(match), text.nextSibling);
                }
            }
        };


        var ConteudoTermos = $.ObterWebMethod({
            Url: '/site/Controls/Cozinha/CozinhaScriptWebMethods.aspx/PesquisarTermosToolTip',
            Parametros: "{urlPagina:'" + SrvFiltro.UrlPagina + "'}",
            Formato: 'xml',
            DataType: 'json'
        });

        for (var x = 0; x < SrvFiltro.Elements.length; x++) {
            var id = 0;
            var arrayTermos = new Array();
            var elementID = SrvFiltro.Elements[x];

            $('termos > termo', ConteudoTermos).each(function() {
                id++;
                var modelo = '<div class="glossario #ID#" style="width:250px"><div class="bgtop"> </div><div class="superior"><p class="fechar"><a href="javascript:void(0)" onclick="javascript:$(this.parentNode.parentNode.parentNode.parentNode).hide();" title="Fechar">X</a></p></div>'
                modelo += '<div class="meio"><h4 class="titverbete">#TITULO#</h4><p class="textoverbete">#DESCRICAO#</p><p class="saibamais" #CLASS#><a href="#LINK#" title="Saiba mais">[Saiba mais]</a></p></div><div class="inferior"></div></div>';
                modelo = modelo.replace('#TITULO#', $('nome', this).text());
                modelo = modelo.replace('#DESCRICAO#', $('descricao', this).text());
                if ($('link', this).text() != '' && $('link', this).text() != null)
                    modelo = modelo.replace('#LINK#', $('link', this).text());
                else
                    modelo = modelo.replace('#CLASS#', 'style="display:none"');

                modelo = $.ReplaceAll(modelo, '#ID#', 'boxglossario' + elementID + id);

                var find = new RegExp('\\b' + $('nome', this).text() + '\\b', 'gi');
                if ($(elementID).size() > 0 && $(elementID) != undefined) {
                    replaceInElement($(elementID)[0], find, function(match) {
                        var link = document.createElement('a');
                        link.className = 'glossario glossarioitem' + x + id;
                        link.href = 'javascript:void(0)' + match[0] + '.aspx';
                        link.appendChild(document.createTextNode(match[0]));
                        return link;
                    });
                }

                arrayTermos.push(modelo);
            });

            for (var i = 0; i < id; i++) {
                $('.glossarioitem' + x + (i + 1)).simpletip({
                    position: 'bottom',
                    showEffect: 'none',
                    hideEffect: 'none',
                    content: arrayTermos[i]
                });
            }
        }
    },

    ///Carocel
    $.CarocelLoadCallback = function(carousel, state, SrvFiltro) {
        //Numero de items retornados
        SrvFiltro.Url += (SrvFiltro.Url.indexOf('?') != -1) ? '&randon=' + Math.random() + '&first=' + SrvFiltro.Indice + '&last=' + (carousel.last + 1) : '';
        var Documento = $.ObterWebMethod(SrvFiltro);
        var innerHTML = ((SrvFiltro.Formato == 'xml') ? $('innerHTML', Documento).text() : Documento);

        //Adicionar texto ao carocel caso a requisição seja xml ou texto
        if (SrvFiltro.Paginas > carousel.size() || SrvFiltro.Paginas == null)
            carousel.size((parseInt(carousel.first) + 1));
        carousel.add((SrvFiltro.Indice != null) ? SrvFiltro.Indice : (parseInt(carousel.first) + 1), innerHTML);

        if (SrvFiltro.Paginas <= 0)
            $('#' + carousel.container.context.id + ' .paginacao').hide();
        if (SrvFiltro.LoadImages == true) {
            $.preload('#' + carousel.container.context.id + ' img', {//<the first argument is a selector to the images>
                notFound: SrvFiltro.notFound != null ? SrvFiltro.notFound : '/site/Images/notfound_lg.gif',
                threshold: 20 //<'2' is the default, how many at a time, to load.>
            });
        }

        //Retornar Documento requisitado
        return Documento;
    },

    //Gerenciar a paginação
     $.Paginacao = function(Objeto) {
         if (Objeto.Paginas < 1) {
             $(Objeto.jCReceitaID + 'Top').slideUp();
             $(Objeto.jCReceitaID + 'Bottom ').slideUp();
         } else {
             $(Objeto.jCReceitaID + 'Top').slideDown();
             $(Objeto.jCReceitaID + 'Bottom ').slideDown();

             $(Objeto.jCReceitaID + 'Top .paginaAtual').html(Objeto.Pagina);
             $(Objeto.jCReceitaID + 'Bottom .paginaAtual').html(Objeto.Pagina);
             $(Objeto.jCReceitaID + 'Top .totalPaginas').html(Objeto.Paginas);
             $(Objeto.jCReceitaID + 'Bottom .totalPaginas').html(Objeto.Paginas);

             $(Objeto.jCReceitaID + 'Top  .jcarousel-prev-horizontal').attr('class', (Objeto.Pagina <= 1) ? 'jcarousel-prev-horizontal jcarousel-prev-disabled-horizontal' : 'jcarousel-prev-horizontal');
             $(Objeto.jCReceitaID + 'Top  .jcarousel-next-horizontal').attr('class', (Objeto.Pagina >= Objeto.Paginas) ? 'jcarousel-next-horizontal jcarousel-next-disabled-horizontal' : 'jcarousel-next-horizontal');
             $(Objeto.jCReceitaID + 'Bottom  .jcarousel-prev-horizontal').attr('class', (Objeto.Pagina <= 1) ? 'jcarousel-prev-horizontal jcarousel-prev-disabled-horizontal' : 'jcarousel-prev-horizontal');
             $(Objeto.jCReceitaID + 'Bottom  .jcarousel-next-horizontal').attr('class', (Objeto.Pagina >= Objeto.Paginas) ? 'jcarousel-next-horizontal jcarousel-next-disabled-horizontal' : 'jcarousel-next-horizontal');
         }

     }

    $.CriarLinksPaginacao = function(options) {
        var settings = {
            $container: $(options.container),
            pagina: options.pagina,
            paginas: options.paginas,
            paginasView: options.paginasView,
            separacao: options.separacao != undefined ? options.separacao : ' | '
        };

        var links_laterais = parseInt(options.paginasView / 2);
        var inicio = settings.pagina - links_laterais;
        var limite = settings.pagina + links_laterais; limite = inicio < 1 ? (limite + (1 - inicio)) : limite;
        var display = '';

        for (var i = inicio; i < limite; i++) {
            if (i == settings.pagina)
                display += '<span class="paginaAtual"> ' + i + '</span>';
            else if (i >= 1 && i <= settings.paginas)
                display += '<a href="javascript:void(0)" class="link-paginacao">' + i + '</a>';

            if (display != '' && (i >= 1 && i < settings.paginas) && i < (limite - 1))
                display += settings.separacao;
        }

        settings.$container.html(display);
        if (options.onClick != undefined) {
            $('a.link-paginacao', settings.$container).click(function() {
                options.onClick($(this).text());
            });
        }
    }


})(jQuery);