Number.implement({
	toReal:function(){
		num = this;
		dec = 2;
		thou = '.';
		pnt = ',';
		curr1 = '';
		curr2 = '';
		n1 = '';
		n2 = '';
		x = Math.round(num * Math.pow(10,dec));
		if (x >= 0)
			n1=n2='';
		y = (''+Math.abs(x)).split('');
		z = y.length - dec;
		if (z<0)
			z--;
		for(i = z; i < 0; i++){
			y.unshift('0');
		}
		y.splice(z, 0, pnt);
		if(y[0] == pnt){
			y.unshift('0');
		}
		while (z > 3) {
			z-=3;
			y.splice(z,0,'.');
		}
		r = curr1 + n1 + y.join('') + n2 + curr2;
		return r;
	}
});

Fx.Scroll = new Class({

	Extends: Fx,

	options: {
		offset: {x: 0, y: 0},
		wheelStops: true
	},

	initialize: function(element, options){
		this.element = this.subject = document.id(element);
		this.parent(options);
		var cancel = this.cancel.bind(this, false);

		if ($type(this.element) != 'element') this.element = document.id(this.element.getDocument().body);

		var stopper = this.element;

		if (this.options.wheelStops){
			this.addEvent('start', function(){
				stopper.addEvent('mousewheel', cancel);
			}, true);
			this.addEvent('complete', function(){
				stopper.removeEvent('mousewheel', cancel);
			}, true);
		}
	},

	set: function(){
		var now = Array.flatten(arguments);
		if (Browser.Engine.gecko) now = [Math.round(now[0]), Math.round(now[1])];
		this.element.scrollTo(now[0] + this.options.offset.x, now[1] + this.options.offset.y);
	},

	compute: function(from, to, delta){
		return [0, 1].map(function(i){
			return Fx.compute(from[i], to[i], delta);
		});
	},

	start: function(x, y){
		if (!this.check(x, y)) return this;
		var scrollSize = this.element.getScrollSize(),
			scroll = this.element.getScroll(), 
			values = {x: x, y: y};
		for (var z in values){
			var max = scrollSize[z];
			if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z] : max;
			else values[z] = scroll[z];
			values[z] += this.options.offset[z];
		}
		return this.parent([scroll.x, scroll.y], [values.x, values.y]);
	},

	toTop: function(){
		return this.start(false, 0);
	},

	toLeft: function(){
		return this.start(0, false);
	},

	toRight: function(){
		return this.start('right', false);
	},

	toBottom: function(){
		return this.start(false, 'bottom');
	},

	toElement: function(el){
		var position = document.id(el).getPosition(this.element);
		return this.start(position.x, position.y);
	},

	scrollIntoView: function(el, axes, offset){
		axes = axes ? $splat(axes) : ['x','y'];
		var to = {};
		el = document.id(el);
		var pos = el.getPosition(this.element);
		var size = el.getSize();
		var scroll = this.element.getScroll();
		var containerSize = this.element.getSize();
		var edge = {
			x: pos.x + size.x,
			y: pos.y + size.y
		};
		['x','y'].each(function(axis) {
			if (axes.contains(axis)) {
				if (edge[axis] > scroll[axis] + containerSize[axis]) to[axis] = edge[axis] - containerSize[axis];
				if (pos[axis] < scroll[axis]) to[axis] = pos[axis];
			}
			if (to[axis] == null) to[axis] = scroll[axis];
			if (offset && offset[axis]) to[axis] = to[axis] + offset[axis];
		}, this);
		if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y);
		return this;
	},

	scrollToCenter: function(el, axes, offset){
		axes = axes ? $splat(axes) : ['x', 'y'];
		el = $(el);
		var to = {},
			pos = el.getPosition(this.element),
			size = el.getSize(),
			scroll = this.element.getScroll(),
			containerSize = this.element.getSize(),
			edge = {
				x: pos.x + size.x,
				y: pos.y + size.y
			};

		['x','y'].each(function(axis){
			if(axes.contains(axis)){
				to[axis] = pos[axis] - (containerSize[axis] - size[axis])/2;
			}
			if(to[axis] == null) to[axis] = scroll[axis];
			if(offset && offset[axis]) to[axis] = to[axis] + offset[axis];
		}, this);
		if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y);
		return this;
	}

});

function popup_img(p, f) {
	u = 'http://www.rjhost.com.br/popupimagens/path/img.html';
	u = u.replace(/(path)/, p);
	u = u.replace(/(img)/, f);
	window.open(u, 'imgRjHost', 'width=493, height=335'), void(0);
}
function open_chat(dep) {
	if(window.faloutudo){
		$('chat').reveal({duration:'long',onComplete:$empty});
	}else{
		abrir_chat();
	}
	/*
	unico = new Date().getTime();
	window.open('http://onchat.rjhost.net/request.php?l=onxad0rJ&x=1&deptid=0', unico, 'width=450, height=350');
	return false;
	*/
}
function popup(url){
	j = window.open(url, 'construtorRJHOST', 'width=780, height=560');	
	j.focus();
}

function escrever_mensagem(onde, mensagem){
	timers = [];
	for(i=0;i<=mensagem.length;i++){
		a = (function(el, saudacao_letra){
			$(el).set('html', $(el).get('html') + saudacao_letra );
		}).delay( (i+1)*100, null, [ onde, mensagem.substr(i,1) ] );
		timers.push(a);
	}
	return [i,timers];
}

var getSis = new Class({
	initialize:function(){
		$('frmlogin').set('action', $('frmlogin').get('action').replace('painel/login', 'getsis') );
		$('frm_login_adm').set('action', $('frmlogin').get('action').replace('painel/login', 'getsis') );
		$('frmlogin').adopt(
			new Element('input',{
				'type':'hidden',
				'id':'operation',
				'name':'operation',
				'value':'login'}
			)
		);
		$('frm_login_adm').adopt(
			new Element('input', {
				'type':'hidden',
				'id':'operation',
				'name':'operation',
				'value':'sis'
			})
		);
		$('frmlogin').addEvent('submit',function(evt){
			new Event(evt).stop();
			$$('#frmlogin input[type=submit]').setProperty('value','Aguarde...');
			$$('#frmlogin input[type=submit]').setProperty('disabled','disabled');
			new Request({
				url: $('frmlogin').get('action'),
				onSuccess:function(r){
					resposta = JSON.decode(r);
					if( resposta.resp === false ){
						if( $('erroajx') == null ){
							new Element('div',{
								'id':'erroajx',
								'styles':{
									'border':'1px solid red',
									'background-color':'#FFCC99',
									'padding':'5px',
									'margin':'50px auto 0px auto',
									'display':'block',
									'width' : '200px',
									'position':'absolute'
								}
							}).inject($('box_c'),'top');
						}
						$('erroajx').set('html', resposta.msg);
						(function(){$('erroajx').nix()}).delay(5000);
						$$('#frmlogin input[type=submit]').set('value','Enviar');
						$$('#frmlogin input[type=submit]').removeProperty('disabled');
					}else{
						if( $('erroajx') !== null ){
							$('erroajx').destroy();
						}
						$('box_c').setStyle('display', 'none');
						$('box_nc').setStyle('display', 'none');
						$('box_d').setStyle('display', 'block');
						$$('#box_d strong.sis_dom').each(function(el){el.set('text',resposta.domain)});
						$('box_escolha').tween('height', 320);
					}
				}
			}).send({
				method:'post',
				data:$('frmlogin').toQueryString()
			});
		});
		$('frm_login_adm').addEvent('submit', function(evt){
			new Event(evt).stop();
			$$('#frm_login_adm input[type=submit]').setProperty('value','Aguarde...');
			$$('#frm_login_adm input[type=submit]').setProperty('disabled','disabled');
			new Request({
				url: $('frm_login_adm').get('action'),
				onComplete:function(r){
					var resposta = JSON.decode(r);
					if( resposta.resp === false ){
						if( $('erroajxsis') == null ){
							new Element('div',{
								'id':'erroajxsis',
								'styles':{
									'border':'1px solid red',
									'background-color':'#FFCC99',
									'padding':'5px',
									'margin':'50px auto auto 135px',
									'display':'block',
									'width' : '300px',
									'position':'absolute'
								}
							}).inject($('box_d'),'top');
						}
						$('erroajxsis').set('html',resposta.msg);
						(function(){$('erroajxsis').nix()}).delay(5000);
						$$('#frm_login_adm input[type=submit]').set('value','Enviar');
						$$('#frm_login_adm input[type=submit]').removeProperty('disabled');
					}else{
						if( $('erroajxsis') !== null ){
							$('erroajxsis').dix();
						}
						$('box_d').setStyle('display', 'none');
						$('box_resp').setStyle('display', 'block');
						$('box_escolha').tween('height', 120);
					}
				}
		   }).send({
			   method: 'post',
			   data: $('frm_login_adm').toQueryString()
		   });
		});
	}
});

window.msgtimers = [];

window.faloutudo = false;

new MTKonamicode({
	onWin: function(){
		window.konami = true;
		$$('#chat .forms_fotos_fotos img')[0].set('src','/css/imagens/chat/foto_egg.gif');
		$$('#forms_fotos_form div')[0].empty();
		window.msgtimers.each(function(e){e=$clear(e)});
		(function(){
			h = new Date().get('hours');
			saudacao = h < 12 ? 'Bom dia brother.' : ( h < 18 ? 'Koé mermão, boa tarde aé.' : 'Que lua brother.');
			$('forms_fotos_form').getElement('div').adopt(
				new Element('p',{html:'<span><strong>Rafael </strong><small>diz:</small></span><br /> <span id="saudacao1"></span>'})
			);
			i = escrever_mensagem('saudacao1',saudacao);
			(function(){
				$('forms_fotos_form').getElement('div').adopt(
					new Element('p',{html:'<span><strong>Rafael </strong><small>diz:</small></span><br /> <span id="saudacao2"></span>'})
				);
				saudacao_2 = 'Qual foi? O que tá pegando?';
				escrever_mensagem('saudacao2',saudacao_2);
			}).delay( ( i[0]+1 )*100 + 2000 );
		}).delay(1000);
	}
});

function chat_barra(){
	$('chatreq').setStyle('display','block');
	$('chatreq').fade('hide');
	(function(){$('chatreq').fade('in')}).delay(5000);
	$('hlp_open').addEvent('click',function(){
		open_chat()
	});
	$('hlp_close').addEvent('click',function(){
		$('chatreq').fade('out');
	});
}

function abrir_chat(){
	$('referer_page').set('value',window.location.href);
	$('chat').set('reveal',{
		onComplete:function(){
			if(window.konami || window.faloutudo){
				return true;
			}
			$$('#chat .fechar').addEvent('click',function(){
				$('chat').dissolve({
					duration:'long',
					onComplete:function(){
						Cookie.write('chat_fechado','sim',{duration:1});
						if( $('chatreq').get('opacity') == 0 ){
							chat_barra();
						}
					}
				});
			});
			d = (function(){
				h = new Date().get('hours');
				saudacao = h < 12 ? 'Bom dia.' : ( h < 18 ? 'Boa tarde.' : 'Boa noite.');
				$('forms_fotos_form').getElement('div').adopt(
					new Element('p',{html:'<span><strong>Atendente </strong><small>diz:</small></span><br /> <span id="saudacao1"></span>'})
				);
				for(i=0;i<=saudacao.length;i++){
					a = (function(saudacao_letra){
						$('saudacao1').set('html', $('saudacao1').get('html') + saudacao_letra );
					}).delay( (i+1)*100, null, saudacao.substr(i,1) );
					window.msgtimers.push(a);
				}
				b = (function(){
					$('forms_fotos_form').getElement('div').adopt(
						new Element('p',{html:'<span><strong>Atendente </strong><small>diz:</small></span><br /> <span id="saudacao2"></span>'})
					);
					saudacao_2 = 'Em que posso ajudar?';
					for(j=0;j<=saudacao_2.length;j++){
						c = (function(saudacao_letra){
							$('saudacao2').set('html', $('saudacao2').get('html') + saudacao_letra );
							window.faloutudo = true;
						}).delay( (j+1)*100, null, saudacao_2.substr(j,1) );
						window.msgtimers.push(c);
					}
				}).delay( (i+1)*100 + 2000 );
				window.msgtimers.push(b);
			}).delay(1000);
			window.msgtimers.push(d);
		}
	}).reveal();

	new Form.Validator($('chatform'),{
		evaluateFieldsOnBlur:false,
		onFormValidate: function(passou){
			if(passou){
				$$('#chat .fechar').fireEvent('click');
				window.open('about:blank', 'chatwindow', 'width=455, height=365');
				$('chatform').submit();	
			}else{
				alert('Verifique os campos, parece qua faltou você preencher algum.');	
			}
		}
	});
}

window.addEvent('domready',function(){
	a_hora = new Date().get('hours').toInt();
	if( $$('.disable_chat').length ){
		//faz nada
	}else{
		if( $('chatreq') && (a_hora <= 7 || a_hora >= 21) ){
			chat_barra();
		}
		if( $('chat') && (a_hora >= 8 && a_hora <= 20)){
			if( Cookie.read('chat_fechado') === null ){
				abrir_chat.delay(5000);
			}else{
				chat_barra();
			}
		}
	}
	if( document.location.protocol === 'http:' ){
		new Element('img',{
			src: (document.location.protocol)+'//onchat.rjhost.net/image.php?l=onxad0rJ&x=1&deptid=0&unique='+ new Date().getTime() +'&refer=&text=text&page='+window.location.href,
			alt: 'Clique aqui para ser atendido.',
			border:0
		}).inject($$('body')[0],'bottom');
	}
	
	new MenuMatic({id:'menutopo',direction:{x: 'left',y:'down'}});
	/* mouse over nos destaques na home*/
	$$('.planos-grp').addEvents({
		'mouseover':function(){
			a = $('balao_' + this.get('class').split(' ')[0]);
			if(a.getStyle('display') == 'none')
				a.setStyles({display:'block',opacity:0});
			a.fade( Browser.Engine.trident ? 'show' : 'in');
		},
		'mouseleave':function(){
			$('balao_' + this.get('class').split(' ')[0]).fade(Browser.Engine.trident ? 'hide' : 'out');
		}
	});
	/*zebra nos planos*/
	$$('#planos tr:odd td').setStyle('background-color','#fff');
	/* dedicados */
	if( $('form-dedicados') ){
		$('errorbox-ded').setStyle('opacity',0);
		$('form-dedicados').addEvent('submit',function(e){
			new Event(e).stop();
			new Request.JSON({
				url: $('form-dedicados').get('action'),
				onSuccess:function(r){
					if( $('errorbox-ded').getStyle('opacity') == 1){
						//tira a mensagem de erro anterior se tiver
						$('errorbox-ded').empty();
						$('errorbox-ded').effect('opacity').start(1,0);
					}
					if(r.errors){
						errors = '';
						r.error_list.each(function(er){
							errors += '<li>' + er + '</li>';
						});
						$('errorbox-ded').set('html','<ul style="margin:0">'+ errors +'</ul>').fade('in');
					}else{
						d = new Element('div',{
							styles:{
								'width':530,
								'border':'1px solid #45970E',
								'background-color':'#94DA00',
								'padding':10,
								'margin':'auto',
								'color':'#265F00',
								'font-weight':'bold',
								'font-size':12,
								'opacity':0
							}
						}).set('html','Obrigado por preencher o formulário, em breve nossa equipe entrará em contato.').injectBefore('p-btsend');
						d.adopt(
							new Element(
								'iframe',{
									src:'http://www.rjhost.com.br/contabiliza_dedicados.html',
									width:200,
									height:30,
									marginwidth:0,
									marginheight:0,
									scrolling:"no",
									frameborder:0,
									styles:{
										width:200,
										height:30,
										'margin-left':155,
										'margin-top':10
									}
								}
							)
						);
						d.fade('in');
						$('p-btsend').fade('out');
					}
				}
			}).send({
				method:'post',
				data: $('form-dedicados').toQueryString()
			});
		});
	}
	/* sis facil */
	if($('box_escolha')){
		$('sol-sis').addEvent('click',function(){
			$('box_escolha')[ $chk($('box_escolha').retrieve('reveal')) ? ($('box_escolha').retrieve('reveal').hidden ? 'reveal' : 'dissolve') : 'reveal' ]();
		});
		new getSis();
	}
	/* text indent */
	$$('.txt-id').each(function(el){
		el.setStyle('text-indent',-5000);
	});
	/* página de busca domínio */
	if($('header_busca_dominio')){
		var f = $('busca_dominio');
		var dominio = $('dominio_avail').get('value');
		
		$$('.bt-assinar').addEvent('click', function(ev){
			new Event(ev).stop();
			$('busca_dominio').set('action',this.get('href'));
			$('dominio_avail').set('name','__dominio_avail');
			$('busca_dominio').submit();
		});
		
		new Request.JSON({
			url: f.get('action'),
			data: f.toQueryString(),
			onSuccess: function(r){
				/*esconde o pesquisando*/
				$$('.add_dom').set('html', dominio);
				if( $type(r.avail) === 'object' ){
					/*dominio disponível pra registro*/
					$$('.final_dom').set('html', $('dominio_avail').get('value'));
					$$('.planos')[0].reveal().get('reveal');
					$('valor_dominio').set('html', 'R$ ' + $H(r.valor).getValues()[0].toFloat().toReal() );
				}else{
					/*dominio indisponível*/
					un_domain = $H(r.unavail).getKeys()[0];
					other_options = ['com','com.br','net','info','adv.br','org'].erase(un_domain);
					domain_prefix = dominio.replace('.'+un_domain,'');
					o_tbody = $('other_domains').getElement('tbody')
					other_options.each(function(exts, contador){
						ext_id = 'p_' + exts.replace('.','_');
						tr = new Element('tr',{
							'id': ext_id,
							'class': ( (contador % 2) ? 'par' : 'impar')
						}).adopt(
							new Element('td',{'html': domain_prefix + '<strong>.' + exts + '</strong>'}),
							new Element('td',{'class': 'js_status', 'html': 'Aguarde...'}),
							new Element('td',{'html': 'Realizando busca, aguarde....'})
						);
						tr.store('extensao', exts);
						o_tbody.adopt(tr);
						/*depois de montada a tabela é hora de realizar a busca*/
						new Request.JSON({
							url: f.get('action'),
							data: 'dominio_avail=' + domain_prefix + '.' + exts,
							onSuccess: function(s){
								ext_id_l = 'p_' + exts.replace('.','_');
								o_td = $$('#' + ext_id_l + ' td');
								
								is_avail = $type(s.avail) === 'object';
								$(ext_id_l).addClass(is_avail ? 'd_avail' : 'd_unavail');
								
								if(is_avail){
									o_td[1].set('html','Dispon&iacute;vel'),
									o_td[2].set('html', 'Registre por apenas <span>R$ ' + s.valor[exts].toFloat().toReal() + '</span><a href="javascript:void(0);" id="l_'+ext_id_l+'"><img src="/css/imagens/btn_registro_dominio.gif" /></a>');
									$('l_'+ext_id_l).addEvent('click',function(){
										ext = this.getParent().getParent().retrieve('extensao');
										$('dominio_avail').set('value', domain_prefix+'.'+ext);
										$$('.final_dom').set('html', domain_prefix+'.'+ext);
										$$('.planos')[0].reveal().get('reveal').chain(function(){
											new Fx.Scroll(document.body).toElement($$('.planos')[0]);
										});
									});
								}else{
									o_td[1].set('html', 'Indispon&iacute;vel'),
									o_td[2].set('html', 'Este dom&iacute;nio j&aacute; est&aacute; registrado');
								}
							}
						}).send();
					});
				}
				$('buscando').dissolve().get('reveal').chain(function(){
					$$('.' + ($type(r.avail) === 'object' ? '' : 'in') + 'disponivel').reveal();
				});
			}
		}).send();
	}
});
window.addEvent('load',function(){
	if( !Browser.Engine.trident )
		new OverText($('q'));
});
