/* ELO - carrega funções no load do DOM da página, ao invés do window.onload
 * Utilização: ELO.functionsToCallOnload.push("myFunction()");
 *
 *	ELO - Encapsulated Load Object, by Robert Nyman, http://www.robertnyman.com
 *	Inspired and influenced by Dean Edwards, Matthias Miller, and John Resig: http://dean.edwards.name/weblog/2006/06/again/
 */
var ELO = {
	loaded : false,
	timer : null,
	functionsToCallOnload : [], // Type in functions as strings here. e.g. "myFunction()"
	init : function (){
		if(ELO.loaded) return;
		ELO.loaded = true;
		ELO.load();
	},
	
	load : function (){
		if(this.timer){
			clearInterval(this.timer);
		}
		for(var i=0; i<this.functionsToCallOnload.length; i++){
			try{
				eval(this.functionsToCallOnload[i]);
			}
			catch(e){
				// Handle error here
			}
		}
	}
};
// ---
/* Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	if(document.getElementById){
		document.write("<script id=\"ieScriptLoad\" defer src=\"javascript:void(0)\"><\/script>");
	    document.getElementById("ieScriptLoad").onreadystatechange = function() {
	        if (this.readyState == "complete") {
	            ELO.init();
	        }
	    };
	}
/*@end @*/
// ---
/* Mozilla/Opera 9 */
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", ELO.init, false);
}
// ---
/* Safari */
if(navigator.userAgent.search(/WebKit/i) != -1){
    ELO.timer = setInterval(function (){
		if(document.readyState.search(/loaded|complete/i) != -1) {
			ELO.init();
		}
	}, 10);
}
// ---
/* Other web browsers */
window.onload = ELO.init;
// ---



/* abreMenuProdutos : força a exibição do menu de produtos, caso seja clicado no link herbicidas/fungicidas/inseticidas */
abreMenuProdutos = function() {
	var menu = document.getElementById("navmenu");
	var li = menu.getElementsByTagName("li")[5]; //5 é o quinto LI dentro do menu, de produtos. Mudar numero caso o menu sofra alteração
	li.className += " iehover";
	li.onmouseout = function() { li.className = li.className.replace(/ iehover/gi, ""); }
}


/* ========== JS AddEvent e RemoveEvent  ========= */

/* addEvent(object: Object, event: String, handler: Function(e: Event): Boolean, [scope: Object = object]): Boolean
 * Adiciona uma função que será disparada quando ocorrer determinado evento no objeto.
 * 
 * @object		objeto que receberá o listener
 * @event		nome do evento sem o prefixo "on" (click, mouseover, ...)
 * @handler		função que será chamada quando o evento ocorrer, será enviado como argumento
 * 				para esta função o objeto de evento, que além das propriedades normais, *sempre* irá conter:
 * 				@@target: objeto que gerou o evento
 *	 			@@key: código do caractere em eventos de teclado
 * 				@@stopPropagation: método para evitar a propagação do evento
 * 				@@preventDefault: método para evitar que a ação default ocorra o preventDefault pode ser emulado retornando "false" na função
 * @scope		escopo (quem o "this" irá referenciar dentro do handler) que será usado quando a função for chamada, o default é o objeto no primeiro argumento
 */
addEvent = function(o, e, f, s){
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e){
        try{
            (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
            e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
            e.target || (e.target = e.srcElement || null);
            e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        }catch(f){}
        for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

/* removeEvent(object: Object, event: String, handler: function(e: Event): Boolean, [scope: Object = object]): Boolean
 * Remove um listener previamente adicionado em um objeto e retorna true em caso de sucesso.
 * 
 * @object		objeto que recebeu o listener
 * @event		nome do evento sem o prefixo "on" (click, mouseover, ...)
 * @handler		mesma função que foi atribuida no addEvent
 * @scope		escopo em que a função foi adicionada, caso você tenha fornecido um escopo diferente no addEvent, é necessário que você passe como parâmetro o mesmo objeto, caso contrário a remoção do evento não será realizada
 */
removeEvent = function(o, e, f, s){
    for(var i = (e = o["_on" + e] || []).length; i;)
        if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
            return delete e[i];
    return false;
};
/* ========== Fim JS AddEvent e RemoveEvent  ========= */


/* ========== JS Restrict  ========= */
Restrict = function(form){
    this.form = form, this.field = {}, this.mask = {};
}
Restrict.field = Restrict.inst = Restrict.c = null;
Restrict.prototype.start = function(){
    var $, __ = document.forms[this.form], s, x, j, c, sp, o = this, l;
    var p = {".":/./, w:/\w/, W:/\W/, d:/\d/, D:/\D/, s:/\s/, a:/[\xc0-\xff]/, A:/[^\xc0-\xff]/};
    for(var _ in $ = this.field)
        if(/text|textarea|password/i.test(__[_].type)){
            x = $[_].split(""), c = j = 0, sp, s = [[],[]];
            for(var i = 0, l = x.length; i < l; i++)
                if(x[i] == "\\" || sp){
                    if(sp = !sp) continue;
                    s[j][c++] = p[x[i]] || x[i];
                }
                else if(x[i] == "^") c = (j = 1) - 1;
                else s[j][c++] = x[i];
            o.mask[__[_].name] && (__[_].maxLength = o.mask[__[_].name].length);
            __[_].pt = s, addEvent(__[_], "keydown", function(e){
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                r.l = r.value.length, Restrict.inst = o; Restrict.c = e.key;
                setTimeout(o.onchanged, r.e = 1);
            });
            addEvent(__[_], "keyup", function(e){
                (Restrict.field = e.target).e = 0;
            });
            addEvent(__[_], "keypress", function(e){
				if (e.ctrlKey) {
				} else {
					o.restrict(e) || e.preventDefault();
					var r = Restrict.field = e.target;
					if(!o.mask[r.name]) return;
					if(!r.e){
						r.l = r.value.length, Restrict.inst = o, Restrict.c = e.key || 0;
						setTimeout(o.onchanged, 1);
					}
                }
            });
        }
}
Restrict.prototype.restrict = function(e){
    var o, c = e.key, n = (o = e.target).name, r;
    var has = function(c, r){
        for(var i = r.length; i--;)
            if((r[i] instanceof RegExp && r[i].test(c)) || r[i] == c) return true;
        return false;
    }
    var inRange = function(c){
        return has(c, o.pt[0]) && !has(c, o.pt[1]);
    }
    return (c < 30 || inRange(String.fromCharCode(c))) ?
        (this.onKeyAccept && this.onKeyAccept(o, c), !0) :
        (this.onKeyRefuse && this.onKeyRefuse(o, c),  !1);
}
Restrict.prototype.onchanged = function(){
    var ob = Restrict, si, moz = false, o = ob.field, t, lt = (t = o.value).length, m = ob.inst.mask[o.name];
    if(o.l == o.value.length) return;
    if(si = o.selectionStart) moz = true;
    else if(o.createTextRange){
        var obj = document.selection.createRange(), r = o.createTextRange();
        if(!r.setEndPoint) return false;
        r.setEndPoint("EndToStart", obj); si = r.text.length;
    }
    else return false;
    for(var i in m = m.split(""))
        if(m[i] != "#")
            t = t.replace(m[i] == "\\" ? m[++i] : m[i], "");
    var j = 0, h = "", l = m.length, ini = si == 1, t = t.split("");
    for(i = 0; i < l; i++)
        if(m[i] != "#"){
            if(m[i] == "\\" && (h += m[++i])) continue;
            h += m[i], i + 1 == l && (t[j - 1] += h, h = "");
        }
        else{
            if(!t[j] && !(h = "")) break;
            (t[j] = h + t[j++]) && (h = "");
        }
    o.value = o.maxLength > -1 && o.maxLength < (t = t.join("")).length ? t.slice(0, o.maxLength) : t;
    if(ob.c && ob.c != 46 && ob.c != 8){
        if(si != lt){
            while(m[si] != "#" && m[si]) si++;
            ini && m[0] != "#" && si++;
        }
        else si = o.value.length;
    }
    !moz ? (obj.move("character", si), obj.select()) : o.setSelectionRange(si, si);
}

/* ========== Fim JS Restrict  ========= */





/* ========== Scroll de noticias ========= */
//var neo_scroll_div = "";
//var neo_scroll_sheight=200;
//var neo_scroll_sspeed=2;
//var neo_scroll_swidth = 150;

/* neo_scroll_start(object: params
 * Inicia um painel de scroll em determinado elemento
 * 
 * Variaveis enviadas em params:
 * @div			Alvo: elemento a ser ativado (obrigatorio)
 * @speed		Velocidade do scroll - de 0 a 4
 * @height		Altura do scroll
 * @width		Largura do scroll
 *
 * ex: neo_scroll_start({div: "divScroll", speed: 3}) ;
 */
function neo_scroll_start(params) {
	var neo_scroll_div			= document.getElementById(params.div); //alvo
	var neo_scroll_sheight		= (params.height==null) ? neo_scroll_sheight : params.height; //altura
	var neo_scroll_swidth		= (params.width==null) ? neo_scroll_swidth : params.width; //largura
	var neo_scroll_sspeed		= (params.speed==null) ? neo_scroll_sspeed : params.speed; //Velocidade de corrida
	neo_scroll_resumesspeed	= neo_scroll_sspeed; // Velocidade a ser recuperada após pausa do mouse

	var html = neo_scroll_div.innerHTML;

	// cria uma div interna com o conteudo da div original
	var div = document.createElement("DIV");
	div.id = "neo_scroll_ticker_" + neo_scroll_div.id;
	div.innerHTML = html;
	div.style.position = "relative";
	div.style.width = neo_scroll_swidth + "px";

	neo_scroll_div.innerHTML = ""; // zera conteudo
	neo_scroll_div.appendChild(div); // repõe o conteudo


	// antigo (so rodava em 1 scroll na pagina)
	//neo_scroll_div.neo_scroll_sspeed = neo_scroll_sspeed;
	//neo_scroll_div.neo_scroll_sheight = neo_scroll_sheight;
	//neo_scroll_div.neo_scroll_resumesspeed = neo_scroll_resumesspeed;
	//neo_scroll_div.onmouseover = function() { this.neo_scroll_sspeed = 0; }; //pausa
	//neo_scroll_div.onmouseout  = function() { this.neo_scroll_sspeed = neo_scroll_resumesspeed; }; //resume da pausa

	div.neo_scroll_sspeed = neo_scroll_sspeed;
	div.neo_scroll_sheight = neo_scroll_sheight;
	div.neo_scroll_resumesspeed = neo_scroll_resumesspeed;
	div.onmouseover = function() { this.neo_scroll_sspeed = 0; }; //pausa
	div.onmouseout  = function() { this.neo_scroll_sspeed = neo_scroll_resumesspeed; }; //resume da pausa

	//personaliza visual
	neo_scroll_div.style.position = "relative";
	neo_scroll_div.style.overflow = "hidden";
	neo_scroll_div.style.width = neo_scroll_swidth + "px";
	neo_scroll_div.style.height = neo_scroll_sheight + "px";
	//neo_scroll_div.style.padding = "2px";

	neo_scroll_marquee(document.getElementById("neo_scroll_ticker_" + neo_scroll_div.id));
}

function neo_scroll_marquee(whichdiv){
	var ns6div = whichdiv;
	ns6div.neo_scroll_sheight += 50;
	ns6div.style.top = ns6div.neo_scroll_sheight + "px";
	sizeup = ns6div.offsetHeight;
	neo_scroll_slide(ns6div.id);
}

function neo_scroll_slide(qdiv){
	var ns6div = document.getElementById(qdiv);

	if (parseInt(ns6div.style.top) >= sizeup * (-1)) {
		theTop = parseInt(ns6div.style.top) - ns6div.neo_scroll_sspeed;
		ns6div.style.top = theTop + "px";
		setTimeout("neo_scroll_slide('" + qdiv + "')",100);
	}
	else {
		ns6div.style.top = ns6div.neo_scroll_sheight + "px";
		neo_scroll_slide(qdiv);
	}
}



/* ========== FIM Scroll de noticias ========= */




/* submitProduto
 * Envia o formulário da página produtos/index.php
 * 
 * Parametros:
 * @select	Objeto <SELECT> de onde o produto é selecionado
 *
 * Retorno: null
 *
 * ex: submitProduto(document.getElementById('selectProduto'));
 */
function submitProduto(select) {
	if (select.selectedIndex==0)
		return;

	var form = encontraTagAcima(select, "FORM");
	if (form!=null) {
		form.submit();
	}
}


/* encontraTagAcima
 * Encontra a tag pai de objReferencia
 * 
 * Parametros:
 * @objReferencia	Alvo: elemento a ser tomado como referência
 * @tag				Nome da tag pai
 *
 * Retorno: object
 *
 * ex: 
 * HTML - <body> <form> <table> <tr id='tagReferencia'> ... </tr> </table> </form> </body>
 * JS: var tag = encontraTagAcima(document.getElementById('tagReferencia'), 'form');
 */
function encontraTagAcima(objReferencia, tag) {
	obj = objReferencia.parentNode;
	while (obj.nodeName != tag) {
		obj = obj.parentNode;
		if (obj.nodeName=="BODY") {
			obj = null;
			break;
		}
	}

	return obj;
}

/* abrePopUp
 * Owner: David Franco
 * Abre uma janela PopUp
 * 
 * Parametros:
 * @link	(string) página que o PopUp deve abrir
 * @width	(string) largura em pixels- opcional
 * @height	(string) algura em pixels - opcional
 *
 * Retorno: null
 *
 * ex: abrePopUp('produto.asp');
 * ex: abrePopUp('produto.asp', 800); // abre janela com valor default para altura, e 800 de largura
 */
function abrePopUp (link, width, height) {
	if (width==null) width = "600";
	if (height==null) height = "400";

	if (link != null) {
		var janela = window.open(link,'janelaPop','location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no,width=' + width + ',height=' + height);
		if (janela != null)
			janela.focus();
	}
	return false;
}


popUpImagem = function(aLink){
	var link = null;
	var janela;

	if (typeof(aLink)=="String") {
		link = aLink;
	} else if (typeof(aLink)=="object") {
		link = aLink.href;
	}

	if (link!=null) {
		var janela = window.open(link,'janelaPop','location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no,width=600,height=400');
		if (janela != null)
			janela.focus();
	}
	return false;
}


/* iniciaRotacaoCampanhas
 * Faz rotação das campanhas carregadas no conteudo direito da pagina
 * O elemento campanhasProdutos deve ter inicialmente o conteúdo no formato: <ul> <li>campanha...</li><li>campanha...</li> </ul>
 * 
 * Retorno: null
 *
 * ex: iniciaRotacaoCampanhas();
 */

var campanhasCarregadas = new Array;
var campanhaAtual = -1;
function iniciaRotacaoCampanhas() {
	var div = document.getElementById("campanhasProdutos");
	if (div != null) {
		var campanhas = div.getElementsByTagName("LI");

		if (campanhas!=null && campanhas.length > 1) {
			for (var i = 0; i < campanhas.length; i++) {
				campanhasCarregadas.push(campanhas[i].innerHTML);
			}
		}
	}

	rodarCampanha();
}

function rodarCampanha() {
	try {
		campanhaAtual++;
		if (campanhaAtual >= campanhasCarregadas.length) {
			campanhaAtual = 0;
		}

		var div = document.getElementById("campanhasProdutos");
		if (div != null) {
			div.innerHTML = campanhasCarregadas[campanhaAtual];
		}

		window.setTimeout(rodarCampanha, 10000);
	}
	catch (ex) {
	}
}