var Application = {};
var Classes = {};

$(function(){
    Classes.App = Class.extend({
        init: function(){
            this.instances = {};

            $("a:not(.not-address, .ui-state-default)").live("click", function(){
                var urlTmp = $(this).attr("href");
                SWFAddress.setValue(urlTmp);

                return false;
            });
        },

        initClass: function(className){
            
            if(!this.instances[className]){
                this.instances[className] = new Classes[className]();
            }
            else {
                this.instances[className].init();
            }
        },

        bindAddressChange: function(){
            var self = this;
            SWFAddress.onChange = function(){
                self.addressChange();
            };
        },
        
        unbindAddressChange: function(){
            SWFAddress.onChange = null;
        },

        //ALTERA O ENDERECO DA URL SEM FAZER A REQUISICAO AJAX
        setAddress: function(urlTmp){
            this.unbindAddressChange();
            SWFAddress.setValue(urlTmp);
            this.bindAddressChange();
        },
        
        addressChange: function(){
            var self = this;
            var target = this.addressChangeTarget ? $("#" + this.addressChangeTarget) : $("#content");
            
            this.showLoading();
            var urlRequest = SWFAddress.getValue() == "/" ? SWFAddress.getBaseURL() : SWFAddress.getBaseURL() + SWFAddress.getValue();
			
			//FIX DO BUG DO TOOLTIP DA ABA DO ANO VIGENTE NA VISUALIZACAO DA ONG
			if($("#current")){
				$("#current").blur();
			}
			
            
            $.get(urlRequest, function(resp){
                target.html(resp);
                self.addressChangeResponse();
            })
        },
        
        addressChangeResponse: function(){
        
        },
        
        //Mostra mensagem informativa que desaparece automaticamente. Delay parametrizavel.
        statusMessage: function(messages, delay){
            var messagesTmp = [];

            if(!$.isArray(messages)){
                messagesTmp.push(messages);
            } else {
                messagesTmp = messages;
            }

            $.each(messagesTmp, function(n, v){
                $.jGrowl(v, {
                    life: delay ? delay : 2000
                });
            })

        },
        
        //Mostra loading da requisição ajax. Desaparece automaticamente no retorno da requisição.
        showLoading: function(){
            $.loading({
                onAjax: true,
                text: 'Carregando'
            });
        },
        
        renderAccordion: function(containerSelector){
            $(containerSelector).accordion({
                autoHeight: false,
                active: false,
                collapsible: true
            });
            
            $(containerSelector).find(".ui-accordion-header").click(function(e){
                
                //REMOVE O TOOLTIP CASO EXISTA ALGUM VISIVEL DA OPERACAO ANTERIOR.
                $("#tiptip_holder").hide();

                $(e.target).parents(containerSelector).siblings().accordion('activate', false);
                $(this).next("div").load($('a', this).attr("href"));
            })
            
        },

        setEditor: function(textarea_id, maxChar){

             window[textarea_id] = $("#"+textarea_id).cleditor({
                width:        500, // width not including margins, borders or padding
                height:       250, // height not including margins, borders or padding
                controls:     // controls to add to the toolbar
                "bold italic underline | bullets numbering | alignleft center alignright justify",
                sizes:        // sizes in the font size popup
                "1,2,3,4,5,6,7",
                styles:       // styles in the style popup
                [["Paragraph", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"],
                ["Header 3", "<h3>"],  ["Header 4","<h4>"],  ["Header 5","<h5>"],
                ["Header 6","<h6>"]],
                useCSS:       false, // use CSS to style HTML when possible (not supported in ie)
                docCSSFile:   "", // CSS file used to style the document contained within the editor.
                bodyStyle:    // style to assign to document body contained within the editor
                "margin:4px; font:10pt Arial,Verdana; cursor:text"
            });
            
            var self = this;

            $(window[textarea_id][0].$main).after('<div style="margin-top: 8px;">&nbsp;Caracteres restantes:<strong>&nbsp;<span class="editorCharCount"></span></strong></div><br/>');

            var maxCharCount = maxChar ? maxChar : 800;
            window[textarea_id][0].maxCharCount = maxCharCount;

            $(window[textarea_id][0].doc).bind("paste keyup", function(e){

                if(e.type != "paste" && (e.keyCode == 17 || e.keyCode == 91)){
                    return false;
                }

                if(e.type == "paste"){
                    $(window[textarea_id][0].doc.body).html($(window[textarea_id][0].doc.body).text());
                }

                self.counterTextEditor(textarea_id);

            });

            //FIX PARA O PASTE NO INTERNET EXPLORER
            if($.browser.msie){
                window[textarea_id][0].$frame[0].contentDocument.body.onpaste = function(){
                    setTimeout(function(){
                        $(window[textarea_id][0].doc.body).html($(window[textarea_id][0].doc.body).text());
                        self.counterTextEditor(textarea_id);
                     }, 20);
                }
            }

        },

        counterTextEditor: function(textarea_id){
            
            var objEditorBody = $(window[textarea_id][0].doc.body);

            if($(window[textarea_id][0].doc.body).html() != window[textarea_id][0].$area.html()){
                
                var btnSalvar = $("#"+textarea_id).parents("form").find(".btnSalvar");

                if(btnSalvar.length <= 0){
                    btnSalvar = $("#"+textarea_id).parents(".ui-accordion-content").find(".btnSalvar").eq(0);
                }

            }

            var qtdChar = objEditorBody.text().length;

            var matches = objEditorBody.html().match(/<div><br><\/div>/gi);

            if(matches) {
                qtdChar += matches.length;
            }

            $("#"+textarea_id).parents("form").find(".editorCharCount").text(window[textarea_id][0].maxCharCount - qtdChar);
        },

        verificaEditorMaxLength: function(textarea_id){
            var objEditorBody = $(window[textarea_id][0].doc.body);
            var qtdChar = objEditorBody.text().length;

            var matches = objEditorBody.html().match(/<div><br><\/div>/gi);

            if(matches) {
                qtdChar += matches.length;
            }

            if(qtdChar > window[textarea_id][0].maxCharCount){
                $.prompt("Quantidade de caracteres é maior que o permitido");
                return false;
            } else {
                return true;
            }
        },

        setEditorText: function(textarea_id, text){
            $(window[textarea_id][0].doc.body).html(text);

            window[textarea_id][0].$area.html(text);
            window[textarea_id][0].focus();
            this.counterTextEditor(textarea_id);
        },

        setTextCounter: function(objInput){
            
          objInput.each(function(){
            $(this).after("&nbsp;(<span>máx.: "+$(this).attr("maxlength")+"</span>)");
          })
//
//          objInput.keyup(function(e){
//              var target = $(e.target);
//              var maxLength = target.attr("maxlength");
//
//              target.next("span").text(maxLength - target.val().length);
//          });
//
//          objInput.keypress(function(e){
//              var target = $(e.target);
//              var maxLength = target.attr("maxlength");
//
//              if(target.val().length >= maxLength){
//                  return false;
//              }
//
//              return true;
//          });
        },

        //HABILITA BOTAO E APLICA TOOLTIP
        enableButton: function(objButton){
            objButton.button({
                disabled:false
            }).tipTip({
                delay:0,
                content:"Salvar Alterações",
                defaultPosition: "right"
            }).mouseover().click(function(e){
                $(e.target).mouseout().button({disabled:true});
            });
        },

        //MONTA COMBO
        montaSelect: function(urlRequest, selectObj, data, emptyOption, callback){
            var dataRequest = data ? data : {};
            $.getJSON(urlRequest, dataRequest, function(response){

                var html = '';

                if(emptyOption){
                    html += '<option value="">selecione</option>';
                }

                $.each(response, function(n, v){
                    html += '<option value="'+v.id+'">'+v.nome+'</option>';
                });
                
                selectObj.html(html);

                if(typeof callback == 'function'){
                    callback();
                }

            });
        }
        
    });
	
    Application = new Classes.App();
    
});

