/*
	funções deste arquivo
		init()					- inicialização das funções
		browserNS()				- verifica o suporte do browser.
		addFav()				- adiciona aos favoritos
		replacex()				- função replace consderando toda a string.
		printOpen()				- abre a janela de impressão.
		sendMail()				- abre a janela de enviar página por e-mail.
		maxlenght()				- valida os campos textarea de acordo com a propriedade maxlength.
		add0(value)				- adiciona um 0 a esquerda do valor (considerando total de 2 caracteres). Retorna string.
		f_date(obj)				- seta a hora em tempo real no objeto do parâmetro obj.
		menuproduto(obj)		- ajusta e aplica os eventos do menus / filtro de produtos.
		blockDataAdjust(obj)	- ajuste a lista de conteúdo em blocks - arquivo functions/templateBodyList - classe +block-data (utilizado em lista de notícias, etc)
		topMovie()				- executa a animação do topo da página
		menuLeft()				- executa a animação do menu a esquerda
*/
var jqDoc;
var jqWin;
var pagarea='';

var objBxCorner;
function init(){
	jqDoc=$('body');
	jqWin=$(window);

	var obj=null;
	
	obj = jqDoc.find('div#top_bx:eq(0)');
	obj.find('span#swftime:eq(0)').flash(
        { src: siteUrl+'/clock.swf', width: 29, height: 29,  wmode: 'transparent', menu: false },
        { version: 8 }
    );
	f_date(obj.find('span#time:eq(0)'));
	
	
	//*********** menu top *****************
	var topMenu_base=obj.find('ul#top_menu:eq(0)');
	var topMenu_over=$("<img src='"+siteUrl+"/image/top-menu-over.png' class='over' style='display:none;' />").insertBefore(topMenu_base);
	var topMenu_oSelect=null;
	var topMenu_oCur=null;
	var topMenu_oSub=null;
	var topMenu_oSub2=null;
	var topMenu_c=-1;
	setInterval(function(){
		//console.debug(topMenu_c)
		if(topMenu_c==0){
			topMenu_c=-1;
			topMenu_oSelect.trigger('mouseenter');
		}else if(topMenu_c>0){
			topMenu_c--;
		};
	},10);
	topMenu_oSelect = topMenu_base
		.find('>li')
		.each(function(){
			var o;
			
			o=$(this).find('>ul');
			if(o.length>0){
				//ícone do submenu
				$(this).append("<div class='icon'></div>");
				//ajuste da largura do submenu
				if(o.width()<200)o.width(200);
				
				
							//******* sub menu 2 ***********
							o.find('>li')
							.each(function(){
								if($(this).find('>ul').length>0)$(this).addClass('sub');
							})
							.bind({
								'mouseenter':function(){
									var li=$(this);
									var ul=li.find('>ul');
									if(ul.length>0){
										topMenu_oSub2=ul;
										ul.css({left:li.width()-1}).fadeIn();//,top:li.position().top
									};
								},'mouseleave':function(){
									if(topMenu_oSub2!=null)topMenu_oSub2.hide();
								}
							})
				
			};
			
			//correção do link vazio ou '#'
			o=$(this).find('>a:eq(0)');
			if(o.attr('href')=='' || o.attr('href')=='#')o.bind('click',function(){return false;})
		})
		.bind({//bind li
			'mouseenter':function(e){
				topMenu_c=-1;
				var li=$(this);
				var ul=li.find('>ul');
				
				//if(topMenu_oCur!=null)if(topMenu_oSub[0]!=ul[0])topMenu_oCur.removeClass('hideline').prev().removeClass('hideline');
				if(topMenu_oCur!=null)topMenu_oCur.removeClass('over');
				topMenu_oCur=li.addClass('over');

				if(topMenu_oSub!=null)if(topMenu_oSub[0]!=ul[0])topMenu_oSub.hide();
				topMenu_oSub=ul;
				
				//submenu2
				if(topMenu_oSub2!=null){topMenu_oSub2.hide();topMenu_oSub2=null};

				topMenu_over.stop().animate({
												left:li.position().left,
												width:li.width()		//+20+20 por causa do css padding left and right
											},
											'fast',
											function(){
												//li.addClass('hideline').prev().addClass('hideline');
												if(ul.length>0)ul.fadeIn();
										   })
				;
			},
			'mouseleave':function(e){
				topMenu_c=100;
			}
		})
		.eq(-1).addClass('last')//foca no último item
		.end()
		.filter(function(){ return $(this).find('>a:eq(0)').hasClass('over'); })//filtra o objecto over
	;
	 setTimeout(function(){ topMenu_oSelect.trigger('mouseenter').show(); },100);

	
	
	/************ top movie ******************/
	topMovie();
	
	
	
	/***********stats online*************/
	var statsCalc=function(){
		//prompt('',siteUrl+'/load.asp?pag=statsOnline&sx='+screen.width)
		$.ajax({
			type: "GET",
			url: siteUrl+'/load.asp',
			data: 'pag=statsOnline&sx='+screen.width,
			success: function(r){setTimeout(function(){statsCalc();},1000*60*5);}
		});
	};
	setTimeout(function(){statsCalc();},3000);
	
	
	//***************** para para as demais páginas (com excessão da página inicial) *****************
	if(!(window.location.href==siteUrl || window.location.href==String(siteUrl+'/'))){
		//console.debug('****')
		setTimeout(function(){
			//botões do corpo da página
			jqDoc.find('a.bt-print:first').bind('click',function(){printOpen();return false;});
			jqDoc.find('a.bt-mail:first').bind('click',function(){sendMail();return false;});
			
			//scroll para o conteúdo
			var o=jqDoc.find('div#menu-center:eq(0)');//var o=jqDoc.find('div#menu-center:eq(0)');
			if(o.length>0){
					var jqBodyHtml = $('html,body');
					//console.debug('####')
					//alert(11);//$.browser.name
					if($.browser.opera){
						//não faz nada
					}else{
						jqBodyHtml.animate({scrollTop:o.offset().top-25},700,function(){bxUnlock=true;o=null;});	//-20 - margin left
					};
			};
			
			//ajuste a lista de conteúdo em blocks - arquivo functions/templateBodyList - classe +block-data (utilizado em lista de notícias, etc) 
			blockDataAdjust(jqDoc.find('div#block-data:eq(0)'));
			
			/************ menu left movie ******************/
			//menuLeft(jqDoc.find('div#menu-left:eq(0)'));
			
			
			//************ controle de audio na pagina ***********
			jqDoc.find('a.audio').flash(
				{ src: siteUrl+'/flash/singlemp3player.swf', height: 20, width: 250 },
				{ version: 7 },
				function(htmlOptions) {
					htmlOptions.flashvars.file = $(this).attr('href');
					htmlOptions.flashvars.showDownload = "false";
					htmlOptions.flashvars.showDownload = "false";
					$(this).before($.fn.flash.transform(htmlOptions));						
				}
			).each(function(){
				//$(this).after("<span>"+$(this).text()+"</span>");
				$(this).remove();
			});
			
			//************ controle de video na pagina ***********
			var objm=jqDoc.find('a.video');
			var jsLoadedMedia=false;
			if(objm.length>0){
				if(jsLoadedMedia==false){
					//carrega o player do vídeo. Obs.: o css player do vídeo já foi carregado na inicialização do sistema.
					$.getScript(siteUrl+'/js/jwplayer.js',function(){//carregou o js do vídeo
							jsLoadedMedia=true;
							f_mediaStart(objm);
					});
				}else{
					f_mediaStart(objm);
				};
			};
	
		},0);
	};
	
	
	/******* para a página de produtos - menuright - css: .bx-produtos **************/
	
};


var f_mediaStart=function(obj){//função de inicialização de vídeos na página
	/*	parâmetros:
			obj:	coleção jquery de objetos audio/video
	*/
	var oCurr=null;
	obj.each(function(){
		var oo=$(this);
		jwplayer(oo.attr('idref')).setup({
			flashplayer: siteUrl+"/flash/player.swf",
			file: oo.attr('href'),
			width:640,
			height:390,
			events:{
				onPlay:function(){
					if(oCurr!=null)if(oCurr!=this)oCurr.pause();
					oCurr = this;
				}
			}
		});
		//oo.remove();
	});
	
	//seta para o coletor de lixo
	obj=null;
};




function browserNS(){//browser not support
	if($.browser.msie)if($.browser.version<=6){
		var html="";
		var navigador="Internet Explorer"
		html += "<div class='table'><table width='100%' border='0' cellpadding='0' cellspacing='0' align='center'>";
			html += "<tr><td colspan='5'>"
				html += "<p><img src='"+siteUrl+"/arquivos/logo.jpg' /><br><br>Este sistema não oferece suporte ao navegador que você está utilizando: "+ navigador +" "+ $.browser.version +".";
				html += "<br />Para prosseguir é necessário atualizar seu navegador para um mais moderno.</p>";
			html += "</td></tr>";
			html += "<tr>"
				html += "<td><a class='ie' href='http://www.microsoft.com/windows/internet-explorer/default.aspx' target='_blank' title='Internet Explorer'>Internet Explorer</a></td>";
				html += "<td><a class='ff' href='http://www.mozilla.com/pt-BR/' target='_blank' title='FireFox'>FireFox</a></td>";
				html += "<td><a class='chrome' href='http://www.google.com/chrome/' target='_blank' title='Chrome'>Chrome</a></td>";
				html += "<td><a class='safari' href='http://www.apple.com/safari/' target='_blank' title='Safari'>Safari</a></td>";
				html += "<td><a class='opera' href='http://www.opera.com/browser/' target='_blank' title='Opera'>Opera</a></td>";
			html += "</tr>";
		html += "</table></div>";
		
		jqDoc.addClass('browserNS').html(html);
		
		html=null;
		navigador=null;
		
		return false;
	};
	return true;
};

function addFav(){
    var url      = siteUrl
    var title    = siteNameLabel
	if(navigator.userAgent.search(/(Chrome)[ \/]([\w.]+)/)>0){//chrome
		var e=window.event;
		alert('Pressione Ctrl+D para adicionar aos favoritos (Command+D para macs) Logo após clicar em OK.');
	}else{//demais browsers
		if (window.sidebar) window.sidebar.addPanel(title, url,"");
		else if(window.opera && window.print){
			var mbm = document.createElement('a');
			mbm.setAttribute('rel','sidebar');
			mbm.setAttribute('href',url);
			mbm.setAttribute('title',title);
			mbm.click();
		}else if(document.all){window.external.AddFavorite(url, title);}
	};
};


function replacex(text,sfind,sreplace){var r=text; for(var i=0;i<text.length;i++){r = r.replace( sfind, sreplace);} return r; }//replace geral
function printOpen(){
	var w = 750; var h = 550;
	var l = screen.width/2 - w/2; l=parseInt(l);
	var t = screen.height/2 - h/2; t=parseInt(t);
	var winPrint = window.open(siteUrl+'/print.asp','print','width='+w+',height='+h+',top='+t+',left='+l+',scrollbars=1,status=no,menubar=1');
	if (window.focus){winPrint.focus();}
};
function sendMail(){
	var w = 700; var h = 380;
	var l = screen.width/2 - w/2; l=parseInt(l);
	var t = screen.height/2 - h/2; t=parseInt(t);
	var winSendMail = window.open(siteUrl+'/sendMail.asp','print','width='+w+',height='+h+',top='+t+',left='+l+',scrollbars=1,status=no,menubar=0');
	if (window.focus){winSendMail.focus();}
};
function maxlenght(selector){//valida os campos textarea de acordo com a propriedade maxlength
	$(selector).bind('blur keypress',function(){
		var limite=$(this).attr('maxlength');
		if(limite!=undefined && isNaN(limite)==false){
			limite=parseFloat(limite);
			if(limite>0 && $(this).val().length>limite){$(this).val( $(this).val().substring(0,limite) );return false;}//obj.value=obj.value.substring(0,limite);
		}
	});
};

function add0(v){if(v.toString().length==1){return '0'+v;}else{return v;}};//adiciona um 0 a esquerda do valor (considerando total de 2 caracteres). Retorna string.

function f_date(obj){
	var oDate={
		o:	null,
		h:	0,
		m:	0,
		s:	0
	};
	
	setInterval(function(){
		oDate.o=new Date();
		oDate.h = oDate.o.getHours();
		oDate.m = oDate.o.getMinutes();
		oDate.s = oDate.o.getSeconds();
		if (oDate.m<=9)oDate.m="0"+oDate.m;
		if (oDate.s<=9)oDate.s="0"+oDate.s;
		obj.html(''+oDate.h + "h " + oDate.m + ":" + oDate.s+"");
	},1000);
};


function menuproduto(palco){
	if(palco.length>0){
		var o=null;
		var uls=palco.find('a.title:not(#not)').bind('click',function(e){
			e.preventDefault();
			
			o = $(this).next().slideDown();
			uls.filter(function(){ return $(this)[0]!=o[0] }).slideUp();
			
		})
		.each(function(){ if($(this).hasClass('over')){o=$(this);return false;} })
		.next();//retorna a todos objetos UL
		
		if(o!=null)o.trigger('click');
	};
};


function blockDataAdjust(palco){//palco = each $('div#block-data')
	//*************** center - ajuste a lista de conteúdo em blocks - arquivo functions/templateBodyList - classe +block-data (utilizado em lista de notícias, etc) ********************
	if(palco.length>0)
		palco.each(function(){
			var opt=$(this).attr('opt');
			var itens=$(this).find('>div.item');
			if(opt!=undefined && opt!='' && opt!=null){
				opt=eval('('+opt+')');
			}else{
				opt={col:3}
			};
			var th;
			var i=0;
			var h=0;
			
			itens.each(function(count){
					th=$(this);
					if(th.hasClass('not')){
						//não calcula a altura
					}else{
						if(h<th.height())h=th.height();
						
						i++;
						if(i>=opt.col){
							//ajusta a altura do objeto atual + 2 objetos anteriores
							h+=5;//+5 = margin bottom;
							
							itens.eq(count).height(h);
							itens.eq(count-1).height(h);
							itens.eq(count-2).height(h);
							//console.debug(h)
							
							i=0;
							h=0;
						};
						//console.debug(bc_v.o.)
					};
					
			});
			th=null;
			h=null;
			i=null;
			opt=null;
			itens=null;
		})
	;
};


function topMovie(){
	var o=jqDoc.find('div#movietop:eq(0)');
	if(o.length==0)return false;

	var v={
		width:950,//623
		height:200,
		control:0,
		total:0,
		delay:0,		//temoo exibiação entre os quadros
		speedy:200,		//velocidade da animação do scroll
		pos:[],
		i:0,
		count:0,
		clicked:false
	};
	var o2=o.wrapInner('<div class="palco" />').find('>.palco:eq(0)');
	v.total = o2.find('>div.item')
				.each(function(){
					v.pos[v.pos.length]=v.width*v.i;
					v.i++;
				})
				/*.bind('mouseenter mouseleave',function(e){
					if(e.type=='mouseenter'){
						$(this).animate({'opacity':1.0},500);
					}else{
						$(this).animate({'opacity':0.85},100);
					}
				})*/
				.length
	;
	
	if(v.total==0)return false;
	o2.css({width:(v.width*v.total)});
	
	var f_mov=function(){
		
		if(v.control >= v.total){v.control=v.total-1;};
		if(v.control < 0){v.control=0;};
		
		o2.stop().animate({"left":"-"+v.pos[v.control]+"px"},v.speedy);
	};

	//efeito alpha left right
	//o.append("<div class='alphaL'></div><div class='alphaR'></div>");
	//console.debug(o)
	
	//inicializa com a função
	v.count=0;
	v.delay=850;
	setInterval(function(){ 
		v.count++;
		if(v.count>v.delay){
			v.count=0;
			if(v.clicked==false){
				v.control++;
				if(v.control >= v.total){v.control=0;};
			};
			v.clicked=false;
			f_mov();
		};
	},1);
	
	//botões left right
	var v1=0;//variável de controle dos botões abaixo 'btLR'
	var btLR = $("<img src='"+siteUrl+"/image/movietop_btL.png' id='btLeft' /><img src='"+siteUrl+"/image/movietop_btR.png' id='btRight' />").appendTo(o).hide();
	setTimeout(function(){
		btLR
			.bind('click',function(){
				if($(this).attr('id')=='btLeft'){
					v.control--;
					v.count=v.delay;
					if(v.control < 0){v.control=v.total-1;};
					v.clicked=true;
				}else{
					btLR.css('z-index','9');
					v.control++;
					v.count=v.delay;
					if(v.control >= v.total ){v.control=0;};
					v.clicked=true;
				};
				f_mov();
			})
			.show()
			//.css('alh','1')
			.bind('mouseover mouseleave',function(e){
				if(e.type=='mouseover'){
					//$(this).animate({'opacity':1.0},500);
					v1=1;
					$(this).stop().animate({width:49,height:49,top:76,marginLeft:-6},200);
				}else{
					//$(this).animate({'opacity':0.6},500);
					v1=0;
					var oo=$(this);
					setTimeout(function(){
						if(v1==0)oo.stop().animate({width:37,height:37,top:84,marginLeft:0},100);
						oo=null;
					},50);
				}
			})
			/*.animate({'opacity':0.6},1000);*/
		;
	},100);

};


function menuLeft(obj){
	if(obj.length>0){
		//console.debug(obj)
		var uls;
		var tmp;
		
		obj.find('>div:eq(1)>h3')
		.each(function(){
			tmp = $(this).next().hide();
			$(this).data('ul',tmp);
			if(uls==undefined){uls=tmp}else{uls = uls.add(tmp);};
		})
		.bind({
			'click':function(e){
				e.stopPropagation();
				e.preventDefault();
				
				var ul = $(this).data('ul');
				//console.debug(ul)
				if(ul.length>0){
					ul.stop().slideDown();
				};
				uls.filter(function(){ return $(this)[0]!=ul[0] }).stop().slideUp();
				
			}
		});
	};
};




