var $j = jQuery.noConflict();

// JavaScript Document
var conteudoGMapas = "";
conteudoGMapas += '<div id="modulo_gmaps">';
conteudoGMapas += '<a class="close" href="javascript: fechaBox();"><img src="modulos/google_maps/img/btn_janela_close.png" style="width:auto; height:auto" /></a>';
conteudoGMapas += '<iframe name="detGoogleMaps" id="detGoogleMaps" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="modulos/google_maps/detGoogleMaps.php" width="480" height="500" style="overflow-x: hidden; margin-bottom:10px;"></iframe>';
conteudoGMapas += '</iframe>';
conteudoGMapas += '</div>';

ModuloIndique = function(args)  {
	args	= escape(args);
	novoBox('modulos/indique/cadIndique.php?pagina=' + args, '', 400, 385);
}

function applySelectedTo(link, abrir) {
	var ul = document.getElementById("sanfona"); // get the first ul tag on the page
	var allLinks = ul.getElementsByTagName("h3"); // get all the links within that ul

	for (var i=0; i<allLinks.length; i++) { // iterate through all those links
		allLinks[i].className = ""; // and assign their class names to nothing
		document.getElementById(allLinks[i].lang).style.display='none';
	}
	link.className = "ativo";  // finally, assign class="selected" to our chosen link
	document.getElementById(abrir).style.display='';
}

function bookmarksite(title,url){
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}else if(document.all)// ie
		window.external.AddFavorite(url, title);
}

// Para usar coloque o comando: "javascript:mudaTamanho('tag_ou_id_alvo', -1);" para diminuir
// e o comando "javascript:mudaTamanho('tag_ou_id_alvo', +1);" para aumentar

// Especificando os possíveis tamanhos de fontes, poderia ser: x-small, small...
var tamanhos = new Array('100%','110%','120%','130%','140%','150%');
var tamanhoInicial = 0;

function mudaTamanho( idAlvo,acao ){
  if (!document.getElementById) return
  var selecionados = null,tamanho = tamanhoInicial,i,j,tagsAlvo;
  tamanho += acao;
  if ( tamanho < 0 ) tamanho = 0;
  if ( tamanho > 5 ) tamanho = 5;
  tamanhoInicial = tamanho;
  if ( !( selecionados = document.getElementById( idAlvo ) ) ) selecionados = document.getElementsByTagName( idAlvo )[ 0 ];

	dives	= document.getElementsByTagName('div');
	for (i=0;i<dives.length;i++)  {
		if (dives[i].id==idAlvo)  {
			dives[i].style.fontSize = tamanhos[ tamanho ];
		}
	}
}

function scrollTop()  {
	window.scroll(0,0);
}

function voltaBack()  {
	history.back();
}

function mudaBusca(id) {
	document.getElementById('frmBusca').action = document.getElementById('cmbBusca').value;
}

function verficaBusca() {
	if (document.getElementById('q').value == 'O que você Procura?') {
		document.getElementById('q').value = '';
	}

	return false;
}

function excluiProduto(codproduto) {
	if (confirm("Deseja excluir este produto?")) {
		document.getElementById('produto_deletar').value = codproduto;
		document.getElementById('redirecionar').value = true;
		document.forms['frmCotacao'].submit();
	} else {
		return false;
	}
}

function excluiTodosProdutos() {
	if (confirm("Confirma exclusão de todos os produtos da sua cotação?")) {
		document.getElementById('produto_deletar').value = 'todos';
		document.getElementById('redirecionar').value = true;
		document.forms['frmCotacao'].submit();
	} else {
		return false;
	}
}

function salvarCotacao() {
	document.getElementById('redirecionar').value = false;
	document.getElementById('finalizar').value = false;
	document.forms['frmCotacao'].submit();
}

function finalizarCotacao() {
	document.getElementById('redirecionar').value = false;
	document.getElementById('finalizar').value = true;
	document.forms['frmCotacao'].submit();
}

function camposExtras(assunto) {
	if (assunto != '' && assunto != 'undefined' && assunto != 'Personalizar Produto' && assunto != 'Ser Representante') {
		gtr_makeRequest('modulos/fale_conosco/manMontaForm.php?assunto=' + assunto, 'campos_extras');
		document.getElementById('campos_extras').style.display = 'block';
	} else {
		document.getElementById('campos_extras').innerHTML = '';
		document.getElementById('campos_extras').style.display = 'none';
	}
}

var map;
var gdir;
var geocoder = null;
var addressMarker;

function initialize(latitude, longitude) {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        geocoder = new GClientGeocoder();
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        map.addControl(new GSmallMapControl());
        map.setCenter(new GLatLng(latitude,longitude), 16);
        map.addOverlay(new GMarker(new GLatLng(latitude,longitude)));
    }
}

function setDirections(latitude,longitude) {

    var fromAddress = document.getElementById('from').value;

    var point = geocoder.getLatLng(fromAddress,
        function(point) {
            if (!point) {
                alert(fromAddress + " não encontrado");
            } else {
                var wp = new Array(2);
                wp[0] = point;
                wp[1] = new GLatLng(latitude,longitude);

                gdir.loadFromWaypoints(wp, {"locale": "pt_BR"});
            }
        }
    );

    return false;

}

function handleErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    else
        alert("An unknown error occurred.");
}

function onGDirectionsLoad(){
}

function GetFilialEstado(codestado) {
    GTR_AjaxClick('detOndeEncontrar.php?codestado=' + codestado, 'conteudo');
}

moduloFaq = function (id,speed,selecionado) {

    if (typeof speed == 'undefined') {
        var speed = 0;
    }

    $j("#"+id+" h3 ~ div").slideUp(0);

    $j("#"+id+" h3").each(function (i) {

        var url = $j(this).attr('url');
        var cod = $j(this).attr('cod');

        if (url != ''){
            $j(this).bind('click', function() {
                if (url.search('http://') != -1) {
                    window.location = url;
                } else {
                    GTR_AjaxClick(url, 'conteudo');
                }
            });
        } else {
            $j(this).bind('click', function() {
                var display = $j(this).next().css('display');

                $j("#"+id+" h3 ~ div").slideUp(speed);
                $j("#"+id+" h3").removeClass('ativo');

                if (display != 'block') {
                    $j(this).addClass('ativo');
                    $j(this).next().slideToggle(speed);
                }
            });
        }

        if (cod == selecionado) {
            $j(this).addClass('ativo');
            $j(this).next().slideToggle(speed);
        }

    });

}
