String.prototype.isEmail = function()
{
	var regex = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)+)\.([A-Za-z]{2,})$/

	if (regex.test(this))
	{
		return true;
	}
	
	return false;
};

Number.prototype.toMili = function()
{
	return (this * 1000);
};

// get a querystring
jQuery.url = function(strChave)
{
	var querystring = document.location.search;
	var expressao   = eval('/(?:&)*' + strChave.toLowerCase() + '=([^\&]+)(?:&)*/i');
	var regexp      = expressao.exec(querystring);

	if (regexp != null) 
	{
		if (querystring.length > 0)
			return regexp[1]; 
		else
			return false;
	}
};

$(function()
{
	// categories
	//var elmCats      = $('#categories'),
	//	elmCatsItems = elmCats.find('ul');
	
	// create a new item, in order to close the categories box
	//var elmCatsClose = elmCatsItems.prepend('<li><a href="#" class="closeCategories">Fechar</a></li>');
	
	// open the categories, including onfocus to improve accessibility
	/*elmCats.find('h3')
		.bind('click', showCats)
		.bind('focus', showCats);
	*/
	// close the categories
	/*
	elmCatsClose.click
	( 
		function()
		{ 
			elmCatsItems.slideUp(200); 
		}
	);
	*/
	
	// open the 'lost password' popup
	$('#login > fieldset > p > a').click
	(
	 	function() 
		{
			popup('esqueci.asp', {width:300, height:200, name:'passwordRetrieval', dependent:true});
			return false;
		}
	);
	
	// hide all answers in "FAQ"
	$('#faq > dd').each
	(
		function()
		{
			$(this).hide();
		}
	);
	
	// applies onclick to all questions, in order to show the corresponding answer
	$('#faq > dt').each
	(
		function()
		{
			$(this).click
			(
				function()
				{
					$('#answer' + (this.id.match(/\d+/)) ).toggle();
				}
			).addClass('clickable underline'); // simulate an anchor
		}
	);

	// open the contact livehelp popup
	$('a[rel*="livehelp"]').click
	(
	 	function() 
		{
			popup('atendimento/livehelp.php', {width:500, height:400, name:'livehelp', dependent:true});
			return false;
		}
	);

	// validade contact form
	$('#frmContact').submit
	(
	 	function()
		{
			var Validator = new FormValidator();
			
			Validator.setup
			([
				{id : 'txt_nome'     , minLen  : 2},
				{id : 'txt_ddd'      , minLen  : 2, defType : 'number'},
				{id : 'txt_fone'     , minLen  : 7},
				{id : 'txt_email'    , defType : 'email'},
				{id : 'txt_mensagem' , minLen  : 2},
				{id : 'txt_assunto'  , minLen  : 2}
			]);
			 
			Validator.setMsgTarget('msgValidacao');
			
			return Validator.run({showErrors:true});
		}
	);
	
	// hides all images of products, except for the first
	$('#product-photos > li').not(':first)').each
	(
		function()
		{
			$(this).hide();
		}
	);
	
	// binds events to the links of thumbails' larger image
	$('#product-thumbs > li > a').each
	(		
		function()
		{
			var id = this.href.substr(this.href.indexOf('#'));
			
			$(this)
				.bind('mouseover', {id : id}, showBigPic)
				.bind('focus',     {id : id}, showBigPic);
		}
	);
	
	function showBigPic(args)
	{
		$('#photoHolder > img')
			.attr('src', $(args.data.id + ' > img')
			.attr('src'));
	}
	
	
	// form my data change
	if ($('#frmCadastro.changeData').length == 0)
	{
		// shows the selected sign-in form
		toggleTipoCadastro('f');
		$('#radPessoaFisica').bind('focus', function() { toggleTipoCadastro('f') });
		$('#radPessoaJuridica').bind('focus', function() { toggleTipoCadastro('j') });
	}
	else
	{
		var changeData = true;
	}
	
	function toggleTipoCadastro(tipo)
	{
		var showId, hideId, container;
		
		if (tipo == 'f')
		{
			showId = 'Fisica';
			hideId = 'Juridica';
		}
		else
		{
			showId = 'Juridica';
			hideId = 'Fisica';
		}
		
		// hide the container and disable all fields
		container = $('#pessoa' + hideId);
		container.hide();
		container.find('input, select').each
		(
			function()
			{
				$(this).attr('disabled', true);
			}
		)
		// show the container and enable all fields
		container = $('#pessoa' + showId);
		container.show();
		container.find('input, select').each
		(
			function()
			{
				$(this).removeAttr('disabled');
			}
		)
	}
	
	// validate signup form
	$('#frmCadastro').submit
	(
	 	function()
		{
			var fields, Validator = new FormValidator();
			
			if ($('#radPessoaFisica').attr('checked') === true)
			{
				fields = [
					{id : 'txtNome'     , minLen  : 2},
					{id : 'txtSobrenome', minLen  : 2},
					{id : 'txtCpf'      , minLen  : 5},
					{id : 'txtRg'       , minLen  : 5}
				];
			}
			else
			{
				fields = [
					{id : 'txtEmpresa', minLen  : 5},
					{id : 'txtContato', minLen  : 2},
					{id : 'txtCnpj'   , minLen  : 8}
				];
			}
			
			fields.push({id : 'txtEmail'        , defType : 'email'});
			fields.push({id : 'txtEmailRepetido', equals  : 'txtEmail'});
			fields.push({id : 'txtEndereco'     , minLen  : 2});
			fields.push({id : 'txtNumero'       , minLen  : 1, defType : 'number'});
			fields.push({id : 'txtBairro'       , minLen  : 2});
			fields.push({id : 'txtCidade'       , minLen  : 2});
			fields.push({id : 'cmbEstado'       , minLen  : 1});
			fields.push({id : 'cmbPais'         , minLen  : 1});
			fields.push({id : 'txtCep'          , minLen  : 3});

			if (changeData !== true)
			{
				fields.push({id : 'txtSenha'        , minLen  : 6});
				fields.push({id : 'txtSenhaRepetida', equals  : 'txtSenha'});
				fields.push({id : 'txtLogin'        , minLen  : 3});
			}

			Validator.setup(fields);
			Validator.setMsgTarget('msgValidacao');
			
			return Validator.run({showErrors:true});
		}
	);

	// apply some rounded borders
	
	// bugs in IE 6-
	if ($.browser.msie && parseInt($.browser.version) <= 6)
	{
		$('#product-info div').corner('bottom 15px');
	}
	else
	{
		$('#product-info div').corner('bottom 15px');
		$('#colorSelection').corner('15px');
	}

	
	// display a dialog with a message, if there's one
	var closeMsg = '<br /><span style="color:#999; font-size:10px">Para fechar esta mensagem, aperte ESC.</span>'
	switch ($.url('msg'))
	{
		case 'loginErr':
			$.fn.nyroModalManual
			({
				content   : 'O nome de usuário e/ou a senha fornecidos são inválidos' + closeMsg,
				minHeight : 40
			});
			setTimeout(function(){$.nyroModalRemove();}, (10).toMili());
			break;
			
		case 'loginBlocked':
			$.fn.nyroModalManual
			({
				content   : 'Seu login está bloqueado. Entre em contato conosco.' + closeMsg,
				minHeight : 40
			});
			setTimeout(function(){$.nyroModalRemove();}, (10).toMili());
			break;
			
		case 'loginDisabled':
			$.fn.nyroModalManual
			({
				content   : 'Seu login está inativo. Entre em contato conosco.' + closeMsg,
				minHeight : 40
			});
			setTimeout(function(){$.nyroModalRemove();}, (10).toMili());
			break;
			
		case 'loginInvalid':
			$.fn.nyroModalManual
			({
				content   : 'Seu login não está cadastrado ou sua senha está incorreta.<br />Cadastre-se, ou clique em "esqueci minha senha", caso a tenha esquecido.' + closeMsg,
				minHeight : 50
			});
			setTimeout(function(){$.nyroModalRemove();}, (10).toMili());
			break;

		case 'loginExpired':
			$.fn.nyroModalManual
			({
				content   : 'Atenção: sua sessão expirou! Por favor, faça o login novamente.' + closeMsg,
				minHeight : 40
			});
			setTimeout(function(){$.nyroModalRemove();}, (10).toMili());
			break;
			
		case 'cadastroAlt':
			$.fn.nyroModalManual
			({
				content   : 'Seus dados cadastrais foram alterados com sucesso!' + closeMsg,
				minHeight : 40
			});
			setTimeout(function(){$.nyroModalRemove();}, (10).toMili());
			break;
	}

	function showCats()
	{
		if ( elmCatsItems.not(':visible') )
		{
			elmCatsItems.slideDown(200);
		}
	}
	
	function callUrchin(strCode)
	{
		if (pageTracker && location.host.indexOf('.com') != -1)
		{
			pageTracker._trackPageview();
		}
	}

	var pageTracker =_gat._getTracker("UA-3908411-1");
		pageTracker._initData();
	
	callUrchin();
	
	if (location.pathname.indexOf('album.asp') != -1)
	{
		$('#photos li a').attr('rel', 'shadowbox[album]');

		Shadowbox.init();
	}
});

/**
 * Opens a stardard popup
 *
 * @author Rodrigo Henrique Paiva - rhpaiva[at]gmail.com
 *
 * @param string url The popup's URL.
 * @param object Optional. An object with the following possible parameters:
 *                          int    width        = popup width
 *                          int    height       = popup height
 *                          string name         = popup name
 *                          bool   checkBlocker = whether to check for a popup blocker
 *                          bool   dependent    = tells the popup to be dependent of the opener [it used to work for FireFox :( ]
 *                          string properties   = other possible custom properties not implemented here
 *                          bool   autoClose    = whether the popup must close itself after opening
 *                          bool   center       = whether the popup must open on the very center of screen
 *
 * @return object The reference to the created window
 */
function popup (url, config)
{ 	
	var largura      = (config.width > 0)          ? (config.width)             : (750),
		altura       = (config.height > 0)         ? (config.height)            : (500),
		propriedades = (config.properties != '')   ? (', ' + config.properties) : (''),
		dependent    = (config.dependent === true) ? (', dependent=yes, minimizable=no, dialog=yes, alwaysRaised=yes, modal=yes') : ('');
	
	var top  = 100, 
		left = 100;
	
	if (config.center !== false) 
	{ 
		left = (screen.width  - largura) / 2; 
		top  = (screen.height - altura ) / 2; 
	} 

	var propriedades = 'width=' + largura + ', height=' + altura + ',top=' + top + ', left=' + left + propriedades + dependent; 
	
	var popwin = window.open(url, config.name, propriedades); 
	
	if ((config.checkBlocker === true) && (popwin == null)) 
	{ 
		alert('Seu navegador possui bloqueador de pop-up.\n Por favor habilite a abertura de pop-up para este \n endereço e atualize esta página.'); 
		return false; 
	} 
	
	if (config.autoClose === true) 
	{
		popwin.close(); 
	} 
	else 
	{ 
		popwin.focus(); 
		return popwin; 
	}

}

function validaCpf(cpf)
{
	return {
		valid : isCpf( $('#' + cpf.id).val() ), 
		error : 'O campo <strong>"%field%"</strong> não contém um CPF válido.'
	};
}

function validaCnpj(cnpj)
{
	return {
		valid : isCnpj( $('#' + cnpj.id).val() ), 
		error : 'O campo <strong>"%field%"</strong> não contém um CNPJ válido.'
	};
}

function rand()
{
	var mili, rnd, limit;

	limit = rand.arguments[0];	

	if (limit > 0)
	{
		rnd  = Math.floor(Math.random() * limit) + 1;
	}
	else
	{
		mili  = new Date().getMilliseconds(); 	
		rnd   = Math.floor(Math.random() * mili) + 1;
		rnd  *= mili;
	}
	
	return rnd;
}