var dominioc = 3;

var Dados = {
    HOST : function(){
        return window.location.hostname;        
    },
    BASE_URL : function(){
        return "http://"+this.HOST()+"/";        
    },
    IMG_URL : function(){
        return this.BASE_URL()+"img/";        
    },
    EVT_INT : function ( obj, type, fn ) {
        if (obj.addEventListener) {
            obj.addEventListener( type, fn, false );
        } else if (obj.attachEvent) {
            obj["e"+type+fn] = fn;
            obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
            obj.attachEvent( "on"+type, obj[type+fn] );
        } else {
            obj["on"+type] = obj["e"+type+fn];
        }
    }
    
};

/**
 *
 * @author Bernardo Rufino <bermonruf@gmail.com>
 * @license Creative Commons Developing Nations: http://creativecommons.org/licenses/devnations/2.0/
 * @version 0.8
 * @description Script to add dynamic navigating functionality, it's framework independent
 *
 *       !Não retire essas informações!
 *       !Do not drop this information!
 */
 
//Just like the prototype, it returns a function wrapped in a context

Function.prototype.bind = function(context){
	var closure = this;
	var tmp_fnc = function(){
		return closure.apply(context, arguments);
	}
	return tmp_fnc;
}
 
 
document.navigators = {
	settings: {
		interval: 200, //The interval which the verification for new data will be done (in miliseconds)
		helper: true, //Specify if the onnavigate function will return the helper, do not change!
		iframe_src: Dados.BASE_URL()+"etc/control.htm" //The location of the file control.htm, absolute path please
	},
	initialize: function(){
		this.is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") > -1) ? true : false;
		if(this.is_ie){
			this.settings.iframe_src = this.settings.iframe_src.replace(/(\?|#).*$/, "");
			window.attachEvent("onload", (function(){
				//this.running = true; The iFrame that needs to make it running
				this.iframe = document.createElement("iframe");
				this.iframe.setAttribute("src", this.settings.iframe_src);
				this.iframe.style.display = "none";
				document.getElementsByTagName("body")[0].appendChild(this.iframe);
			}).bind(this));
		} else {this.running = true;}
	},
	//The function that is called by the user and puts new data in the hash to be called
	helper: function(data, force){
		var navs = document.navigators; var data = "" + this.id + "" + data;
		if(!force){navs.data_buffer = "";} //If force is true then calling sequentially the same helper works
		if(navs.is_ie){navs.iframe.src = navs.settings.iframe_src + "?act=" + data;}
		else{window.location.hash = "#" + data;}
	},
	called: false,
	history: [],
	data_buffer: ""
};
 
function onnavigate(id, callback){
	var navs = document.navigators; navs[id] = {};
	if(!navs.running){navs.initialize();}
	setInterval(function(){if(navs.running){
		var url = window.location.href;
		var hash = window.location.hash.replace(/#/, "");
		var theid = "#" + id + "";
		if(url.indexOf(theid) > -1){ //If the call is with us!
			var data = url.split(theid)[1] || "";
			var new_data = theid + data;
			if(navs.data_buffer != new_data){ //If the old content is diferent
				callback(data); //Calling the callback function!
				navs.called = true; //To make sure was already called to fix the index state
				navs.history.push(new_data);
				navs.data_buffer = new_data;
			}
		} else if (!hash && navs.called){ //If the navigators was called and the page is in index state (no hashes), it means reload!
			navs.running = false; //To stop the others Intervals to dont make it the same way and broke something
			window.location = ((url.indexOf("#") > -1) ? url.split("#")[0] : url) + "#";
			window.location.reload();
		}
	}}, navs.settings.interval);
    navs[id].merge = function(object){
        for(attr in object){
            this[attr] = object[attr];
        }
    }
	navs[id].merge({callback: callback});
	if(navs.settings.helper){
		navs[id].helper = navs.helper.bind({id: id}); return navs[id].helper;
	}
}


//-------------------------------------------------------------------
// FUNÇÃO GLOBAL, PARA DIMINUIR O GETELEMENTBYID, COMO NO MYSQLQUERY
//-------------------------------------------------------------------
var Apelidos = {
    getById : function(elementoID) {
        return document.getElementById(elementoID);
    },
    getByTagName : function(tag) {
        return document.getElementsByTagName(tag);
    },
    getByClassName : function (clsName) {
        var retVal = new Array();
        var elements = this.getByTagName("*");
        for(var i = 0;i < elements.length;i++){
            if(elements[i].className.indexOf(" ") >= 0){
                var classes = elements[i].className.split(" ");
                for(var j = 0;j < classes.length;j++){
                    if(classes[j] == clsName)
                        retVal.push(elements[i]);
                }
            } else if(elements[i].className == clsName)
                retVal.push(elements[i]);
        }
        return retVal;
    },
    urlencode : function(s) {
        s = encodeURIComponent(s);
        return s.replace(/~/g,'%7E').replace(/%20/g,'+' );
    },
    MTitulo : function (title){
        return document.title = title+' - Hallel Paracatu 2010';
    }

};

//-----------------------------------------------------------------------------------------
// FUNÇÃO PARA VALIDAR FORMULÁRIOS
//-----------------------------------------------------------------------------------------
/* Script Adptado por ThiagoInfo */

var Validar = {
	isEmail : function(s) {
		return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$');
	},

	isAbsUrl : function(s) {
		return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$');
	},

	isSize : function(s) {
		return this.test(s, '^[0-9]+(%|in|cm|mm|em|ex|pt|pc|px)?$');
	},

	isId : function(s) {
		return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$');
	},

	isEmpty : function(s) {
		var nl, i;

		if (s.nodeName == 'SELECT' && s.options[s.selectedIndex].value == 'Selecione')
			return true;
		if (s.nodeName == 'INPUT' && s.value == '')
			return true;
		if (s.nodeName == 'TEXTAREA' && s.value == '')
			return true;

		if (s.type == 'checkbox' && !s.checked)
			return true;

		if (s.type == 'radio') {
			for (i=0, nl = s.form.elements; i<nl.length; i++) {
				if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked)
					return false;
			}

			return true;
		}

		return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s);
	},
	test : function(s, p) {
		s = s.nodeType == 1 ? s.value : s;

		return s == '' || new RegExp(p).test(s);
	}
};

var AutoValidar = {
	settings : {
		id_cls : 'id',
		int_cls : 'int',
		url_cls : 'url',
		number_cls : 'number',
		email_cls : 'email',
		size_cls : 'size',
		required_cls : 'requerido',
		invalid_cls : 'invalido',
		min_cls : 'min',
		max_cls : 'max',
		verificado_cls : 'verificado'
	},

	init : function(s) {
		var n;

		for (n in s)
			this.settings[n] = s[n];
	},

	valida : function(f) {
		var i, nl, s = this.settings, c = 0;

		nl = this.tags(f, 'label');
		if(Apelidos.getById("msg-form-erro")){
            // Ao clicar no botão limpar, retira a mensagem de erro
            Apelidos.getById("msg-form-erro").style.display = "none";
        }
		for (i=0; i<nl.length; i++)
			this.removeClass(nl[i], s.invalid_cls);
			

		c += this.validaElms(f, 'input');
		c += this.validaElms(f, 'select');
		c += this.validaElms(f, 'textarea');

		return c == 3;
	},

	invalidate : function(n) {
		this.mark(n.form, n);
	},

	limpa : function(e) {
		var t = ['label', 'input', 'select', 'textarea'];
		var i, j, nl, s = this.settings;

		if (e == null)
			return;
		if(Apelidos.getById("msg-form-erro")){
            // Ao clicar no botão limpar, retira a mensagem de erro
            Apelidos.getById("msg-form-erro").style.display = "none";
        }	

		for (i=0; i<t.length; i++) {
			nl = this.tags(e.form ? e.form : e, t[i]);
			for (j=0; j<nl.length; j++){
				this.removeClass(nl[j], s.invalid_cls);
				this.removeClass(nl[j], s.verificado_cls);				
			}
				
		}
	},

	validaElms : function(f, e) {
		var nl, i, n, s = this.settings, st = true, va = Validar, v;

		nl = this.tags(f, e);
		for (i=0; i<nl.length; i++) {
			n = nl[i];

			this.removeClass(n, s.invalid_cls);
			
			if (this.removeClass(n, s.invalid_cls) && this.hasClass(n, s.required_cls)){
				this.addClass(n, s.verificado_cls);
			}

			if (this.hasClass(n, s.required_cls) && va.isEmpty(n))
				st = this.mark(f, n);			
				
			if (this.hasClass(n, s.number_cls) && !va.isNumber(n))
				st = this.mark(f, n);

			if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true))
				st = this.mark(f, n);

			if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n))
				st = this.mark(f, n);

			if (this.hasClass(n, s.email_cls) && !va.isEmail(n))
				st = this.mark(f, n);
				
			if (this.hasClass(n, s.size_cls) && !va.isSize(n))
				st = this.mark(f, n);

			if (this.hasClass(n, s.id_cls) && !va.isId(n))
				st = this.mark(f, n);

			if (this.hasClass(n, s.min_cls, true)) {
				v = this.getNum(n, s.min_cls);

				if (isNaN(v) || parseInt(n.value) < parseInt(v))
					st = this.mark(f, n);
			}

			if (this.hasClass(n, s.max_cls, true)) {
				v = this.getNum(n, s.max_cls);

				if (isNaN(v) || parseInt(n.value) > parseInt(v))
					st = this.mark(f, n);
			}
		}

		return st;
	},

	hasClass : function(n, c, d) {
		return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className);
	},

	getNum : function(n, c) {
		c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0];
		c = c.replace(/[^0-9]/g, '');

		return c;
	},

	addClass : function(n, c, b) {
		var o = this.removeClass(n, c);
		n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c;
	},

	removeClass : function(n, c) {
		c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' ');
		return n.className = c != ' ' ? c : '';
	},

	tags : function(f, s) {
		return f.getElementsByTagName(s);
	},

	mark : function(f, n) {
		var s = this.settings;

		this.addClass(n, s.invalid_cls);
		this.markLabels(f, n, s.invalid_cls);
		Apelidos.getById("msg-form-erro").style.display = "block";
		Apelidos.getById("msg-form-erro").innerHTML =  "Os campos marcados em vermelho são de preenchimento obrigatório!";
		return false;
	},
	markLabels : function(f, n, ic) {
		var nl, i;

		nl = this.tags(f, "label");
		for (i=0; i<nl.length; i++) {
			if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id)
				this.addClass(nl[i], ic);
		}

		return null;
	}
};

var Ajax = {
    xhrRequest : function (type) {
        var xhr = new Array(); // ARRAY OF XML-HTTP REQUESTS
        var xi = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
        this.xhr = xhr; this.xi = xi;
        
        xi[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE
        if (!type) { type = 'html'; }
        // xhrsend IS THE xi POSITION THAT GETS PASSED BACK
        // INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
        // IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
        var xhrsend = xi.length;
        // GO THROUGH AVAILABLE xi VALUES
        for (var i=0; i<xi.length; i++) {
            // IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
            if (xi[i] == 1) {
                xi[i] = 0; xhrsend = i;
                break;
            }
        }
        // SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
        xi[xhrsend] = 0;
        // SET UP THE REQUEST
        if (window.ActiveXObject) {
            try {
                xhr[xhrsend] = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xhr[xhrsend] = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        } else if (window.XMLHttpRequest) {
            xhr[xhrsend] = new XMLHttpRequest();
            if (xhr[xhrsend].overrideMimeType) {
                xhr[xhrsend].overrideMimeType('text/' + type);
            }
        }
        return (xhrsend);
    },
    GET : function(nav, crt, el, msg){
        var xhri = this.xhrRequest('html');
        var xhr = this.xhr;
        var xi = this.xi;
        var bs = Dados;
                               
        xhr[xhri].onreadystatechange = function(){
            if (xhr[xhri].readyState == 1) {
                el.innerHTML =  msg;
            }
            if (xhr[xhri].readyState == 4){
                if(xhr[xhri].status == 200) {
                    var texto = xhr[xhri].responseText;
                    texto = texto.replace(/([^\x01-\x7E])/g,function(word){return'&#'+word.charCodeAt(0)+ ';';});
                    el.innerHTML = texto;
                    Executar.Inicio();
                    xi[xhri] = 1;
                    xhr[xhri] = null;
                } else{
                    Executar.Repetir(nav, crt, el, msg);
                }
            }
        };
        xhr[xhri].open("GET", bs.BASE_URL()+nav+"/"+crt+".ajax", true);
        xhr[xhri].setRequestHeader("encoding", "ISO-8859-1");
        xhr[xhri].setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
        xhr[xhri].setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        xhr[xhri].setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        xhr[xhri].setRequestHeader("Pragma", "no-cache");
        xhr[xhri].send(null);
    },
    POST : function(crt,elementoID,formID){
        var xhri = this.xhrRequest('html');
        var xhr = this.xhr;
        var xi = this.xi;
        var bs = Dados;
        var va = Apelidos;
        var elementosFormulario = va.getById(formID).elements;
        var qtdElementos = elementosFormulario.length;
        var queryString = "";
        var elemento;
        //Cria uma funcao interna para concatenar os elementos do form
        this.ConcatenaElemento = function(nome,valor) {
            if (queryString.length>0) {
                queryString += "&";
            }
            queryString += encodeURIComponent(nome) + "=" + encodeURIComponent(this.uni2ent(valor));
        };
        //Loop para percorrer todos os elementos
        for (var i=0; i<qtdElementos; i++) {
            //Pega o elemento
            elemento = elementosFormulario[i];
            if (!elemento.disabled) {
                //Trabalha com o elemento caso ele nao esteja desabilitado
                switch(elemento.type) {
                    //Realiza a acao dependendo do tipo de elemento
                    case 'text': case 'password': case 'hidden': case 'textarea':
                        this.ConcatenaElemento(elemento.name,elemento.value);
                        break;
                    case 'select-one':
                        if (elemento.selectedIndex>=0) {
                            this.ConcatenaElemento(elemento.name,elemento.options[elemento.selectedIndex].value);
                        }
                        break;
                    case 'select-multiple':
                        for (var j=0; j<elemento.options.length; j++) {
                            if (elemento.options[j].selected) {
                                this.ConcatenaElemento(elemento.name,elemento.options[j].value);
                            }
                        }
                        break;
                    case 'checkbox': case 'radio':
                        if (elemento.checked) {
                            this.ConcatenaElemento(elemento.name,elemento.value);
                        }
                        break;
                }
            }
        }
        
        xhr[xhri].onreadystatechange = function(){
            if (xhr[xhri].readyState==1) {
                va.getById(elementoID).innerHTML =  "<div class=\"carregando\"><img src=\""+bs.IMG_URL()+"carregando.gif\" /> Aguarde, enviando dados...</div>";
            }
            if (xhr[xhri].readyState == 4){
                if (xhr[xhri].status == 200){
                    va.getById(elementoID).innerHTML = xhr[xhri].responseText;
                    Executar.Inicio();
                    xi[xhri] = 1;
                    xhr[xhri] = null;
                }
            }
        };
        xhr[xhri].open("POST", bs.BASE_URL()+"form/"+crt+".ajax", true);
        xhr[xhri].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr[xhri].send(queryString);
    },
    
    geral : function (nav, crt, elemento, msg){
        var va = Apelidos;        
        var elemento = va.getById(elemento);        
        this.GET(nav, crt, elemento, msg);
     },
     uni2ent : function (srcTxt) {
        var entTxt = '';
        var c, hi, lo;
        var len = 0;
        for (var i=0, code; code=srcTxt.charCodeAt(i); i++) {
            var rawChar = srcTxt.charAt(i);
            // needs to be an HTML entity
            if (code > 255) {
                // normally we encounter the High surrogate first
                if (0xD800 <= code && code <= 0xDBFF) {
                    hi  = code;
                    lo = srcTxt.charCodeAt(i+1);
                    // the next line will bend your mind a bit
                    code = ((hi - 0xD800) * 0x400) + (lo - 0xDC00) + 0x10000;
                    i++; // we already got low surrogate, so don't grab it again
                }
                // what happens if we get the low surrogate first?
                else if (0xDC00 <= code && code <= 0xDFFF) {
                    hi  = srcTxt.charCodeAt(i-1);
                    lo = code;
                    code = ((hi - 0xD800) * 0x400) + (lo - 0xDC00) + 0x10000;
                }
                // wrap it up as Hex entity
                c = "&#x" + code.toString(16).toUpperCase() + ";";
            } else {
                c = rawChar;
            }
            entTxt += c;
            len++;
        }
        return entTxt;
     }
};

var Executar = {
    carrega_links : function(){
        var va = Apelidos;
        var links = va.getByTagName("a");
        for ( var i=0; i < links.length; i++) {
            var rel = links[i].getAttribute("rel");
            if(rel != 'interno'){
                if((rel == 'externo') || (rel == 'nofolow')){
                    links[i].onclick = function() {
                        window.open(this.href);
                        return false;
                    }                    
                } else if(rel == 'bbcode'){
                    links[i].onclick = function() {
                        return BBCode.Inserir(this);
                    }
                } else if(rel == 'recados'){
                    links[i].onclick = function() {
                        return Executar.comelID(this);
                    }
                } else {
                    links[i].onclick = function() {
                        return Executar.define_fn(this);
                    }
                }
            }

        }
    },
    carrega_forms : function(){
        var va = Apelidos;
        var forms = va.getByTagName("form");
        if(va.getById('reset')){
            var reset = va.getById('reset');
            reset.onclick = function(){
                return AutoValidar.limpa(this);
            }
        }
        for (var i=0; i < forms.length; i++) {
            forms[i].onsubmit = function() {
                return Executar.form_fn(this);
            }
        }
    },
    form_fn : function(p){
        if (p.getAttribute("id")){
            var fid = p.getAttribute("id");

            if(p.getAttribute("className") != null){
                 var par = p.getAttribute("className").split(':');

            } else if(p.getAttribute("class") != null) {
                var par = p.getAttribute("class").split(':');                
            }
            if(par != undefined){
                var nav = par[0];
                var mid = par[1];
                if(AutoValidar.valida(p)){
                    Ajax.POST(nav, mid, fid);
                }
            } else {
                return true;
            }
        }
        return false;        
    },
    get_href : function (p){
        if (p.getAttribute("href")){
            var href = p.getAttribute("href");
        }
                
        return href;
    },
    define_fn : function (p) {
        var href = this.get_href(p);
        var title = p.getAttribute("title");
        if (title != null){
            Apelidos.MTitulo(title);
        }               
        this.requisicao(href);
        return false;
    },
    requisicao : function (dados){
        var parametros = dados.split('/');
        var ibs = Dados;
        var act = parametros[dominioc];
        if(parametros[dominioc+1] != undefined){
            if(parametros[dominioc+1] == 'pag'){                
                var pag = parametros[dominioc+2];
                
            } else {
                var id = parametros[dominioc+1].split('-');
                id = id[0];
            }
        }
        if(pag != undefined){
            var crt = act+"&pag="+pag;
            navega(crt);
        } else if(id != undefined){
            var crt = act+"&id="+id;
            navega(crt);
        } else {
            navega(act);
        }

    },
    define_fn : function (p) {
        var href = this.get_href(p);
        var title = p.getAttribute("title");
        if (title != null){
            Apelidos.MTitulo(title);
        }               
        this.requisicao(href);
        return false;
    },
    comelID : function (p){
        var href = this.get_href(p);
        var parametros = href.split('/');
        var ibs = Dados;
        var nav = 'conteudo';
        var act = elID = p.getAttribute("rel");
        var msg = '<img src=\"'+ibs.IMG_URL()+'carregando.gif\" alt=\"Aguarde\" />';
        if(parametros[dominioc+1] != undefined){
            var pag = parametros[dominioc+2];
            var crt = act+"&pag="+pag;
            Ajax.geral(nav, crt, elID, msg);
        }      
        return false;
    },
    nav : function (dados){       
        var ibs = Dados;
        var nav = 'navega';
        var msg = "<div class=\"carregando\"><img src=\""+ibs.IMG_URL()+"carregando.gif\" alt=\"Aguarde\" /> Aguarde, carregando dados...</div>";
        var elemento = 'carrega-conteudo';
        Ajax.geral(nav, dados, elemento, msg);
    },
    Repetir : function(nav, crt, el, msg){
        setTimeout("Executar.nav('"+crt+"')", 1000);        
    },
    Inicio : function(){
        this.carrega_links();
        this.carrega_forms();
    }
};

//--------------------------------------------------------------------------------------
// FUNÇÃO INSERIR BBCODES - CLICAVÉIS
//--------------------------------------------------------------------------------------

var BBCode = {
    selecao : function (tag1,tag2,obj){
        elID = Apelidos.getById(obj);
        if (document.selection){
            elID.focus();
            var sel = document.selection.createRange();
            sel.text = tag1 + sel.text + tag2;
        } else {
            var len = elID.value.length;
            var start = elID.selectionStart;
            var end = elID.selectionEnd;
            
            var scrollTop = elID.scrollTop;
            var scrollLeft = elID.scrollLeft;
            
            var sel = elID.value.substring(start, end);
            var rep = tag1 + sel + tag2;
            elID.value =  elID.value.substring(0,start) + rep + elID.value.substring(end,len);
            elID.scrollTop = scrollTop;
            elID.scrollLeft = scrollLeft;
        }
    },
    Inserir : function(p){
        if (p.getAttribute("id")){
            var par = p.getAttribute("id").split(':');
            var tag = par[0];
            var tagvl = par[1];
            var tagfecha = '[/'+tag+']';
            if(tagvl != undefined){
                if(tagvl == 'b'){
                    var tagabre = ':'+tag+'';
                    tagfecha = ':';                    
                } else {
                    var tagabre = '['+tag+'='+tagvl+']';                  
                }
                
            } else {
                var tagabre = '['+tag+']';
                
            }
            
            this.selecao(tagabre, tagfecha, 'descricao');
        }
        return false;
        
    },
    selTexto : function (obj, antes, depois){
        var selecionado = this.selecao(obj, true);
        selecionado.defTexto(antes + selecionado.text + depois);
    }
};

// CHAMA E CONFIGURA A FUNÇÃO
navega = onnavigate("", function(data){
	Executar.nav(data);
});

//-----------------------------------------------------------------------------------------
// CHAMANDO OS EVENTOS NA INICIALIZAÇÃO
//-----------------------------------------------------------------------------------------
Dados.EVT_INT(window, 'load', function(){
    Executar.Inicio();
});
