/*
 * Desenvolvido por Leandro Sales
 * leandroasp at gmail dot com
 * +55 86 94275626
 * http://www.leandrosales.com.br
 *
 * Reprodução autorizada desde que mantenha os créditos
 */
 
if (document.location.href.indexOf('http://localhost/') != -1) {
	var localURL = '/Teens180/www/';
} else {
	var localURL = '/';
}

if (!String.prototype.trim) String.prototype.trim = function() {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
	i || (i = 0);
	var length = this.length;
	if (i < 0) i = length + i;
	for (; i < length; i++)
		if (this[i] === item) return i;
	return -1;
};

var LSL;
if (!LSL) {
	LSL = {};
}

/*
 * Retorna o objeto com o elemento
 */
$L = function(element) {
	if (element && typeof element == "string")
		return document.getElementById(element);
	return element;
};

LSL.addCSS = function(element, css) {
	var style = element.style || element
	for(var obj in css) {
		eval('style.' + obj + '=\'' + css[obj] + '\'');
	}
}

/*
 * Limita a quantidade de caracteres em um campo textarea
 */
LSL.limitCaracter = function(opt) {
	if (!opt.field) return;
	if (!opt.maxChar) opt.maxChar = 4096;
	if (opt.countElement) opt.countElement = $L(opt.countElement);

	opt.field = $L(opt.field);
	var e = opt.e ? opt.e : window.event;

	var tecla;
	if (e.keyCode) tecla = e.keyCode;
	else if (e.which) tecla = e.which;
	
	var x = opt.field.value.replace(/\n/g," ").length;
	if (x >= opt.maxChar && (tecla >= 32 || tecla == 13)) {
		opt.field.value = opt.field.value.substring(0, opt.maxChar);
		return false;
	}
	if (opt.countElement) {
		opt.countElement.innerHTML = opt.maxChar - x;
	}
};

/*
 * AJAX
 * Ex:
 *   new LSL.AJAX.Event({
						url: url que enviara os dados,
						resultElement: element que receberar o resultado,
						data: dados que serao enviados,
						onCreate: funcao que sera chamada quando iniciar, 
						onComplete: funcao que sera chamada quando terminar. será enviado o objeto com o resultado.
						});
 * Só é obrigatorio a URL.
 */
if (!LSL.AJAX) {
	LSL.AJAX = {};
}
LSL.AJAX.Event = function(opt) {
	this.init(opt);
};
LSL.AJAX.Event.prototype.init = function(opt) {
	if (!opt.url) return;

	this.url = opt.url;
	this.resultElement = (opt.resultElement?$($L(opt.resultElement)):null);
	this.data = opt.data || '';

	this.onCreate = opt.onCreate;
	this.onComplete = opt.onComplete;
	
	if (this.onCreate) {
		this.onCreate();
	}
	this.send();
};
LSL.AJAX.Event.prototype.createAjaxObject = function() {
	if (!this.ajaxObj) {
		var obj;
		try {
			obj = new XMLHttpRequest();
		} catch(e1) {
			try {
				obj = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e2) {
				try {
					obj = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e3) {
					alert("Seu navegador não suporta AJAX!");
					obj = false;
				}
			}
		}
		this.ajaxObj = obj;
	}
};
LSL.AJAX.Event.prototype.send = function() {
	this.createAjaxObject();
	clearTimeout(this.ajaxRequestTimer);

	var self = this;
	this.ajaxObj.open("POST", this.url, true);
	
	this.ajaxObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=iso-8859-1');
	this.ajaxObj.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	this.ajaxObj.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	this.ajaxObj.setRequestHeader("Pragma", "no-cache");

	this.ajaxObj.onreadystatechange = function() {
		try {
			if (self.ajaxObj.readyState!=4) return;

			clearTimeout(self.ajaxRequestTimer);
			if (self.ajaxObj.status==200) {
				//alert('deu: ' + self.data);
				if (self.resultElement) {
					self.resultElement.html(self.ajaxObj.responseText);
				}
			} else {
				//alert('ERRO: \n' + self.ajaxObj.statusText);
			}
			if (self.onComplete) {
				self.onComplete(self.ajaxObj);
			}
			self.cancel();
		} catch (e) {
			if (self.onComplete) {
				self.onComplete(null);
			}
			self.cancel();
			//alert('ERRO: \n' + e);
		}
	};
	this.ajaxObj.send(this.data);

	this.ajaxRequestTimer = setTimeout(function() {
		self.cancel();
		//alert("Ocorreu um erro na sua conexão ou ela está muito lenta!\nAtualize a página e tente novamente.");
     }, 30000);
};
LSL.AJAX.Event.prototype.cancel = function() {
	try {
		this.ajaxObj.abort();
		this.ajaxObj = null;
	} catch (e) {}
};
/*FIM AJAX*/
/********************/

/*
 * ThickBOX By Leandro Sales
 */
var msie6 = 
        !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1)
        && /MSIE 6\.0/i.test(window.navigator.userAgent) 
        && !/MSIE 7\.0/i.test(window.navigator.userAgent);
LSL.ThickBoxCreate = function(url) {
	/*Parametros que podem ser alterados*/
	var WIDTH = 350;
	var HEIGHT = 400;
	var IMG_LOADING = localURL + 'images/loading.gif';
	/***********************************/
	
	
	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		LSL.addCSS(document.getElementsByTagName('html')[0], {height: "100%", width: "100%", overflow: "hidden"});
		LSL.addCSS(document.body, {height: "100%", width: "100%"});

		var iframe = $L('_IFRAME_BOX_SUSPENSED_');
		if (iframe === null) {
			iframe = document.createElement('iframe');
			iframe.id = '_IFRAME_BOX_SUSPENSED_';
			LSL.addCSS(iframe, {
				zIndex: '99',
				position: (msie6?'absolute':'fixed'),
				top: '0',
				left: '0',
				backgroundColor: '#fff',
				border: 'none',
				filter: 'alpha(opacity=0)',
				MozOpacity: '0',
				opacity: '0',
				height: (msie6?(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'):'100%'),
				width: '100%'
			});
			document.body.appendChild(iframe);
		} else {
			LSL.addCSS(iframe, {display: 'block'});
		}
	}
	
	if ($L("_DIV_BG_BOX_SUSPENSED_") === null){
		var div_bg = document.createElement('div');
		var div_window = document.createElement('div');
		div_bg.id = '_DIV_BG_BOX_SUSPENSED_';
		div_window.id = '_DIV_WINDOW_BOX_SUSPENSED_';

		LSL.addCSS(div_bg, {
			position: (msie6?'absolute':'fixed'),
			zIndex: '100',
			top: '0px',
			left: '0px',
			height: (msie6?(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'):'100%'),
			width: '100%'
		});

		var userAgent = navigator.userAgent.toLowerCase();
		if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
			LSL.addCSS(div_bg, {
				background: 'url(macFFBgHack.png) repeat'
			});
		} else {
			LSL.addCSS(div_bg, {
				backgroundColor: '#000',
				filter: 'alpha(opacity=75)',
				MozOpacity: '0.75',
				opacity: '0.75'
			});
		}
		LSL.addCSS(div_window, {
			position: (msie6?'absolute':'fixed'),
			background: '#ffffff',
			zIndex: '102',
			color: '#000000',
			display: 'none',
			textAlign: 'left',
			top: '50%',
			left: '50%'
		});

		div_bg.onclick = function() {
			LSL.ThickBoxRemove();
		};

		document.body.appendChild(div_bg);
		document.body.appendChild(div_window);
	}
	if ($L("_DIV_IMG_BOX_SUSPENSED_") === null) {
		var div_img = document.createElement('div');
		div_img.id = '_DIV_IMG_BOX_SUSPENSED_';
		
		var imgLoader = new Image();// preload image
		imgLoader.src = IMG_LOADING;
		
		div_img.appendChild(imgLoader);
		
		LSL.addCSS(div_img, {
			position: (msie6?'absolute':'fixed'),
			display: 'none',
			height: '13px',
			width: '208px',
			zIndex: '103',
			top: '50%',
			left: '50%',
			margin: '-6px 0 0 -104px'
		});
		if (msie6) {
			LSL.addCSS(div_img, {marginTop: (0 - parseInt(div_img.offsetHeight / 2) + (document.documentElement?document.documentElement.scrollTop:document.body.scrollTop) + 'px') });
		}
		document.body.appendChild(div_img);
	}

	var div_id = $L('_DIV_BG_BOX_SUSPENSED_');
	LSL.addCSS(div_id, {display: 'block'});

	var div_window = $L('_DIV_WINDOW_BOX_SUSPENSED_');
	var div_img = $L('_DIV_IMG_BOX_SUSPENSED_');
	//alert(url.replace(/^([^\?]+)\??.*/,'$1') + '\n' + url.replace(/^[^\?]+\??/,''));
	var url_send = url.replace(/^([^\?]+)\??.*/,'$1').toString();
	var data_send = url.replace(/^[^\?]+\??/,'').toString();
	new LSL.AJAX.Event({
		url: url_send,
		data: data_send,
		onCreate: function() {
			LSL.addCSS(div_img, {display: 'block'});
		},
		
		onComplete: function(obj) {
			var root, erro;
			if (obj && obj.status == 200) {
				div_window.innerHTML = obj.responseText;
			} else {
				div_window.innerHTML = '<div id="_DIV_ERRO_BOX_SUSPENSED_"><strong>Ocorreu um erro no envio dos dados. <a href="javascript:;" onclick="return LSL.ThickBoxRemove()">Clique aqui</a> e tente novamente!</strong></div>';
				LSL.addCSS($L('_DIV_ERRO_BOX_SUSPENSED_'), {
					fontSize: '16px',
					color: '#F00'
				});
			}
			
			LSL.addCSS(div_img, {display: 'none'});
			
			LSL.addCSS(div_window, {marginLeft: '-' + parseInt((WIDTH / 2),10) + 'px', width: WIDTH+'px'});
			LSL.addCSS(div_window, {display: 'block'});
			if (msie6) {
				LSL.addCSS(div_window, {marginTop: (0 - parseInt(div_window.offsetHeight / 2) + (document.documentElement?document.documentElement.scrollTop:document.body.scrollTop) + 'px') });
			} else {
				LSL.addCSS(div_window, {marginTop: '-' + parseInt((div_window.offsetHeight / 2),10) + 'px'});
			}
			
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					LSL.ThickBoxRemove();
				}	
			};
		}
	});
	return false;
};
LSL.ThickBoxRemove = function() {
	var div_window = $L('_DIV_WINDOW_BOX_SUSPENSED_');
	if (div_window) {
		LSL.addCSS(div_window, {display: 'none'});
		div_window.innerHTML = '';
	}
	
	var div_img = $L('_DIV_IMG_BOX_SUSPENSED_');
	if (div_img) {
		LSL.addCSS(div_img, {display: 'none'});
	}

	var div_bg = $L('_DIV_BG_BOX_SUSPENSED_');
	if (div_bg) {
		LSL.addCSS(div_bg, {display: 'none'});
	}
	
	var iframe = $L('_IFRAME_BOX_SUSPENSED_');
	if (iframe) {
		LSL.addCSS(iframe, {display: 'none'});
	}

	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		LSL.addCSS(document.getElementsByTagName('html')[0], {height: "auto", width: "auto", overflow: ""});
		LSL.addCSS(document.body, {height: "auto", width: "auto"});
	}
	document.onkeyup = "";
	return false;
};

/**
 * Carrocel - By Leandro Sales
 * v2.0
 */
LSL.Carrocel = function(opt) {
	if (!opt) return; //obrigatorio
	if (!opt.size) return; //obrigatorio
	if (!opt.slide) return; //obrigatorio
	//if (!opt.inScreen) opt.inScreen = 1; //opcional
	if (!opt.duration) opt.duration = 1000; //opcional
	if (!opt.timeView) opt.timeView = ((opt.back || opt.forward)?0:5000);  //opcional
	
	if (opt.back) opt.back = $(opt.back);  //opcional
	if (opt.forward) opt.forward = $(opt.forward);  //opcional
	
	opt.slide = $(opt.slide);
	opt.total = opt.slide.length;
	opt.atualSlide = 0;
	
	var banners = new Array();
	var slides = new Array();
	
	jQuery.each(opt.slide, function(i, val) {
		var val2 = $(val);
		if (i == opt.atualSlide) {
			val2.animate({left: '0px'}, 1000);
		} else {
			val2.css({left: '-' + opt.size + 'px'});
		}
		if (opt.bannerClass != '' && val2.hasClass(opt.bannerClass)) {
			banners.push(val);
		} else {
			slides.push(val);
		}
	});

	var totalBanner = banners.length;
	if (totalBanner > 0) {
		var totalSlide = slides.length;
		var intervalo = Math.floor(totalSlide/totalBanner);
		var sobra = (totalSlide-intervalo*totalBanner);
		var newSlide = [];
		var ultimoBannerIndex = 0;
		for (var i = 0, j = 0; i < slides.length; i++) {
			newSlide.push(slides[i]);
			if (i+1 == intervalo+ultimoBannerIndex) {
				ultimoBannerIndex = i+1;
				newSlide.push(banners[j++]);
				if (j == totalBanner-sobra) intervalo++;
			}
		}
		slides = newSlide;
	}

	if (opt.total <= 1) return;
	
	var hideControlFunc = function() {
		if (opt.hideControl == true) {
			if (opt.atualSlide <= 0) {
				opt.back.css({visibility: 'hidden'});
			} else {
				opt.back.css({visibility: 'visible'});
			}
			if (opt.atualSlide >= opt.total-1) {
				opt.forward.css({visibility: 'hidden'});
			} else {
				opt.forward.css({visibility: 'visible'});
			}
		}
	}
	hideControlFunc();

	var carrocelControlClick = function(t) {
		if (t == 'back') {
			var nextSlide = opt.atualSlide-1;
			nextSlide = (nextSlide < 0?nextSlide = opt.total-1:nextSlide);

			$(slides[nextSlide]).css({left: '-' + opt.size + 'px'});
			$(slides[opt.atualSlide]).animate({left: opt.size + 'px'}, opt.duration);
			$(slides[nextSlide]).animate({left: '0px'}, opt.duration);
			
			opt.atualSlide = nextSlide;
		} else {
			if (opt.beforeNextSlide && !opt.beforeNextSlide(slides[opt.atualSlide])) return false;

			var nextSlide = opt.atualSlide+1;
			nextSlide = (nextSlide >= opt.total?nextSlide = 0:nextSlide);

			$(slides[nextSlide]).css({left: opt.size + 'px'});
			$(slides[opt.atualSlide]).animate({left: '-' + opt.size + 'px'}, opt.duration);
			$(slides[nextSlide]).animate({left: '0px'}, opt.duration);
			
			opt.atualSlide = nextSlide;
		}

		hideControlFunc();

		if (opt.timeView > 0) opt.timeout = setTimeout(carrocelControlClick, opt.timeView);
	};
	
	if (opt.back) {
		opt.back.click(function() {
			clearTimeout(opt.timeout);
			carrocelControlClick('back');
		});
	}
	if (opt.back) {
		opt.forward.click(function() {
			clearTimeout(opt.timeout);
			carrocelControlClick('forward');
		});
	}
	if (opt.timeView > 0) opt.timeout = setTimeout(carrocelControlClick, opt.timeView);
};

/*Testes*/
LSL.verifyQuestion = function(slide) {
	var selected = $(slide).find('input:radio:checked');
	if (selected.length == 0) {
		alert('Selecione uma opção antes de continuar!');
		return false;
	}
	return true;
};

/*Enquete*/
LSL.submitEnquete = function(form, result) {
	var element = $(form)
	element.find('div.err').slideUp().text('');
	if (typeof(result) == 'undefined') result = false;
	
	var val;
	if (!result) { //apenas se for para votar
		val = element.find('input:radio[name=op]:checked').val();
		if (typeof(val) == 'undefined' || val == '') {
			element.find('div.err').text('Escolha uma opção!').slideDown('slow');
			return false;
		}
	}
	
	var left = element.find('div.captcha').css('left');
	var captcha = element.find('input:text[name=captcha]').val();
	var idEnquete = element.find('input:hidden[name=id]').val();

	if (!result && left == '0px' && captcha == '') { //apenas se for para votar
		element.find('div.err').text('Digite as letras corretamente!').slideDown('slow');
		element.find('input:text[name=captcha]').focus();
		return false;
	}
	
	element.find('div.err').slideUp().text('');
	
	if (!result) { //apenas se for para votar
		element.find('div.captcha').animate({left: '0px'}, 1000);
		element.find('input.button').animate({left: '127px'}, 1000);
		element.find('a.button').animate({left: '182px'}, 1000);
	}

	if (left == '0px' || captcha != '' || result) {
		var uri = 'op=' + val + '&id=' + idEnquete + '&captcha=' + captcha + '&result=' + (result?'true':'false');
		
		element.find('div.button, input.button, a.button').css({display: 'none'});
		element.find('img.loading').css({display: 'block'});

		new LSL.AJAX.Event({
			url: localURL + 'enquetes.votar.php',
			data: uri,
			onCreate: function() {
				element.find('input').attr('disabled','disabled');
			},
			onComplete: function(obj) {
				var root, isErro = '';
				if (obj && obj.status == 200) {
					var html = obj.responseXML;
					var erro = html.getElementsByTagName('err');
					if (erro.length > 0) {
						isErro = erro[0].firstChild.nodeValue;
					} else {
						var itens = html.getElementsByTagName('item');
						for (var i = 0; i < itens.length; i++) {
							var cod = itens[i].getElementsByTagName('cod')[0].firstChild.nodeValue;
							var pixel = itens[i].getElementsByTagName('pixel')[0].firstChild.nodeValue;
							var percent = itens[i].getElementsByTagName('percent')[0].firstChild.nodeValue;
							
							var span = element.find('label.label-' + idEnquete + '-' + cod + ' span.result-enquete');
							span.find('span.barra-percent').css({width: pixel});
							span.find('span.percent-text').text(percent);
							span.slideDown('slow');
						}
						
						if (!result) element.find('div.buttons').text('Voto registrado!').css({color: '#090', fontWeight: 'bold'}).animate({height: '20px'}, 500);
					}
				} else {
					isErro = 'Ocorreu um erro!';
				}
				
				element.find('img.loading').css({display: 'none'});
				
				if (isErro != '' || result) {
					element.find('input').removeAttr('disabled');
					element.find('div.button, input.button, a.button').css({display: 'block'});
					if (isErro != '') element.find('div.err').text(isErro).slideDown('slow');
				}
			}
		});
	}
	
	return false;
};

LSL.getFormEnquete = function(id, result) {
	if (!id) return;
	
	var element = $('#enquete-' + id);
	var form = $('#form-list-enquete-' + id);
	
	if (form.hasClass('ja-carregado')) {
		form.slideDown('slow');
		if (result) form.find('span.result-enquete').slideDown('slow');
		return;
	}
	new LSL.AJAX.Event({
		url: localURL + 'enquetes.form.php',
		resultElement: 'form-list-enquete-' + id,
		data: 'id=' + id,
		onCreate: function() {
			form.slideUp('slow');
			element.find('div.vote-tambem').slideUp('slow');
			element.find('img.loading').slideDown('slow');
		},
		onComplete: function(obj) {
			var root, isErro = '';
			if (!obj || obj.status != 200) {
				form.html('<span class="red2">Ocorreu um erro na página!</span>');
			}
			element.find('div.vote-tambem').slideDown('slow');
			element.find('img.loading').slideUp('slow');
			form.addClass('ja-carregado').slideDown('slow');

			if (result) form.find('span.result-enquete').slideDown('slow');
		}
	});
};

/*Paginação*/
LSL.Paginacao = function(opt) {
	if (!opt) return; //obrigatorio
	
	if (opt.form) {
		opt.form = $(opt.form);
		var pag = opt.form.find('input:text[name=pag]').val();
		
		if (!LSL.Form.isNatural(pag)) {
			alert('Número inválido!');
		} else {
			var query = opt.form.find('input:hidden[name=query]').val();
			if (typeof(query) == 'undefined') query = '';
			document.location.href = opt.form.attr('action') + pag + query;
		}
		return false;
	}
	
	if (!opt.element) return; //obrigatorio
	if (!opt.secao) return; //obrigatorio
	if (!opt.url) return; //obrigatorio
	if (!opt.result) return; //obrigatorio
	if (opt.loading) opt.loading = $(opt.loading);
	if (opt.error) opt.error = $(opt.error);
	
	opt.element = $(opt.element);
	opt.result = $(opt.result);
	
	var getPage = function(pag) {
		new LSL.AJAX.Event({
			url: opt.url,
			data: 'secao=' + opt.secao + '&pag=' + pag + '&ajax=1',
			onCreate: function() {
				opt.result.fadeTo(500, 0.10);
				if (opt.loading) opt.loading.show();
			},
			onComplete: function(obj) {
				var root, isErro = '';
				if (obj && obj.status == 200) {
					var html = obj.responseXML;
					var erro = html.getElementsByTagName('err');
					if (erro.length > 0) {
						isErro = erro[0].firstChild.nodeValue;
					} else {
						var text = obj.responseText;
						var pos = text.indexOf('<ul');
						
						var li = text.substring(pos);
						var pos = li.indexOf('>');
						li = li.substring(pos+1);
						pos = li.indexOf('</ul>');
						
						text = li.substring(pos);
						
						li = li.substring(0, pos);
						opt.result.html(li);
						
						pos = text.indexOf('<ul');
						li = text.substring(pos);
						pos = li.indexOf('>');
						li = li.substring(pos+1);
						pos = li.indexOf('atual');
						li = li.substring(pos);
						pos = li.indexOf('>');
						li = li.substring(pos+1);
						pos = li.indexOf('</li>');
						li = li.substring(0, pos);
						
						var newPag = parseInt(li.replace(/^.+([0-9]+).+$/,'$1'));
						var totalPag = parseInt(li.replace(/^.+([0-9]+)$/,'$1'));

						if (newPag <= 1) {
							opt.element.find('li.back').css({visibility: 'hidden'});
						} else {
							var liBack = opt.element.find('li.back');
							liBack.css({visibility: 'visible'});
							
							var href = liBack.find('a').attr('href');
							liBack.find('a').attr('href', href.replace(/^(.*pag=)([0-9]+)(#.*)$/,'$1'+(newPag-1)+'$3'));
						}
						
						if (newPag >= totalPag) {
							opt.element.find('li.next').css({visibility: 'hidden'});
						} else {
							var liNext = opt.element.find('li.next');
							liNext.css({visibility: 'visible'});
							
							var href = liNext.find('a').attr('href');
							liNext.find('a').attr('href', href.replace(/^(.*pag=)([0-9]+)(#.*)$/,'$1'+(newPag+1)+'$3'));
						}
						
						opt.element.find('li.atual').html('Pág ' + newPag + ' de ' + totalPag);
					}
				} else {
					isErro = 'Ocorreu um erro!';
				}
				
				if (isErro != '') {
					if (opt.error) {
						opt.error.text(isErro);
						opt.error.show();
						opt.error.fadeOut(1500);
					} else {
						alert(isErro);
					}
				}
				if (opt.loading) opt.loading.fadeOut(500);
				opt.result.fadeTo(1000, 1);
			}
		});
	};

	opt.element.find('li a').click(function(e) {
		e.preventDefault();

		var pag = $(this).attr('href').replace(/^.*pag=([0-9]+)#.*$/,'$1');

		getPage(pag);

		return false;
	});
	
	var textAtual = opt.element.find('li.atual').text();
	var pagAtual = textAtual.replace(/^.+([0-9]+).+$/,'$1');
	var pagTotal = textAtual.replace(/^.+([0-9]+)$/,'$1');
	
	if (pagAtual == 1) opt.element.find('li.back').css({visibility: 'hidden'});
	if (pagAtual == pagTotal) opt.element.find('li.next').css({visibility: 'hidden'});
	
	opt.element.find('form').submit(function(e) {
		var pag = $(this).find('input:text[name=pag]').val();
		
		if (!LSL.Form.isNatural(pag)) {
			alert('Número inválido!');
		} else {
			getPage(pag);
		}
		return false;
	});
};

/*Avaliação*/
LSL.Avaliacao = function(opt) {
	if (!opt.element) return;
	if (!opt.id) return;
	if (!opt.loading) return;
	if (!opt.url) return;
	
	opt.votado = false;

	opt.element = $(opt.element);
	opt.loading = $(opt.loading);
	
	var a = opt.element.find('a');
	jQuery.each(a, function(i, val) {
		var element = $(val);
		element.mouseover(function() {
			if (opt.votado) return;
			a.removeClass('no-estrela');
			a.addClass('estrela');

			var atual = $(this.parentNode);
			for (j = 1; j < 5; j++) {
				if (atual.hasClass('' + j)) {
					opt.element.find('li.' + j + ' ~ li a').removeClass('estrela').addClass('no-estrela');
				}
			}
		});
		element.mouseout(function() {
			if (opt.votado) return;
			a.removeClass('estrela no-estrela');
		});
		element.click(function() {
			$(this).mouseout();
			if (opt.votado) return;
			var atual = $(this.parentNode);
			var pontos = 0;
			for (j = 1; j <= 5; j++) {
				if (atual.hasClass('' + j)) {
					pontos = j;
				}
			}
			
			new LSL.AJAX.Event({
				url: localURL + opt.url,
				data: 'id=' + opt.id + '&v=' + pontos,
				onCreate: function() {
					opt.loading.html('<img src="images/loading-circle.gif" width="16" height="16" alt="loading..." />').show();
				},
				onComplete: function(obj) {
					var root, err = '', color = '#060';
					if (obj.status == 200 && (root = obj.responseXML)) {
						try {
							err = root.getElementsByTagName('err');
							if (err.length > 0) {
								err = err[0].childNodes[0].nodeValue
								color = '#F00';
							} else {
								var media = root.getElementsByTagName('media')[0].childNodes[0].nodeValue;

								media = parseFloat(media);
								
								opt.element.find('li').removeClass('estrela').removeClass('meia-estrela');
								for (j = 1; j <= 5; j++) {
									if (media > j-0.5) {
										opt.element.find('li.' + j).addClass('estrela');
									} else if (media > j-1) {
										opt.element.find('li.' + j).addClass('meia-estrela');
									}
								}
								
								var num_votos = root.getElementsByTagName('num_votos');
								if (num_votos.length > 0) {
									num_votos = num_votos[0].childNodes[0].nodeValue;
									var text_votos = num_votos + ' voto';
									if (num_votos > 1) text_votos += 's';
									
									$('#avalie-total-' + opt.id).html(text_votos);
								}
								
								err = 'Voto confirmado!';
								opt.votado = true;
								
								a.css({cursor: 'default'});
							}
						} catch (e) {
							err = 'Ocorreu um erro';
							color = '#F00';
						}
					} else {
						err = 'Ocorreu um erro';
						color = '#F00';
					}
					opt.loading.css({color: color}).html(err).show().fadeOut(2000);
				}
			});
		});
		
		if (opt.updateOnLoad) {
			new LSL.AJAX.Event({
				url: localURL + opt.url,
				data: 'id=' + opt.id + '&v=0',
				onComplete: function(obj) {
					var root;
					if (obj.status == 200 && (root = obj.responseXML)) {
						try {
							var media = root.getElementsByTagName('media')[0].childNodes[0].nodeValue;

							media = parseFloat(media);
								
							opt.element.find('li').removeClass('estrela').removeClass('meia-estrela');
							for (j = 1; j <= 5; j++) {
								if (media > j-0.5) {
									opt.element.find('li.' + j).addClass('estrela');
								} else if (media > j-1) {
									opt.element.find('li.' + j).addClass('meia-estrela');
								}
							}
						} catch (e) {
						}
					}
				}
		   });
		}
	});
};

/*Comentarios*/
LSL.sendComment = function(element) {
	var disable = function(disable) {
		for (var i=0, size = element.elements.length; i<size; i++) {
			var field = element.elements[i];
			if (typeof field.name == 'undefined') continue;
			if (field.type.toLowerCase() == 'hidden') continue;
			if (field.disabled == disable) continue;
			field.disabled = disable;
		}
	};
	if (LSL.Form.valida(element)) {
		var form = $(element);

		var uri = LSL.Form.getURI(element);
		var divMsg;
		if (form.find('input:hidden[name=altospapos]').val() == '1') {
			divMsg = $(element.parentNode.parentNode.parentNode).find('div.form-perguntas');
		} else if (form.find('input:hidden[name=altospapos]').val() == '2') {
			divMsg = $(element.parentNode.parentNode).find('div.form-msg');
		} else {
			divMsg = $(element.parentNode).find('div.form-msg');
		}
		new LSL.AJAX.Event({
				url: localURL +  form.find('input:hidden[name=uri]').val(),
				data: uri,
				onCreate: function() {
					form.find('img.loading').show();
					divMsg.removeClass('form-msg-green').hide();
					disable(true);
					form.find('input.button').fadeTo(100, 0.1);
				},
				
				onComplete: function(obj) {
					var root, err = '';
					if (obj && obj.status == 200 && (root = obj.responseXML)) {
						err = root.getElementsByTagName('err');
						if (err.length > 0) {
							err = err[0].childNodes[0].nodeValue;
						} else {
							var ok = root.getElementsByTagName('ok');
							if (ok.length > 0) {
								if (form.find('input:hidden[name=mural]').val() == 'true') {
									var url = document.location.href;
									url = url.match(/^.*\/([0-9]+)\/?$/);

									if (!url) {
										$('#mural div.mensagem:first').before(ok[0].childNodes[0].nodeValue).fadeTo(1, 0.01, function() {$(this).fadeTo(500, 1);} );
									}
									err = 'Recado enviado com sucesso.';
								} else if (form.find('input:hidden[name=altospapos]').val() == '1') {
									$('#perguntas-altospapos div.pergunta:first').before(ok[0].childNodes[0].nodeValue).fadeTo(1, 0.01, function() {$(this).fadeTo(500, 1);} );
									err = 'Pergunta enviada com sucesso.';
								} else if (form.find('input:hidden[name=altospapos]').val() == '2') {
									$('#resposta-altospapos div.resposta:first').before(ok[0].childNodes[0].nodeValue).fadeTo(1, 0.01, function() {$(this).fadeTo(500, 1);} );
									err = 'Resposta enviada com sucesso.';
								} else if (form.find('input:hidden[name=horoscopo]').val() == 'true') {
									err = 'Hist&oacute;ria enviada com sucesso.';
								} else {
									err = 'Coment&aacute;rio enviado com sucesso. Em breve ele ser&aacute; ativado.';
								}
								divMsg.addClass('form-msg-green');
								
								form.find('input:text, textarea, select').val('');
								var max_char = form.find('input:hidden[name=max_char]').val();
								if (max_char == '') max_char = 500;
								$('#countElement').text(max_char);
							} else {
								err = 'Ocorreu um erro no resultado dos dados. Tente novamente!';
							}
						}
					} else {
						err = 'Ocorreu um erro no envio dos dados. Tente novamente!';
					}

					disable(false);
					divMsg.hide().html(err).slideDown('slow');
					form.find('img.loading').hide();
					form.find('input.button').fadeTo(1, 1);
				}
	   });
	}
	return false;
};

/*
 * Recarrega uma nova imagem do captcha
 */
LSL.newCaptcha = function(element, size) {
	element = $L(element);
	element.src = localURL + 'captcha.php?' + (size?'size=1&':'') + Math.floor(Math.random()*1001);
	return false;
};

/*
 * Slide das fotos pequenas do album
 */
LSL.SlideFoto = function(opt) {
	if (!opt.up) return;
	if (!opt.down) return;
	if (!opt.slide) return;
	if (!opt.fotoGr) return;
	if (typeof(opt.maxClick) == 'undefined') return;

	var size = 64;

	opt.up = $(opt.up);
	opt.down = $(opt.down);
	opt.slide = $(opt.slide);
	opt.fotoGr = $(opt.fotoGr);
	
	opt.slide.find('a').click(function() {
		var a = $(this);
		var img = a.find('img');
		var src = img.attr('src');
		var title = img.attr('title');
		src = src.replace(/^(.+)_pq\.(.+)$/,'$1.$2');
		
		var div = opt.fotoGr.find('div');
		div.fadeTo(500, 0.01, function() {
			opt.fotoGr.find('img.loading').show();
			div.html('<img src="' + src + '" width="555" height="420" alt="' + title + '" onload="$(this).parent().fadeTo(1000, 1, function() {$(this).parent().parent().find(\'img.loading\').hide() })" />');
		});
		
		var p = opt.fotoGr.find('p');
		p.slideUp(500, function() {p.html(title);});
		p.slideDown(500);

		//Alterar url da imagem nas informações do album
		var url = a.attr('href');
		var url_reduzida = '';
		for (var i = 0; i < url.length; i+=26) {
			url_reduzida += url.substr(i, 26) + ' ';
		}
		var urlImg = $('#url-img-album');
		urlImg.fadeTo(500, 0.01, function() {
			urlImg.html('<a href="' + url + '">' + url_reduzida + '</a>').fadeTo(500, 1);
		});

		//div.find('img').attr('src', src);
		return false;
	});

	if (opt.maxClick == 0) {
		opt.up.css({backgroundColor: '#CCC', cursor: 'default'});
		opt.down.css({backgroundColor: '#CCC', cursor: 'default'});
		return;
	}

	opt.up.click(function() {
		var top = parseInt(opt.slide.css('top').replace('px',''));
		if (top == 0) return false;
		
		opt.slide.animate({top: (top+size)+'px'}, 1000);

		opt.down.css({backgroundColor: '#69F', cursor: 'pointer'});
		if ((top+size) == 0) {
			opt.up.css({backgroundColor: '#CCC', cursor: 'default'});
		}
	});
	
	opt.down.click(function() {
		var top = parseInt(opt.slide.css('top').replace('px',''));
		if (top < 0) top = top * -1;
		if (top / size >= opt.maxClick) return false;
		
		opt.slide.animate({top: ((top+size)*-1)+'px'}, 1000);

		opt.up.css({backgroundColor: '#69F', cursor: 'pointer'});
		if ((top+size) / size >= opt.maxClick) {
			opt.down.css({backgroundColor: '#CCC', cursor: 'default'});
		}
	});
};

//Adicionar pagina aos favoritos
LSL.addFavoritos = function(title) {
	var url = document.location.href;
	var title = title || "Teens180 - O 1º portal jovem do Piauí";
	if (window.sidebar) { //FF
		window.sidebar.addPanel(title, url,"");
	} else if (window.opera && window.print) { //OPERA
		var favOpera = document.createElement('a');
		favOpera.setAttribute('rel','sidebar');
		favOpera.setAttribute('href',url);
		favOpera.setAttribute('title',title);
		favOpera.click();
	} else if (document.all) { //IE
		window.external.AddFavorite(url, title);
	}
	return false;
};

//selecionar sessao na central de comentarios
LSL.changeCommentSessao = function(element) {
	var sessao = element.options[element.selectedIndex].value;
	var url = localURL + 'comentarios';
	if (sessao != '') url += '/' + sessao;
	document.location.href = url;
};

//Enviar formulario para a url atual, sem ajax
LSL.sendForm = function(form) {
	if (!LSL.Form.valida(form)) {
		return false;
	}
	var action = $(form).attr('action');
	var url = document.location.href;
	url = url.replace(/^(.*)#.*$/,'$1');
	
	$(form).attr('action', url + action);
	return true;
};

LSL.votarAltosPapos = function(element, id, voto) {
	var a = $(element);
	var parent = $(element.parentNode);
	new LSL.AJAX.Event({
		url: localURL + 'altospapos.votar.php',
		data: 'id=' + id + '&v=' + voto,
		onCreate: function() {
			parent.find('span.loading').html('<img src="images/loading-circle.gif" width="16" height="16" alt="loading..." />').show();
			parent.find('a').css({cursor: 'default'}).removeAttr('onclick');
		},
		onComplete: function(obj) {
			var root, err = '', color = '#060';
			if (obj.status == 200 && (root = obj.responseXML)) {
				try {
					err = root.getElementsByTagName('err');
					if (err.length > 0) {
						err = err[0].childNodes[0].nodeValue
						color = '#F00';
					} else {
						try {
							var votos = root.getElementsByTagName('voto')[0].childNodes[0].nodeValue;
							votos = parseFloat(votos);
							if (voto > 0) {
								a.html('(' + votos + ') <big>+</big>');
							} else if (voto < 0) {
								a.html('(' + votos + ') <big>-</big>');
							}
						} catch (e) {
						}
						
						err = 'Voto confirmado!';

						parent.find('a').css({cursor: 'default'}).removeAttr('onclick');
					}
				} catch (e) {
					err = 'Ocorreu um erro';
					color = '#F00';
				}
			} else {
				err = 'Ocorreu um erro';
				color = '#F00';
			}
			parent.find('span.loading').css({color: color}).html(err).show().fadeOut(2000);
		}
   });
};

LSL.Testes = function(opt) {
	if (!opt.element) return;
	if (!opt.total) return;
	
	opt.element = $(opt.element);
	
	opt.element.find('input').click(function() {
		var escolhido = 0;
		var peso = 0;
		for (var i = 1; i <= opt.total; i++) {
			var checked = opt.element.find('input.question-' + i + ':radio:checked');
			
			var novo_peso = 0;
			jQuery.each(checked, function(j, val) {
				val = $(val);
				novo_peso += val.val();
			});
			
			if (novo_peso >= peso) {
				peso = novo_peso;
				escolhido = i;
			}
		}
		for (var i = 1; i <= opt.total; i++) {
			if (i == escolhido) {
				opt.element.find('div.result-' + i).css({display: 'block'});
			} else {
				opt.element.find('div.result-' + i).css({display: 'none'});
			}
		}
	});
};

LSL.addBanner = function(opt) {
	if (!opt.width) return;
	if (!opt.height) return;
	if (!opt.arquivo) return;

	var file = opt.arquivo.replace(/^(.+)\.([a-z]+)$/,'$1');
	var extensao = opt.arquivo.replace(/^(.+)\.([a-z]+)$/,'$2').toLowerCase();
	
	if (extensao == 'jpg' || extensao == 'jpeg' || extensao == 'gif' || extensao == 'png') {
		var html = '<img alt="Publicidade" src="' + opt.arquivo + '" width="' + opt.width + '" height="' + opt.height + '" />';
		if (opt.link != '') {
			html = '<a href="' + opt.link + '" target="_blank">' + html + '</a>';
		}
		document.write(html);
	} else if (extensao == 'swf') {
		if (opt.link != '') document.write('<a href="' + opt.link + '" target="_blank">');
		AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width',opt.width,'height',opt.height,'src',file,'quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie',file,'wmode','transparent');
		if (opt.link != '') document.write('</a>');
	}
};

LSL.getPrevisaoSigno = function(element, signo) {
	$(element).parent().parent().find('li.selected').removeClass('selected');
	$(element).parent().addClass('selected');
	var process = false;
	new LSL.AJAX.Event({
		url: localURL + 'horoscopo.caixa.signo.php',
		data: 'ajax=true&signo=' + signo,
		onCreate: function() {
			$('#previsao-horoscopo').slideUp(function() {if (process == false) $(this).html('<img src="images/loading.gif" width="208" height="13" alt="loading..." />').slideDown();});
		},
		onComplete: function(obj) {
			var err = '';
			process = true;
			if (obj.status == 200) {
				try {
					err = obj.responseText;
				} catch (e) {
					err = '<p class="red">Ocorreu um erro. Atualize a página e tente novamente!</p>';
				}
			} else {
				err = '<p class="red">Ocorreu um erro. Atualize a página e tente novamente!</p>';
			}
			setTimeout($('#previsao-horoscopo').slideUp(function() {$(this).html(err).slideDown();}), 1000);
		}
	});
	return false;
};

LSL.combinarSigno = function() {
	var signo1 = $('#combinarSigno1 option:selected').val();
	var signo2 = $('#combinarSigno2 option:selected').val();
	
	if (signo1 != '' && signo2 != '') {
		document.location.href = localURL + 'horoscopo/' + signo1 + '/' + signo2 + '#combinacao';
	} else {
		alert('Antes de continuar preencha os dois SIGNOS que deseja combinar.');
	}
};

LSL.printNews = function(element) {
	window.open(element.href, '', 'menubar=yes,scrollbars=yes,width=700,height=600');
	return false;
};

LSL.sendNews = function(element) {
	if (LSL.Form.valida(element)) {
		var uri = LSL.Form.getURI(element);
		new LSL.AJAX.Event({
				url: localURL + 'enviar.php',
				resultElement: element,
				data: '' + uri,
				onCreate: function() {
					for (var i=0, size = element.elements.length; i<size; i++) {
						var field = element.elements[i];
						if (typeof field.name == 'undefined') continue;
						if (field.type.toLowerCase() == 'hidden') continue;
						if (field.disabled) continue;
						field.disabled = true;
					}
					element.elements['enviar-noticia'].value = 'Enviando dados...'
				}
	   });
	}
	return false;
};

LSL.sendChat = function(form) {
	$('#formErr').slideUp();
	if (LSL.Form.valida(form)) {
		new LSL.AJAX.Event({
			url: localURL + 'chat.send.php',
			data: LSL.Form.getURI(form),
			onCreate: function() {
				$('#formErr').slideUp();
				$('#formChat').find('textarea, input:text').attr('disabled', true);
				$('#formChat').find('textarea, input:text').fadeTo(50, 0.1, function(){ $('#formChat img.loading').show().fadeTo(50, 1); });
			},
			onComplete: function(obj) {
				var root, isErro = '';
				if (obj && obj.status == 200) {
					var html = obj.responseXML;
					var erro = html.getElementsByTagName('err');
					if (erro.length > 0) {
						isErro = erro[0].firstChild.nodeValue;
					} else {
						var text = html.getElementsByTagName('ok')[0].firstChild.nodeValue;
						$('#pertuntas-chat blockquote.pai:last-child').after(text).parent().find('blockquote.pai:last-child').slideDown();
					}
				} else {
					isErro = 'Ocorreu um erro!';
				}

				$('#formChat').find('textarea, input:text').attr('disabled', false);
				$('#formChat img.loading').fadeTo(1, 0).hide();
				$('#formChat').find('textarea, input:text').fadeTo(1, 1).show();
				if (isErro != '') {
					$('#formErr').html(isErro).slideDown();
					setTimeout(function() {$('#formChat img.loading').hide();}, 500);
				} else {
					$('#formChat textarea').val('');
					$('#countElement').val('160');
				}
				setTimeout(function() {$('#formChat textarea').focus();}, 100);
			}
		});
	}
	return false;
};
LSL.updateChat = function(id) {
	timeUpdateChat = setTimeout(function() {
		var blockquote = $('#pertuntas-chat blockquote.pai');
		var cod = '0';
		var arrcod = [];
		var i = 0;
		jQuery.each(blockquote, function(j, val) {
			val = $(val);
			arrcod[i++] = val.attr('class').replace(/\D/g,'');
		});
		for (var i = 0; i < arrcod.length-1; i++) {
			for (var j = i+1; j < arrcod.length; j++) {
				if (arrcod[i] < arrcod[j]) {
					var temp = arrcod[i];
					arrcod[i] = arrcod[j];
					arrcod[j] = temp;
				}
			}
		}
		for (var i = 0; i < arrcod.length-1; i++) {
			if (i < 20) {
				cod += ',' + arrcod[i];
			}
		}
		new LSL.AJAX.Event({
			url: localURL + 'chat.get.php',
			data: 'cod=' + cod + '&id=' + id,
			onCreate: function() {
			},
			onComplete: function(obj) {
				clearTimeout(timeUpdateChat);
				LSL.updateChat(id);
				var root, isErro = '';
				if (obj && obj.status == 200) {
					var html = obj.responseXML;
					var erro = html.getElementsByTagName('err');
					if (erro.length > 0) {
						isErro = erro[0].firstChild.nodeValue;
					} else {
						var text = html.getElementsByTagName('ok')[0].firstChild.nodeValue;
						if (text != '') {
							$('#pertuntas-chat blockquote.pai:last-child').after(text).parent().find('blockquote.new-message').slideDown().removeClass('new-message');
						}
					}
				} else {
					isErro = 'Ocorreu um erro!';
				}
			}
		});
	}, 20000);
};

$(document).ready(function() {
	//Personalizar
	$('#header ul.personalize li a').click(function() {
		var clas = $(this.parentNode).attr('class');
		if (clas != '') {
			$('body').removeClass().addClass(clas);
		}
		
		var dtmData = new Date();
		dtmData.setTime(dtmData.getTime() + (30 * 24 * 60 * 60 * 1000));
		document.cookie = "backgroundHome=" + clas + "; expires=" + dtmData.toGMTString() + "; path=/";
	});
	
	//Campo de busca
	var element = $('#idSearchField');
	element.focus(function() {
		if (this.value == 'buscar...') {
			this.value = '';
		}
		$(this).css({fontStyle: 'normal'});
	});
	element.blur(function() {
		if (this.value == '') {
			this.value = 'buscar...';
			$(this).css({fontStyle: 'italic'});
		}
	});
	
	//Campo teens club
	element = $('#idEmailField');
	element.focus(function() {
		if (this.value == 'e-mail / senha') {
			this.value = '';
		}
		$(this).css({fontStyle: 'normal'});
	});
	element.blur(function() {
		if (this.value == '') {
			this.value = 'e-mail / senha';
			$(this).css({fontStyle: 'italic'});
		}
	});
	
	//Super Banner
	var divAnuncios = $('#header div.banner');
	var tabContainers = divAnuncios.find('div');
	var li = divAnuncios.find('li a');

	//tabContainers.hide().filter(':first').show();
	li.click(function () {
		tabContainers.hide();
		divAnuncios.find(this.hash).show();
		li.removeClass('selected');
		$(this).addClass('selected');
		return false;
	}).filter(':first').click();

	
	$('#rodape-colaboradores li').mouseenter(function() {
		$(this).find('img').show();
	}).mouseleave(function() {
		$(this).find('img').hide();
	});
});

/////////////////////////////////////////////////

if (!LSL.Form) {
	LSL.Form = {};
}

LSL.Form.valida = function(form) {
	var opcional;
	if (form.opcional)
		opcional = (form.opcional.value.toLowerCase() + ',opcional').split(',');
	else
		opcional = [];

	var radios = [];
	for (var i=0; i<form.elements.length; i++) {
		var field = form.elements[i];
		if (typeof field.name == 'undefined') continue;
		if (field.disabled) continue;

		var fieldName = field.name.toLowerCase();
		var vazio = false;
		if (opcional.indexOf(fieldName) == -1) {
			
			var value = field.value;
			if (value == '') {
				vazio = true;
			} else if ((field.type.toLowerCase() == 'radio' || field.type.toLowerCase() == 'checkbox') && (radios.indexOf(fieldName) == -1)) {
				radios.push(fieldName);
				vazio = true;
				for (var k = 0; k < form.elements.length; k++) {
					if (typeof form.elements[k].name == 'undefined') continue;
					if (form.elements[k].disabled) continue;
					if (form.elements[k].name.toLowerCase() == fieldName) {
						if (form.elements[k].checked) {
							vazio = false;
							break;
						}
					}
				}
			}
		}
		if (vazio) {
			alert('Campo(s) obrigatório(s) não preenchido! (' + fieldName + ')');
			if (field.type.toLowerCase() != 'hidden') {
				field.focus();
			}
			return false;
		} else if (field.value != '') {
			if (fieldName == 'cep' && (!LSL.Form.isNatural(field.value) || field.value.length != 8)) {
				alert('Cep inválido. Digite apenas números!'); field.focus(); return false;
			} else if (fieldName == 'ddd' && (!LSL.Form.isNatural(field.value) || field.value.length != 2 || form.telefone.value == '')) {
				alert('Telefone inválido. Digite apenas números!'); field.focus(); return false;
			} else if (fieldName == 'telefone' && (!LSL.Form.isNatural(field.value) || field.value.length < 8 || form.ddd.value == '')) {
				alert('Telefone inválido. Digite apenas números!'); field.focus(); return false;
			} else if (fieldName == 'dddCel' && (!LSL.Form.isNatural(field.value) || field.value.length != 2 || form.celular.value == '')) {
				alert('Celular inválido. Digite apenas números!'); field.focus(); return false;
			} else if (fieldName == 'celular' && (!LSL.Form.isNatural(field.value) || field.value.length < 8 || form.dddCel.value == '')) {
				alert('Celular inválido. Digite apenas números!'); field.focus(); return false;
			} else if ((fieldName == 'email') && !LSL.Form.isMail(field.value)) {
				alert('E-mail inválido.'); field.focus(); return false;
			} else if (fieldName == 'nascimento' && !LSL.Form.isDate(field.value)) {
				alert('Data de nascimento inválida. Ex: 30/04/2010'); field.focus(); return false;
			} else if ((fieldName == 'cnpj' || fieldName == 'cnpj_cad') && !LSL.Form.verifyCNPJ(field.value)) {
				alert('CNPJ inválido. Digite apenas números!'); field.focus(); return false;
			} else if (fieldName == 'notahoroscopo') {
				if (!LSL.Form.isNumeric(field.value)) {
					alert('Nota inválida. Digite uma nota de 0 a 10.'); field.focus(); return false;
				} else {
					var temp = parseFloat(field.value.replace('.','').replace(',','.'));
					if (typeof(temp) == 'NaN' || temp < 0 || temp > 10) {
						alert('Nota inválida. Digite uma nota de 0 a 10.'); field.focus(); return false;
					}
				}
			} else if (fieldName == 'senha' && field.value.length < 6) {
				alert('A senha deve conter no mínimo 6 caracteres!'); field.focus(); return false;
			} else if (fieldName == 'login') {
				var reg = new RegExp('[^0-9]');
				if (field.value.length != 11 || reg.test(field.value)) {
					alert('O LOGIN/ID deve ser um CPF com apenas números!'); field.focus(); return false;
				}
			}
		}
	}
	return true;
};

LSL.Form.getURI = function(form) {
	var uri = '';

	this.makeURI = function(nome,valor) {
		uri += (uri != ''?'&':'') + nome + '=' + encodeURIComponent(valor);
	};

	for (var i=0; i<form.elements.length; i++) {
		var field = form.elements[i];
		if (!field.disabled) {
			switch(field.type) {
				case 'text': case 'password': case 'hidden': 
					this.makeURI(field.name,field.value);
					break;
				case 'textarea':
					this.makeURI(field.name,field.value);
					break;
				case 'select-one':
					if (field.selectedIndex>=0) {
						this.makeURI(field.name,field.options[field.selectedIndex].value);
					}
					break;
				case 'select-multiple':
					for (var j=0; j<field.options.length; j++) {
						if (field.options[j].selected) {
							this.makeURI(field.name,field.options[j].value);
						}
					}
					break;
				case 'checkbox': case 'radio':
					if (field.checked) {
						this.makeURI(field.name,field.value);
					}
					break;
			}
		}
	}
	return uri;
};

LSL.Form.isNatural = function(text) {
	var chr = '0123456789';
	return LSL.Form.verify(text, chr);
};

LSL.Form.isNumeric = function(text) {
	var chr = '0123456789.,';
	return LSL.Form.verify(text, chr);
};

LSL.Form.isDate = function(text) {
	if (text.length == 10 && LSL.Form.isNatural(text.substring(0,2)) && text.substring(2,3) == '/' && LSL.Form.isNatural(text.substring(3,5)) && text.substring(5,6) == '/' && LSL.Form.isNatural(text.substring(6,10))) {
		return true;
	} else {
		return false;
	}
};

LSL.Form.isDateTime = function(text) {
	//DD/MM/YYYY HH:MM:SS
	//0123456789012345678
	if (text.length == 19 && LSL.Form.isNatural(text.substring(0,2)) && text.substring(2,3) == '/' && LSL.Form.isNatural(text.substring(3,5)) && text.substring(5,6) == '/' && LSL.Form.isNatural(text.substring(6,10)) &&
		text.substring(10,11) == ' ' && LSL.Form.isNatural(text.substring(11,13)) && text.substring(13,14) == ':' && LSL.Form.isNatural(text.substring(14,16)) && text.substring(16,17) == ':' && LSL.Form.isNatural(text.substring(17,19))) {
		return true;
	} else {
		return false;
	}
};

LSL.Form.verify = function(text, chr) {
	for (var i=0; i<text.length;i++) {
		if (chr.indexOf(text.charAt(i)) == -1) 
			return false;
	}
	return true;
};

LSL.Form.isMail = function(text) {
	if (text.indexOf('@')<1 || text.indexOf('@')>=(text.length-5) || text.length < 8)
		return false;
	return true;
};

LSL.Form.verifyCPF = function(cpf) {
	//if (cpf.length != 11) return false;
	//while (cpf != (cpf=cpf.replace('.','').replace('-','')));
	
	cpf = cpf.replace(/[^0-9]/g,'');
	
	if (!LSL.Form.isNatural(cpf)) return false;
	if (cpf.length != 11) return false;
	
	var digitos_iguais = true;
	for (i = 0; i < cpf.length - 1; i++) {
		if (cpf.charAt(i) != cpf.charAt(i + 1)) {
			digitos_iguais = false;
			break;
		}
	}
	if (digitos_iguais) return false;

	var ver1 = parseInt(cpf.charAt(9));
	var ver2 = parseInt(cpf.charAt(10));
	cpf = cpf.substring(0,9);

	var soma = 0;
	var k = 10;
	for (var j=0;j<cpf.length;j++) {
		soma += parseInt(cpf.charAt(j)) * k;
		k--;
	}
	var resto = soma%11;
	
	var verTemp = 0;
	if (resto >= 2) verTemp = 11 - resto;
	
	if (verTemp != ver1)
		return false;
	else {
		soma = 0;
		k = 11;
		cpf += ver1;
		for (var j=0;j<cpf.length;j++) {
			soma += parseInt(cpf.charAt(j)) * k;
			k--;
			if (k < 2) k = 9;
		}
		resto = soma%11;
		verTemp = 0;
		if (resto >= 2) verTemp = 11 - resto;
		if (verTemp != ver2) return false;
	}
	return true;
};

LSL.Form.verifyCNPJ = function(cnpj) {
	//if (cnpj.length != 18) return false;
	//while (cnpj != (cnpj=cnpj.replace('.','').replace('/','').replace('-','')));

	if (!LSL.Form.isNatural(cnpj)) return false;
	if (cnpj.length == 14) cnpj = '0' + cnpj;
	if (cnpj.length != 15) return false;

	var digitos_iguais = true;
	for (i = 0; i < cnpj.length - 1; i++) {
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)) {
			digitos_iguais = false;
			break;
		}
	}
	if (digitos_iguais) return false;

	var ver1 = parseInt(cnpj.charAt(13));
	var ver2 = parseInt(cnpj.charAt(14));
	cnpj = cnpj.substring(0,13);
	var soma = 0;
	var k = 6;
	for (var j=0;j<cnpj.length;j++) {
		soma += parseInt(cnpj.charAt(j)) * k;
		k--;
		if (k < 2) k = 9;
	}
	var resto = soma%11;
	
	var verTemp = 0;
	if (resto >= 2) verTemp = 11 - resto;

	if (verTemp != ver1)
		return false;
	else {
		soma = 0;
		k = 7;
		cnpj += ver1;
		for (var j=0;j<cnpj.length;j++) {
			soma += parseInt(cnpj.charAt(j)) * k;
			k--;
			if (k < 2) k = 9;
		}
		resto = soma%11;
		verTemp = 0;
		if (resto >= 2) verTemp = 11 - resto;
		if (verTemp != ver2) return false;
	}
	return true;
};

LSL.Form.mascaraDate = function(field) {
	var val = field.value;
	val = val.replace(/\D/g, '');
	val = val.replace(/(\d\d)(\d)/, '$1/$2');
	val = val.replace(/(\d\d)(\d)/, '$1/$2');
	field.value = val.substring(0,10);
};

LSL.Form.mascaraTelefone = function(field) {
	var val = field.value;
	val = val.replace(/\D/g, '');
	val = val.replace(/^(\d)(\d)?/, '($1$2');
	val = val.replace(/(\d\d)(\d)/, '$1) $2');
	val = val.replace(/(\d\d\d\d)(\d)/, '$1-$2');
	field.value = val.substring(0,14);
};

LSL.Form.mascaraCPF = function(field) {
	var val = field.value;
	val = val.replace(/\D/g, '');
	val = val.replace(/(\d\d\d)(\d)/, '$1.$2');
	val = val.replace(/(\d\d\d)(\d)/, '$1.$2');
	val = val.replace(/(\d\d\d)(\d)/, '$1-$2');
	field.value = val.substring(0,14);
};

LSL.Form.mascaraNumero = function(field) {
	var val = field.value;
	val = val.replace(/[^0-9,]/g, '');
	field.value = val;
};
