var PAGE;
var PATH;
var PATH_SITE;
var _BROWSER;
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function error(msg, url, line) {
    //return true;
    //alert("ATENÇAO: Erro na página \n\n"	+	"Error:	" + msg + "\n"	+	"URL:	" + url + "\n"	+	"Line:	" + line);
}
window.onerror = error;
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GRUPO DE FUNÇOES BÁSICAS #####################################################################################
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
var _status_back;
function loadMenu() {
    $("#MENU").children("li").hover(
		function(e) {
		    //$(this).find("a:eq(0)").css({'backgroundColor':'fff'});
		    clearInterval(_status_back);
		    $("#MENU").find('.opened').find("a:eq(0)").removeClass("hover");
		    $(this).parent().find("ul").hide();
		    $(this).find("a:eq(0)").addClass("hover");
		    $(this).find("ul:eq(0)").show();
		},
		function(e) {
		    $(this).find("a:eq(0)").removeClass("hover");
		    _status_back = window.setTimeout(backMenuDefault, 100);
		}
	);
    $("#MENU").find("a").each(function(i) {/*
		$(this).parent().hover(
			function(e){
				$(this).parent().find(".block").find("a:eq(0)").removeClass('selected');
				$(this).parent().find(".block").find("ul:eq(0)").hide();
				$(this).find("ul:eq(0)").show();
			},					
			function(e){
				$(this).find("ul:eq(0)").hide();
			}
		);*/
    });
    $("#MENU").find("ul:eq(0)").hover(
		function(e) {
		},
		function(e) {
		    $(this).parent().find(".block").find("a:eq(0)").addClass('selected');
		    $(this).parent().find(".block").find("ul:eq(0)").show();
		}
	);
    backMenuDefault();
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function backMenuDefault() {
    $("#MENU").find("ul").hide();
    $("#MENU").find('.opened').find('ul').show(0);
    $("#MENU").find('.opened').find("a:eq(0)").addClass("hover");
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
confirmacao = function(mensagem, func, btAction, btCancel) {
    removeObj('ALERT');
    if (!btAction) btAction = "Sim";
    if (!btCancel) btCancel = "Não";
    var newElement = document.createElement('div');
    newElement.setAttribute('id', 'ALERT');
    newElement.func = func;
    //document.body.scrollHeight > document.body.offsetHeight
    var str = "<div class=\"alert_back\" style=\"margin-top:0px; display:block; padding-top:0px;\"></div>";
    str += "<div class=\"alert_content\" style=\"margin-top:" + (getScrollHeight() - 530) + "px;\">";
    str += "<div class=\"msg\">" + mensagem + "</div>";
    str += "<div class=\"opt\">";
    str += "<button class=\"button sim\" onclick=\"document.getElementById('ALERT').func(); removeObj('ALERT');\">" + btAction + "</button>";
    str += "<button class=\"button nao\" onclick=\"removeObj('ALERT');\">" + btCancel + "</button>";
    str += "</div>";
    str += "</div>";

    newElement.innerHTML = str;
    newElement.className = 'ALERT';
    document.body.appendChild(newElement);
    $(".alert_back").stop().css({ opacity: 0, display: "block" }).animate({ opacity: 0.3 }, { duration: 290, easing: "easeOutExpo", complete: function(p) { } });
    $(".alert_content").stop().css({ opacity: 0, display: "block" }).animate({ opacity: 1, "marginTop": (getScrollHeight() - 130) + "px" }, { duration: 490, easing: "easeOutExpo", complete: function(p) { } });
}
// LIMPAR INPUTS //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getScrollHeight() {
    var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;
    return h ? h : 0;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
var status_menu;
var status_menu_out;
var ref_menu;
var time_menu = 150;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function menu_front(obj) {
    $(obj).find('li').hover(
		function() {
		    ref_menu = $(this);
		    status_menu = window.setTimeout(teste2, time_menu);
		},
		function() {
		    clearTimeout(status_menu);
		    $(this).find('ul:eq(0)').hide();
		    $(this).find('.menu_img_txt:eq(0)').show();
		    $(this).find('.hover:eq(0)').hide();
		    //$(this).find('.descricao:eq(0)').hide();
		    $(this).find('a:eq(0)').removeClass('listaIntHover');
		    status_menu_out = window.setTimeout(function() { time_menu = 150; }, 200);
		}
	);
    $("#MENU").find("ul").find("li").hover(
			function(e) {
			    $(this).find('.descricao:eq(0)').show();
			},
			function(e) {
			    $(this).find('.descricao:eq(0)').hide();
			}
	);
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////

// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function loadBox(_pag, _dados, _box, _top, _form, _method, _createHistoryPoint, _loadIcon, _createBookmark, _pos) {

    _box = (typeof (_box) != "object") ? $(_box) : _box;

    if (_top) window.scrollBy(0, 0);
    if (!_method) _method = "POST";
    if (_createHistoryPoint == undefined) createHistoryPoint = true;
    if (!_dados) _dados = "";
    if (_createHistoryPoint != "back" && _form) _dados = $(_form).serialize();
    if (_loadIcon) _box.html("<div class='loading' style=' width:99%; height:10px; margin-top:25px; text-align:center; padding-top:" + _pos + "px;'><img src=\"" + PATH + "img/base/ajax-loader.gif\" class=\"loadIcon\"><div style=\"display:none\">" + $(_box).html() + "</div></div>");
    try {
        pageB = _pag.split(".php");
        pageB = pageB[0];
    } catch (e) { }

    $.ajax({
        type: _method,
        url: _pag,
        global: false,
        data: _dados,
        dataType: "html",
        error: function(xhr, ajaxOptions, thrownError) {
            _box.html("ERROR:" + xhr.status + "<br />" + thrownError);
        },
        success: function(content) {
            if (_box.length < 1) {
                try {
                    _boxb = _box.attr('id');
                } catch (e) { }
                var d = document; //alert_back
                var box = $('<div></div>').appendTo(document.body).attr('id', _boxb);
                box.addClass('_box');
                box.hide();
                var box_closer = $('<div></div>').appendTo(document.body).attr('id', _boxb + '_closer');
                box_closer.html('<span>X</span>');
                box_closer.addClass('_box_closer');
                box_closer.hide();

                var box_back = $('<div></div>').appendTo(document.body).attr('id', _boxb + '_back');
                box_back.addClass('alert_back');
                box_back.hide();
            }
            $(_box).html(content);
            unblockInputs();
            $(_box + '_back').stop().css({ opacity: 0, display: "block" }).animate({ opacity: 0.3 }, { duration: 290, easing: "easeOutExpo", complete: function(p) { } });
            $(_box).show(700);
            $(_box + '_closer').show(700);
            $(_box + '_closer').find('span').bind('mouseup', function(e) {
                $(_box).hide(300); $(this).parent().hide(300);
                $(_box + '_back').stop().animate({ opacity: 0 }, { duration: 150, easing: "easeOutExpo", complete: function(p) { $(this).hide(); } });
            });
        }
    });
    if (_createHistoryPoint == "back") createHistoryPoint = false;
    _dadosB = _dados.replace("=", "@#K@");
    if (_createHistoryPoint != false) createPointHistory(_pag, _dadosB, _box, _top, _form, _method, _createHistoryPoint, _loadIcon, _createBookmark, _pos);
    //if(navigator.appName == "Microsoft Internet Explorer" &&  _createBookmark != false) window.location.hash = "/" + pageB + "/" + _box  + "/" + _dados ;
    if (_createBookmark == true) {
        box = _box.attr("id");
        window.location.hash = "/" + pageB + "/" + box + "/" + _dados;
    }
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function loadPage(_pag, _dados, _box, _top, _form, _method, _createHistoryPoint, _loadIcon, _createBookmark, _pos) {

    _box = (typeof (_box) != "object") ? $(_box) : _box;

    if (_top) window.scrollBy(0, 0);
    if (!_method) _method = "POST";
    if (_createHistoryPoint == undefined) createHistoryPoint = true;
    if (!_dados) _dados = "";
    if (_createHistoryPoint != "back" && _form) _dados = $(_form).serialize();
    if (_loadIcon) _box.html("<div class='loading' style=' width:99%; height:10px; margin-top:25px; text-align:center; padding-top:" + _pos + "px;'><img src=\"" + PATH + "img/base/ajax-loader.gif\" class=\"loadIcon\"><div style=\"display:none\">" + $(_box).html() + "</div></div>");
    try {
        pageB = _pag.split(".php");
        pageB = pageB[0];
    } catch (e) { }

    $.ajax({
        type: _method,
        url: _pag,
        global: false,
        data: _dados,
        dataType: "html",
        success: function(content) {
            _box.html(content);
            unblockInputs();
        },
        error: function(xhr, ajaxOptions, thrownError) {
            _box.html("ERROR:" + xhr.status + "<br />" + thrownError);
        }
    });
    if (_createHistoryPoint == "back") createHistoryPoint = false;
    _dadosB = _dados.replace("=", "@#K@");
    if (_createHistoryPoint != false) createPointHistory(_pag, _dadosB, _box, _top, _form, _method, _createHistoryPoint, _loadIcon, _createBookmark, _pos);
    if (_createBookmark == true) {
        box = _box.attr("id");
        window.location.hash = "/" + pageB + "/" + box + "/" + _dados;
    }
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function unblockInputs() {
    $('body').find('input, textarea').bind('focus', function(e) { status_block = false; });
    $('body').find('input, textarea').bind('blur', function(e) { status_block = true; });
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function trim(str) { return str.replace(/^\s+|\s+$/g, ""); }
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function urlencode(str) {
    str = str.replace('‘', "%27");
    str = str.replace('’', "%27");
    str = str.replace('“', '"');
    str = str.replace('”', '"');
    str = str.replace('–', '-');
    str = escape(str);
    str = str.replace('+', '%2B');
    str = str.replace('+', '%2B');
    str = str.replace('\'', '%27');
    str = str.replace('%20', '+');
    str = str.replace('*', '%2A');
    str = str.replace('/', '%2F');
    str = str.replace('@', '%40');
    return str;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function urldecode(str) {
    str = str.replace('+', ' ');
    str = unescape(str);
    return str;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                   1obr 2obr   3obr    4opc	 5opc	6opc   7opc   	8opc
function attachFlash(url, width, height, target, wmode, scale, quality, vars) {
    var content; identity = url.split("."); identity = identity[0]; identity = identity.split("/"); identity = identity[identity.length - 1];
    if (!target) { document.write("<div id=\"id_" + identity + "\"></div>"); target = "id_" + identity; }
    if (!quality) quality = "best";
    target = document.getElementById(target);
    content = "<object id=\"" + identity + "\" width=\"" + width + "\" height=\"" + height + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\">";
    content += "<param name=\"allowScriptAccess\" value=\"sameDomain\" />";
    content += "<param name=\"movie\" 		value=\"" + url + "?" + vars + "\">";
    content += "<param name=\"quality\"	value=\"" + quality + "\">";
    content += "<param name=\"wmode\" 		value=\"" + wmode + "\" /> ";
    content += "<param name=\"bgcolor\" 	value=\"#f0f0f0\" /> ";
    content += "<embed name=\"" + identity + "\" src=\"" + url + "?" + vars + "\"  width=\"" + width + "\" height=\"" + height + "\" wmode=\"" + wmode + "\" scale=\"" + scale + "\" quality=\"" + quality + "\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\"></embed>";
    content += "</object>";
    target.innerHTML = content;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createPointHistory(_pag, _dados, _box, _top, _form, _method, _createHistoryPoint, _loadIcon, _createBookmark, _pos) {
    createHistory = true;
    if (!document.getElementById('targetFrames')) createIframe("iframeSystem", "about:blank");
    var iframeSystem = document.getElementById("iframeSystem");
    if (iframeSystem.contentWindow) iframeSystem = iframeSystem.contentWindow;  // For IE5.5 and IE6
    else if (iframeSystem.window) iframeSystem = iframeSystem.window; 		// For IE5

    if (!iframeSystem) return false;
    //$('#historia').append('<br> Pontos Históricos: '+ _pag + '&_dados=' + _dados + '&_box=' + _box + '&_top=' + _top + '&_form=' + _form + '&_method=' + _method+ '&_createHistoryPoint=' + _createHistoryPoint+ '&_loadIcon=' + _loadIcon+ '&_createBookmark=' + _createBookmark+ '&_pos=' + _pos );
    iframeSystem.location = '_pageHistory.htm?_pag=' + _pag + '&_dados=' + _dados + '&_box=' + _box + '&_top=' + _top + '&_form=' + _form + '&_method=' + _method + '&_createHistoryPoint=' + _createHistoryPoint + '&_loadIcon=' + _loadIcon + '&_createBookmark=' + _createBookmark + '&_pos=' + _pos;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createIframe(name, src) {
    if (!document.getElementById(name)) {
        var newElement = document.createElement('div');
        newElement.setAttribute('id', 'targetFrames');
        newElement.setAttribute('name', 'targetFrames');
        document.body.appendChild(newElement);
        document.getElementById('targetFrames').innerHTML += "<center><iframe name=\"" + name + "\" id=\"" + name + "\" width=\"0\" height=\"0\" frameborder=\"0\" style=\"display:none;\" border=\"0\" frameborder=\"0\" src=\"" + src + "\"></iframe></center>";
    }
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function openLightBox(target) {
    target.show();
    //	alert(document.body.scrollTop);
    sc = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    target.css({ 'marginTop': '0px', 'top': (sc + 100) + "px" });
    target.find('.close:eq(0)').bind('mouseup', function() {
        $(this).parent().fadeOut(200);
        $('.lightbox_back').fadeOut(200);
    });
    $('.lightbox_back').css({ 'opacity': '.84', 'height': $(document).height() + "px" });
    $('.lightbox_back').fadeIn(200);
    $('.lightbox_back').bind('mouseup', function() {
        target.find('.close:eq(0)').mouseup();
    });
    $('.lightbox_back').onScroll = function(n) {
        //alert(111);
        sc = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
        target.css({ 'marginTop': '0px', 'top': (sc + 100) + "px" });
    }
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
function showHide(bt, target) {
    bt.bind('mouseup', function() {
        if (target.is(':visible')) target.hide();
        else target.show();
    });
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function removeObj(obj) {
    $(".alert_back").stop().animate({ opacity: 0 }, { duration: 150, easing: "easeInOutCubic", complete: function(p) { } });
    $(".alert_content").stop().animate({ opacity: 0, "marginTop": (getScrollHeight() + 190) + "px" }, { duration: 200, easing: "easeOutCubic", complete: function(p) { obj = document.getElementById(obj); if (obj) document.body.removeChild(obj); } });
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function browserDetection(type) {
    switch (type) {
        case "codename":
            return navigator.appCodeName;
            break;
        case "name":
            return navigator.appName;
            break;
        case "version":
            return navigator.appVersion;
            break;
        case "cookie":
            return navigator.cookieEnabled;
            break;
        case "plataform":
            return navigator.platform;
            break;
        case "agent":
            return navigator.userAgent;
            break;
        default:
            return navigator.userAgent;
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function checkBrowser(name, version) {
    __browser = browserDetection("name");
    __version = browserDetection("version");
    if (name == "ie" || name == "internet explorer" || name == "explorer") {
        if (__browser.indexOf("Internet Explorer") >= 1) {
            if (version == 8 && __version.indexOf("MSIE 8") >= 1) return true;
            else if (version == 7 && __version.indexOf("MSIE 7") >= 1) return true;
            else if (version == 6 && __version.indexOf("MSIE 6") >= 1) return true;
            else return false;
        } else return false;
    }
    else if (name == "firefox") {
        if (__browser.indexOf("firefox") >= 1) {
            return true;
        } else return false;
    }
    else if (name == "chrome") {
        if (__browser.indexOf("chrome") >= 1) {
            return true;
        } else return false;
    }
    else if (name == "safari") {
        if (__browser.indexOf("safari") >= 1) {
            return true;
        } else return false;
    }
    return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Brazilian initialisation for the jQuery UI date picker plugin. */
/* Written by Leonildo Costa Silva (leocsilva@gmail.com). */
jQuery(function($) {
    $.datepicker.regional['pt-BR'] = {
        closeText: 'Fechar',
        prevText: '&#x3c;&#x3c;',
        nextText: '&#x3e;&#x3e;',
        currentText: 'Hoje',
        monthNames: ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho',
		'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun',
		'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
        dayNames: ['Domingo', 'Segunda-feira', 'Ter&ccedil;a-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sabado'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        dayNamesMin: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 0,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['pt-BR']);
});

jQuery.fn.stripTags = function() { return this.replaceWith(this.html().replace(/<\/?[^>]+>/gi, '')); };
var Url = {
    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },
    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },
    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};

/*

SELFCOMPLETER

*/

(function($) {

    $.selfcompleter = function(element, options) {
        var config = this.settings = this.extend({}, this.defaults(), options);

        this.$inputtext = $(element);

        this.settings.successbackup = this.settings.request.success;
        this.settings.request.success = this.settings.successcallback;

        this.setup();
    };

    var $sc = $.selfcompleter;

    $sc.fn = $sc.prototype = {
        selfcompleter: '0.0.0'

    };

    $sc.fn.extend = $sc.extend = $.extend;

    $sc.fn.extend({
        searchstring: "",
        defaults: function() {
            var self = this;
            return {
                arrayname: "items",
                minlength: 3,
                maxlength: 10,
                ajax: true,
                $inputtext: {},
                dataobject: {},
                request: {},
                searchpattern: function(string, text) {
                    if (text.toString().toLowerCase().indexOf(string.toString().toLowerCase()) > -1) {
                        return true;
                    }
                },
                successcallback: function(data, status, xhr) {
                    var i = 0;
                    var returndata = [];
                    var dataarray = data[self.settings.arrayname];
                    if ($.isFunction(self.settings.successbackup)) {
                        self.settings.successbackup.apply($("body"), [data, status, xhr]);
                    }
                    for (i = 0; i < dataarray.length; i++) {
                        returndata.push(dataarray[i]);
                    }
                    if (self.searchstring.length == self.settings.minlength) {
                        self.$combo.data("busca", self.searchstring);
                        self.$combo.data("dados", returndata);
                    }
                    self.showcombo(returndata, self.searchstring);
                },
                comboheight: 300,
                requestcallback: function(request) {
                    return self.settings.request;
                }
            }
        },
        filterdata: function(dataarray, string) {
            var i = 0;
            var filtereddata = [];
            for (i = 0; i < dataarray.length; i++) {
                if (dataarray[i].text.toLowerCase().indexOf(string.toLowerCase()) > -1) {
                    filtereddata.push(dataarray[i]);
                }
            }
            return filtereddata;
        },
        setup: function() {
            var self = this;

            this.$inputtext.bind("keyup", function(event) {
                var $this = $(this);

                if (event.keyCode == '40') {
                    $selected = $("#complete-result").find(".selected");
                    if ($selected.length <= 0) {
                        $("#complete-result").find("a:first").addClass("selected");
                    } else {
                        $a = $("#complete-result").find("a");

                        i = $a.index($selected);

                        $("#complete-result").find(".selected").removeClass("selected");

                        if (i == ($a.length - 1)) {
                            $("#complete-result").find("a:first").addClass("selected");
                        } else {
                            $("#complete-result").find("a:eq(" + (i + 1) + ")").addClass("selected");
                        }
                    }

                    return false;
                } else if (event.keyCode == '38') {
                    $selected = $("#complete-result").find(".selected");
                    if ($selected.length <= 0) {
                        $("#complete-result").find("a:last").addClass("selected");
                    } else {
                        $a = $("#complete-result").find("a");

                        i = $a.index($selected);

                        $("#complete-result").find(".selected").removeClass("selected");

                        if (i == 0) {
                            $("#complete-result").find("a:last").addClass("selected");
                        } else {
                            $("#complete-result").find("a:eq(" + (i - 1) + ")").addClass("selected");
                        }
                    }

                    return false;
                } else if (event.keyCode == '13') {
                    $selected = $("#complete-result").find(".selected");

                    if ($selected.length == 1) {
                        $selected.click();
                        this.$inputtext.blur();
                    }

                    return false;
                }

                if ($this.val().toString().length >= self.settings.minlength) {
                    self.searchstring = $this.val();
                    if (self.searchstring.indexOf(self.$combo.data("busca")) == 0 && self.searchstring != "" && self.searchstring.length >= self.settings.minglength) {
                        self.showcombo(self.filterdata(self.$combo.data("dados"), self.searchstring), self.searchstring);
                    }
                    else if (self.settings.ajax) {
                        var request = {};
                        self.settings.request.success = self.settings.successcallback;
                        request = self.settings.requestcallback(self.settings.request, self.searchstring);
                        if (request !== null) {
                            $.ajax(request);
                        }
                    }
                    else {
                        self.showcombo(dataobject, self.searchstring);
                    }
                }
                else {
                    self.removecombo();
                }
            });
            this.$inputtext.bind("focusin", function(event) {
                $(this).keyup();
            });
            this.$inputtext.bind("focusout", function(event) {
                window.setTimeout(function() { $("#complete-result").hide(300) }, 500);
            });


            this.setupcombo();
        },
        search: function(string, data, searchpattern) {
            var i = 0;
            var returndata = [];
            var dataarray = data[self.settings.arrayname];
            if (string !== "") {
                for (i = 0; i < dataarray.length; i++) {
                    if (searchpattern(string, dataarray[i].text)) {
                        returndata.push(dataarray[i].text);
                    }
                }
            }
            return returndata;
        },
        setupcombo: function() {
            var $combo = this.$combo = $("ul#complete-result");
            var $inputText = this.$inputtext;
            var self = this;
            $combo.height(this.settings.comboheight);

//            $combo.delegate("li", "click", function(event) {
//                var $this = $(this);
//                classe = $this.attr("class").split("_");
//                grupoID = classe[0];
//                grupoNOME = classe[1];
//                if (window.groupid === undefined) {
//                    loadGrupo($this.children("a").attr("href"), grupoID, grupoNOME);
//                }
//                else {
//                    ordenar($("div#filtros>div#set-filtros>form#filtros-form>ul>li"), $inputText.val(), /^(.*)\s\(.*\)/.exec($(this).text())[1])
//                }
//                $("#resultado").fadeOut(300);
//                $("#filtros").fadeIn(400);
//                $("#box-busca").css("backgroundImage", "url(" + window["imagens compare e escolha"].adicione + ")");
//                return false;
//            });
            $inputText.after($combo);
        },
        showcombo: function(data, searchstring) {
            var i = 0;
            this.clearcombo();
            for (i = 0; i < data.length; i++) {
                if (window.groupid === undefined || window.groupid == data[i].oid) {
                    name = searchstring == undefined ? data[i].text : $.hilitestring(data[i].text, searchstring);
                    link = "<a href=\"" + webPath + "Util/EscolhaAlimento/" + data[i].id + "\">" + name + " (" + data[i].otext + ")</a>";
                    this.$combo.append("<li class='" + data[i].oid + "_" + data[i].otext + "'>" + link + "</li>");
                    var $last = this.$combo.children("li:last-child");
                }
            }
            if (this.$combo.children().length > 0) {
                this.$combo.show();
            }
            $("#complete-result").find("a").mouseover(function() {
                $("#complete-result").find(".selected").removeClass("selected");
                $(this).addClass("selected");
            });
            return this.$combo;
        },
        hidecombo: function() {
            this.$combo.hide();
        },
        removecombo: function() {
            this.$combo.hide();
            this.$combo.children().remove();
        },
        clearcombo: function() {
            this.$combo.children().remove();
        }
    });

    $.fn.selfcompleter = function(settings, argument1, argument2) {
        var returnObject = null;
        if (typeof settings == 'string') {
            for (var i = 0; i < $(this).length; i++) {
                var $this = $(this).eq(i);
                var sc = $this.data('selfcompleter');
                if (sc) {
                    var property = sc[settings];
                    if ($.isFunction(property)) {
                        returnObject = property.apply(sc, [argument1, argument2]);
                    }
                    else if (typeof argument1 == "undefined") {
                        return property;
                    }
                    else {
                        return property = argument1;
                    }
                }
            }
            return returnObject == null ? this : returnObject;
        }
        else {
            return $(this).each(function(i, e) {
                var $this = $(this);
                $this.data("selfcompleter", new $sc($this, settings));
            });
        }
    };

})(jQuery);

(function($) {
    $.hilitestring = function(text, string, tag) {
        var otag = "", ctag = "";
        var i = 0;
        if (tag === undefined) { tag = "strong"; }
        otag = ctag = tag;
        otag = "<" + otag + ">";
        ctag = "</" + ctag + ">";
        for (i = 0; i < text.length; i++) {
            if (text.toString().substr(i, string.toString().length) == string) {
                text = text.toString().substr(0, i) + otag + text.toString().substr(i, string.toString().length) + ctag + text.toString().substr(i + string.toString().length);
                i = i + string.toString().length + otag.length + ctag.length;
            }
        }
        return text;
    };
})(jQuery);


function loadGrupo(url, id, grupo) {
    exibirLoading();
    $.ajax({
        url: url,
        cache: false,
        success: function(data, status, xhr)
        {
            var text = "Busque por " + grupo + " que queira filtrar";
            var $lista = $("form#filtros-form>ul>li");
            /*
            $("#ferramenta").find(".categoria-thumb").css({
            'background': 'url(' + webPath + 'Content/images/compare/categorias/' + id + '.jpg) no-repeat top left'
            }).html('<span>' + grupo + '</span>');
            */
            /*placeholders[$("#Busca").val(text).index()] = text;*/
            $("#Busca").hide();
            $("#Busca1").show();
            $("#Busca1").val('');
            $("#Busca1").attr("placeholder", text);
            //$("#set-filtros").find('ul').html(data);
            $("#container_grupos_alimentares").html(data);
            $("#check-all").attr("checked", false);
            $("#escolha, #resultado").fadeOut(300);
            window.groupid = id;
            $("#filtros").fadeIn(400);
            $("#box-busca").css("backgroundImage", "url(" + window["imagens compare e escolha"].adicione + ")");
            $("#complete-result").hide(200);
            ordenarEmOrdemAlfabetica($lista, $lista.parent());
        },
        error: function(a, b, c)
        {
            //alert(b.status);
        },
        complete: function(xhr, status)
        {
            removerLoading();
        }
    });
    return;
}

function filtrarListaPeloGrupo($lista, groupid) {
    var $notin = $lista.filter(":not([class^=" + groupid + "])");
    $notin.remove();
}

function exibirLoading() {
    var $div = $("div#ferramenta");
    var $header = $("div#box-busca");
    var $modal = $("<div>");
    var $img = $("<img>");
    $div.append($modal).append($img);
    $modal.addClass("modal").addClass("loading");
    $img.addClass("modal").addClass("loading");
    $img.attr("src", webPath + "Content/images/" + "loading.gif");
    $modal.css({
        "position": "absolute",
        "zIndex": "500",
        "backgroundColor": "#FFFFFF",
        "opacity": "0.5",
        "top": "0",
        "left": "0",
        "width": "100%",
        "height": "100%"
    });
    $img.css({
        "width": "100px",
        "height": "100px"
    });
    $img.css({
        "position": "absolute",
        "zIndex": "750"
    });
    $img.css({
        "top": (($div.height() + $header.height()) / 2 - ($img.height() / 2)) + "px",
        "left": (($div.width() / 2) - ($img.width() / 2)) + "px"
    })
}

function removerLoading() {
    var $div = $("div#ferramenta");
    $div.children("div.modal.loading").remove();
    $div.children("img.modal.loading").remove();
}

function ordenar($lista, pesquisa, resultado)
{
	var $parents = $lista.parent();

	$parents.each(function(i, $parent)
	{
		$parent = $($parent);
		var $selecionados = $parent.children("li:has(:checked)");
		var $outros = $parent.children(":not(li:has(:checked))");
		var $ordenados = ordenarEmOrdemAlfabetica($outros, $parent);
		var i, j, t;

		pesquisa = trim(pesquisa.toString().toLowerCase());
		resultado = trim(resultado.toString().toLowerCase());

		//$parent.append($ordenados);

		/*******************
		** ORGANIZAR POR:
		** 1 - Selecionados
		** 2 - Clicado
		** 3 - Pesquisados
		** 4 - Ordenados
		*******************/

		$.each($ordenados, function(i, item)
		{
			if ($(item).text().toString().toLowerCase().indexOf(pesquisa) > -1)
			{
				$parent.prepend($(item));
			}
		});

		$.each($ordenados, function(i, item)
		{
			if ($(item).text().toString().toLowerCase().indexOf(resultado) > -1)
			{
				$parent.prepend($(item));
			}
		});

		$parent.prepend($selecionados);

		$parent.children().removeClass("bg-line");

		$.each($parent.children(), function(i, item)
		{
			if ((i % 4) / 4 >= 0.5)
			{
				$(item).addClass("bg-line");
			}
		});
	});
}

function ordenarEmOrdemAlfabetica(lista)
{
	lista = $.makeArray(lista);

	lista = lista.sort(function(a, b)
	{
		if ($(a).text().toLowerCase() < $(b).text().toLowerCase())
		{
			return -1;
		}
		else
		{
			return 1;
		}
	});

	return lista;
}

(function($) {
    // plugin definition
    $.fn.tabs = function(optionSent) {
        // build main options before element iteration
        var opts = $.extend({}, $.fn.tabs.defaults, optionSent);



        return this.each(function() {
            $this = $(this);
            // build element specific options
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;


            $this.find(".tab").bind("mouseup", function(e) {
                if ($(this).attr("class").indexOf("tab-on") != -1) return false;

                $parentUp = $(this).parents("div.tabs");
                index = $parentUp.find(".tab").index($(this));

                $parentUp.find(".tab-on").removeClass("tab-on");
                $parentUp.find(".tab:eq(" + index + ")").addClass("tab-on");

                $parentUp.find(".tab-content").hide();
                $parentUp.find(".tab-content:eq(" + index + ")").show();
            });
            $this.find(".tab:eq(" + o.startTab + ")").mouseup();
        });
    };

    // plugin defaults
    $.fn.tabs.defaults = {
        startTab: 0
    };
})(jQuery);

//copy this
(function($) {
    // plugin definition
    $.fn.lightBox = function(optionSent) {
        // build main options before element iteration
        var opts = $.extend({}, $.fn.lightBox.defaults, optionSent);

        return this.each(function() {
            $this = $(this);
            // build element specific options
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            $this.click(function() { return false; });

            $this.bind("mouseup", function(e) {
                if ($("#light-mask").length == 0) {
                    //create mask
                    $div = $(document.createElement('div'));
                    $div.attr("id", "light-mask");
                    $("body").prepend($div);
                }

                refId = $(this).attr("href");

                showMask(o.opacityValue, o.animDuration);
                $('#' + refId).show(o.fadeDuration); //show content
                if (o.swf) {
                    var $content = $('#' + refId);
                    $content.find("object, embed").attr("width", $(window).width());
                    $content.find("object, embed").attr("height", $(window).height() - $("div#home-video a.lightbox-close").outerHeight(true));
                    $content.css({
                        "position": "absolute",
                        "top": "0px",
                        "left": "0px",
                        "margin": "0px"
                    });
                    $(window).bind("resize", function(event) {
                        $content.find("object, embed").attr("width", $(window).width());
                        $content.find("object, embed").attr("height", $(window).height() - $("div#home-video a.lightbox-close").outerHeight(true));
                    });
                }
                $('#' + refId).find('.' + o.closeClass).bind("mouseup", function() {
                    $('#' + refId).hide(o.closeDuration);
                    hideMask(o.closeDuration);
                });

                if (!o.modal) {
                    $("#light-mask").bind("mouseup", function() {
                        $('#' + refId).hide(o.closeDuration);
                        hideMask(o.closeDuration);
                    });
                } else
                    $("#light-mask").unbind("mouseup");
            });
        });

        function showMask(op, du) {
            $('#light-mask').css({
                display: "block",
                height: $(document).height() + 'px'
            }).stop().animate(
				{ opacity: op },
				{ duration: du }
			);
        }

        function hideMask(du) {
            $('#light-mask').stop().animate(
				{ opacity: 0 },
				{ duration: du, complete: function(p) { $(this).hide(); }
				});
        }
    };

    // plugin defaults
    $.fn.lightBox.defaults = {
        fadeDuration: 200,
        animDuration: 350,
        closeDuration: 200,
        opacityValue: 0.6,
        swf: false,
        closeClass: 'lightbox-close',
        modal: false
    };
})(jQuery);         // end of plugin


// ************************* Slider Horizontal *********************
(function($) {
    // plugin definition  
    $.fn.sliderHorizontal = function(optionSent) {
        // build main options before element iteration  
        var opts = $.extend({}, $.fn.sliderHorizontal.defaults, optionSent);
        window["slider horizontal index"] = opts.index;
        return this.each(function() {
            slideRunning = false;
            $this = $(this);

            var indice_ativo = 0;

            $this.find(".toSlide:first").addClass("slideAct");
            // build element specific options  
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            // update element styles

            /*if ($('.nav-proj').length > 0) {
            $('.nav-proj').find('li').live("mouseup", function(e) {
            if (!$(this).find('a').hasClass('active')) {
            if ($(this).index() == 0) {
            $this.find(".sliderSeta:first").mouseup();
            }
            if ($(this).index() == 1) {
            $this.find(".sliderSeta:last").mouseup();
            }
            }
            });
            }*/
            if ($('.nav-prof,.nav-proj').length > 0) {
                $('.nav-prof,.nav-proj').find('li').bind("mouseup", function(e) {
                    if (!$(this).find('a').hasClass('active')) {
                        //alert("atual:" + indice_ativo + ' vai para: ' + $(this).index());
                        if ($(this).index() == 0) {
                            if (indice_ativo == 1) {
                                $this.find(".sliderSeta:first").mouseup();
                            } else if (indice_ativo == 2) {
                                $this.find(".sliderSeta:last").mouseup();
                            }
                        }
                        if ($(this).index() == 1) {
                            if (indice_ativo == 0) {
                                $this.find(".sliderSeta:last").mouseup();
                            } else if (indice_ativo == 2) {
                                $this.find(".sliderSeta:first").mouseup();
                            }
                        }
                        if ($(this).index() == 2) {
                            if (indice_ativo == 1) {
                                $this.find(".sliderSeta:last").mouseup();
                            } else if (indice_ativo == 0) {
                                $this.find(".sliderSeta:first").mouseup();
                            }
                        }
                    }
                });
            }

            /*if (o.index == 1) {
            $this.find(".slider").append($this.find(".toSlide:first"));
            $this.find(".slider").css("margin-left", "0");
            $this.find(".slideAct").removeClass("slideAct");
            $this.find(".toSlide:first").addClass("slideAct");
            slideRunning = false; //set animation state: stopped
            $('.nav-proj').find('li').find("a.active").removeClass("active");
            $('.nav-proj').find('li').eq(o.index).find("a").addClass("active")
            }*/

            $this.find(".sliderSeta").bind("mouseup", function(e) {
                if (slideRunning) return; //skip if animation is running  
                slideRunning = true; //set animation state: running
                $parent = $this;

                wid = $parent.find(".toSlide:first").width();
                //ind = $parent.parent().find(".sliderShow").find(".sliderSeta").index($(this));

                if ($(".slider").find(".leia-mais-fechar:visible").length > 0) {
                    $(".slider").find(".leia-mais-fechar:visible").each(function() {
                        $(this).mouseup();
                    });
                }
                    
                ind = $(this).index();
                sld = $parent.find(".sliderShow").find(".toSlide").index($parent.find(".slideAct"));
                qtd = $parent.find(".toSlide").length;

                if (ind == 0) {//go left  
                    margin = 0;
                    $parent.find(".slider").prepend($parent.find(".toSlide:last"));
                    $parent.find(".slider").css("margin-left", (-wid) + "px");
                    if (indice_ativo == 0) indice_ativo = ($parent.find(".toSlide").length - 1);
                    else indice_ativo--;
                } else {//go right
                    margin = (sld) * wid;
                    if (indice_ativo == ($parent.find(".toSlide").length - 1)) indice_ativo = 0;
                    else indice_ativo++;
                }
                if ($('.nav-prof,.nav-proj').length > 0) {
                    $('.nav-prof,.nav-proj').find('li').each(function(n) {
                        if (indice_ativo == n) {
                            $(this).find('a').addClass('active');
                        }
                        else {
                            $(this).find('a').removeClass('active');
                        }
                    });
                }
                /*if ($('.nav-proj').length > 0) {
                $('.nav-proj').find('li').each(function(n) {
                if (window["slider horizontal index"] == 1) {
                if (indice_ativo == n) {
                $(this).find('a').removeClass('active');
                }
                else {
                $(this).find('a').addClass('active');
                }
                }
                else {
                if (indice_ativo == n) {
                $(this).find('a').addClass('active');
                }
                else {
                $(this).find('a').removeClass('active');
                }
                }
                });
                }*/

                $parent.find(".slider").stop().animate(
                        { marginLeft: margin + "px" },
                        {
                            duration: o.slideDuration,
                            complete: function(p) {
                                if (ind == 1) {
                                    $parent.find(".slider").append($parent.find(".toSlide:first"));
                                    $parent.find(".slider").css("margin-left", "0");
                                }
                                $parent.find(".slideAct").removeClass("slideAct");
                                $parent.find(".toSlide:first").addClass("slideAct");

                                slideRunning = false; //set animation state: stopped  
                            }
                        });
            });
        });
    };

    // plugin defaults  
    $.fn.sliderHorizontal.defaults = {
        slideDuration: 150
    };
})(jQuery);                                     // end of plugin  
