/**
 * Carrinho de compras
 * @class Cart
 * @author neto
 */
function Cart(){
	$( '#limpar' ).click( Cart.clear );
	$( 'td.tquantidade input' ).change( Cart.recalculate );
	$( "a#botao_comprar img.botao_comprar_img" ).click( Cart.add );
	$( "input.produto_input_quantidade " ).change( Cart.validate );
	$( "tfoot tr.frete span.flecha" ).click( Cart.calcFrete );
	$( "tfoot tr td.fechar" ).click( Cart.fechar );
	
	$( "select.produto_input_cor" ).change( function(){
		var src = $(this).val();
		
		if ( src.length ){
			var texto = $(this).find( 'option' ).filter( ':selected' ).text();
			$( "img#produto_image_cor" ).replaceWith( [ '<img id="produto_image_cor" src="/Imagens/cores/' , src , '" title="' , texto , '" />' ].join( "" ) );
		}
	} );
}

/**
 * Adiciona um novo item ao carrinho
 * @return Boolean
 */
Cart.add = function(){
	var numero		= parseFloat( $( "input.produto_input_quantidade " ).val() );
	var quantidade	= isNaN( numero ) ? 0 : numero;
	var retorno		= false;
	var cor			= parseInt( $( "select.produto_input_cor" ).find( 'option' ).filter( ':selected' ).attr( 'ref' ) );
	var tamanho		= parseInt( $( "select.produto_input_tamanho" ).find( 'option' ).filter( ':selected' ).val() );
	
	if ( ( !isNaN( cor ) && !isNaN( tamanho ) ) && ( cor != 0 && tamanho != 0 ) ){	
		if ( quantidade >= 1 ){
			var href		= $( "a#botao_comprar" ).attr( "href" );
			var parts		= href.split( '#Produtos' ).join( '' ).split( '/produtos/' ).join( '' ).split( '_' ).join( ' ' ).split( '/' );
			
			if ( parts.length == 3 ){
				var obj = {
					quantidade	: quantidade,
					grupo		: parts[ 0 ],
					linha		: parts[ 1 ],
					produto		: parts[ 2 ],
					cor			: cor,
					tamanho		: tamanho
				};
				
				$.ajax( {
					type		: "POST",
					url			: "/ajax/carrinho/add",
					data		: obj,
					async		: true,
					dataType	: "json",
					success		: function( msg ){
						if ( msg.success !== true ){
							alert( [ 'Ocorreu um erro ao adicionar ao carrinho\n' , msg.message , ', tente novamente.' ].join( '' ) );
						} else {
							Cart.update();
							
							if ( ( msg.message != undefined ) && ( msg.message.length ) ){
								if ( confirm( [ msg.message , '\nDeseja voltar a' , parts[ 1 ] , '?' ].join( ' ' ) ) ){
									window.location.href = [ '/produtos' , parts[ 0 ] , parts[ 1 ] ].join( '/' );
								}
							}
						}
					}
				} );
			}
		} else {
			$( "input.produto_input_quantidade " ).val( '0' );
			alert( 'Informe a quantidade desejada' );
		}
	} else {
		if ( isNaN( cor ) || cor == 0 ) alert( 'Escolha uma cor' );
		else if ( isNaN( tamanho ) || tamanho == 0 ) alert( 'Escolha um tamanho' );
	}
	
	return( retorno );
};

Cart.calcFrete = function(){
	var cep = [ $( 'input#cep1' ).val() , $( 'input#cep2' ).val() ].join( '' ).split( ' ' ).join( '' );
	
	if ( cep.length ){	
		$.ajax( {
			type		: "POST",
			url			: "/ajax/carrinho/calcFrete",
			data		: { cep : cep },
			async		: true,
			dataType	: "json",
			success		: function( msg ){
				if ( msg.success !== true )
					alert( "Ocorreu um erro ao calcular o frete, tente novamente." );
				else {
					$( 'tfoot tr.frete td.tfrete' ).text( Cart.monetary( msg.total ) );
					Cart.recalculate();
				}
			}
		} );
	} else alert( 'Informe o CEP do endereço de entrega para calcular o frete.' );
};

Cart.fechar = function(){
	var frete = $( 'tfoot tr.frete td.tfrete' ).text();
	
	if ( parseFloat( frete.split( 'R$ ' ).join( '' ) ) > 0 ){
		if ( confirm( 'Deseja realmente fechar o pedido ?' ) ){
			window.location.href = '/identificacao';
		}
	} else {
		alert( 'Informe o CEP do endereço de entrega e clique em "Calcular" para fazer o cálculo do frete.' );
	}
};

/**
 * Limpa todo o carrinho
 * @return void
 */
Cart.clear = function(){
	if ( confirm( 'Deseja limpar todo o conteúdo do seu carrinho ?' ) ){
		$.ajax( {
			type		: "POST",
			url			: "/ajax/carrinho/clear",
			data		: {},
			async		: true,
			dataType	: "json",
			success		: function( msg ){
				if ( msg.success !== true )
					alert( "Ocorreu um erro ao limpar o carrinho, tente novamente." );
				
				Cart.update();
				Cart.isEmpty();
			}
		} );
	}
};

/**
 * Exclui um produto do carrinho
 * @param Number offset A posição do produto no carrinho
 * @param String rowid O id da linha do produto
 * @return void
 */
Cart.exclude = function( offset , rowid ){
	if ( confirm( 'Deseja esse produto do seu carrinho ?' ) ){
		var total = parseFloat( $( [ [ 'tbody tr' , rowid ].join( '' ) , 'td.ttotal' ].join( ' ' ) ).text().split( 'R$' ).join( '' ).split( ' ' ).join( '' ).split( ',' ).join( '.' ) );
		var geral = Cart.getTotal( false );
		
		$.ajax( {
			type		: "POST",
			url			: "/ajax/carrinho/exclude",
			data		: { item : offset },
			async		: true,
			dataType	: "json",
			success		: function( msg ){
				if ( msg.success !== true ){
					alert( msg.message );
				} else {
					$( 'tfoot tr td.total' ).text( Cart.monetary( geral - total ) );
					$( [ 'table#produtoscarrinho tbody tr' , rowid ].join( '' ) ).remove();
					Cart.recalculate();
					Cart.update();
					Cart.isEmpty();
				}
			}
		} );
	}
};

/**
 * Recupera a quantidade de um item no carrinho
 * @param String rowid O id da linha do produto
 * @return Number
 */
Cart.getQtd = function( rowid ){
	var items = parseInt( $( [ 'tbody tr#' , rowid , ' td.tquantidade input' ].join( '' ) ).val() );
	
	if ( isNaN( items ) || ( items < 1 ) ) items = 1;
	
	$( [ 'tbody tr#' , rowid , ' td.tquantidade input' ].join( '' ) ).val( items );
	
	return items;
};

/**
 * Recupera o total de um item do carrinho
 * @param String rowid O id da linha do produto
 * @param Boolean monetary Define se o total será formatado
 * @return Number|String
 */
Cart.getItemTotal = function( rowid , monetary ){
	var items = parseInt( $( [ 'tbody tr#' , rowid , ' td.tquantidade input' ].join( '' ) ).val() );
	var total = parseFloat( $( [ 'tbody tr#' , rowid , ' td.tpreco' ].join( '' ) ).text().split( 'R$' ).join( '' ).split( ' ' ).join( '' ).split( ',' ).join( '.' ) );
	
	if ( isNaN( items ) || ( items < 1 ) ) items = 1;
	
	$( [ 'tbody tr#' , rowid , ' td.tquantidade input' ].join( '' ) ).val( items );
	
	if ( ( monetary == undefined ) || ( !monetary ) )
		return total * items;
	else
		return Cart.monetary( total * items );
};

/**
 * Recupera o total geral do carrinho
 * @param Boolean monetary Define se o total será formatado
 * @return
 */
Cart.getTotal = function( monetary ){
	if ( ( monetary == undefined ) || ( !monetary ) )
		return parseFloat( $( "tfoot tr td.total" ).text().split( 'R$' ).join( '' ).split( ' ' ).join( '' ).split( ',' ).join( '.' ) );
	else
		return Cart.monetary( parseFloat( $( "tfoot tr td.total" ).text().split( 'R$' ).join( '' ).split( ' ' ).join( '' ).split( ',' ).join( '.' ) ) );
};

/**
 * Verifica se o carrinho contém algum item
 * @param Boolean redirect Define se será redirecionado caso o carrinho estiver vazio
 * @return Boolean
 */
Cart.isEmpty = function( redirect ){
	var ret = Cart.getTotal() == 0;
	
	redirect = ( redirect == undefined ) ? true : redirect;
	
	$( 'table#produtoscarrinho' ).replaceWith( '<p class="carrinho_vazio">Nenhum produto no carrinho</p>' );
	
	if ( !ret && redirect ) window.location.href = "/produtos";
	
	return ret;
};

/**
 * Formata um número para o padrão R$ #.##
 * @param Number number O número que será formatado
 * @return String
 */
Cart.monetary = function( number ){
	var ret = "";
	
	if ( number != 0 ) {
		ret = [ '' , Math.round( number * 1000 ) / 1000 ].join( '' );
		
		if ( ( parts = ret.split( "." ) ).length == 2 ) {
			if ( parts[ 1 ].length == 1 ) {
				ret = [ 'R$ ' , ret  , '0' ].join( '' );
			}
		} else ret = [ 'R$ ' , ret , '.00' ].join( '' );
	} else ret = 'R$ 0.00';
	
	return ret;
};

/**
 * Recalcula o carrinho
 * @return void
 */
Cart.recalculate = function(){
	var item = $(this);
	var total = 0;
	var ids = [];
	
	$( 'tbody tr.produtos_item.detalhes' ).each( function(){
		var parcial = Cart.getItemTotal( $(this).attr( 'id' ) );
		
		$( [ 'tbody tr#' , $(this).attr( 'id' ) , ' td.ttotal' ].join( '' ) ).text( Cart.monetary( parcial ) );
		
		ids.push( [ $(this).attr( 'id' ).split( 'row' ).join( '' ) , Cart.getQtd( $(this).attr( 'id' ) ) ].join( ':' ) );
		
		total += parcial;
	} );
	
	if ( total > 0 ){
		$.ajax( {
			type		: "POST",
			url			: "/ajax/carrinho/qtds",
			data		: { 'ids[]':ids },
			async		: true,
			dataType	: "json",
			success		: function( msg ){
				if ( msg.success ){
					if ( msg.items ){
						$( 'tfoot tr.frete td.tfrete' ).each( function(){
							total += parseFloat( $(this).text().split( 'R$ ' ).join( '' ).split( ',' ).join( '' ) );
						} );
	
						$( 'tfoot tr td.total' ).text( Cart.monetary( total) );
					} else {
						total = 0;
						$( 'tfoot tr.frete td.tfrete' ).text( 'R$ 0.00' );
						$( 'tfoot tr td.total' ).text( Cart.monetary( total) );
					}
				} else {
					item.val( 0 );
					Cart.recalculate();
					alert( msg.message );
				}
			}
		} );
	} else $( 'tfoot tr.frete td.tfrete' ).text( 'R$ 0.00' );
	
	$( 'tfoot tr td.total' ).text( Cart.monetary( total) );
};

Cart.update = function(){
	$.ajax( {
		type		: "POST",
		url			: "/ajax/carrinho/items",
		data		: {},
		async		: true,
		dataType	: "json",
		success		: function( msg ){
			if ( msg.success !== true ){
				alert( msg.message );
			} else {
				if ( msg.items >= 1 ){
					$( 'div#carrinho' ).replaceWith( [ '<div id="carrinho"><a class="vercarrinho" rel="no-follow" href="/carrinho" title="Ver meus produtos">Você tem <span class="carrinho_total_itens">' , msg.items , '</span> ' , msg.items > 1 ? 'itens' : 'item' , ' no carrinho</a></div>' ].join( '' ) );
				} else {
					$( 'div#carrinho' ).replaceWith( '<div id="carrinho"><img id="carrinho_ico" style="width: 29px; height: 30px; background:transparent url(\'/Imagens/cart_ico.png\') no-repeat; _background: none; _filter : progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'/Imagens/cart_ico.png\', sizingMethod=\'scale\');" src="/Imagens/dot.gif" title="Meu Carrinho" alt="carrinho" /><p>Seu carrinho está vazio</p></div>' );
				}
			}
		}
	} );
};

Cart.validate = function(){
	var numero = parseInt( $(this).val() );
	
	if ( isNaN( numero ) || ( numero < 0 ) ) numero = 0;
	
	$( "input.produto_input_quantidade " ).val( numero );
	return( true );
};

$( Cart );