﻿var lib = {};

var formataReal = function(v1) {
	v1 = new String(v1);
	var s = v1.indexOf('.'), a, r;
	if ( s > -1 ) {
		a = new String(v1.substring(0,s));
		r = new String((v1.length-s >= 3 ) ? v1.substr(s+1,2) : v1.substr(s+1,1) + '0') ;
	} else {
		a = new String(v1);
		r = '00';
	}		
	return 'R$ ' + a + ',' + r;
}

var incluirAjax = function(href) {
	if ( href.indexOf('IsAjax') > 0 ) {
		return href;
	}
	if ( href.indexOf('?') > 0 ) {
		return href.replace('?','?IsAjax=True&');
	} else {
		return href + '?IsAjax=True';
	}
}

lib.comum = {
	init : function() {
		$(function() {
			var $bTexto = $("#busca-main-texto")
				.focus(function() {
					if ( this.value == 'BUSCA' ) {
						this.value = '';
					}
				}).blur(function() {
					if ( this.value.length == 0 ) {
						this.value = 'BUSCA';
					}
				});
			$("#busca-main-form")
				.submit(function() {
					if ( $bTexto.val().length < 3 ) {
						alert('A busca deve possuir pelo menos 3 caracteres.');
						return false;
					}
				 });
			$("a.modalLink")
				.each(function() {
					this.href = incluirAjax(this.href);
					$(this).colorbox( { opacity : 0.5, maxWidth : '50%', maxHeight : '50%', close : 'fechar' });
				});
			$("a#bt-cadastro-news-promo")
				.each(function() {
					this.href = incluirAjax(this.href);
					$(this).colorbox( { opacity : 0.5, height : 450, close : 'fechar' });
				});
			$("div.lista-localizacao a:last-child").each(function(i) {
				var $this = $(this);														  
				$this.html('<b>' + $this.html() + '</b>');
			});
			$("select.selRedireciona")
				.change(function() {
					if ( $(this).val().length > 0 ) {
						window.location.href = $(this).val();
					}
				});
			$("a.link-modal-nova-janela")
				.live('click',function() {
					$.fn.colorbox.close();
				});
			$("#form_news_promo form")
				.live('submit',function() {
					$.post( this.action,
							$(this).serialize(),
							function(data) {
								$("#form_news_promo").html('<h3>Cadastro enviado com sucesso.</h3>Esta janela vai fechar daqui a 3 segundos...');
								window.setTimeout($.fn.colorbox.close,2500);
							});
					return false;
				});
											  
	   });
	},
	formPromo : function() {
		$(function() {
			
			
		});
	}
};

lib.home = {
	init : function() {
		$(function() {
			var $bannerPop = $("#banner-popup");
			
			$bannerPop.children("a.banner-fechar").click(function() { $bannerPop.hide(); });
			
			$bannerPop.fadeIn('slow',function() {
					setTimeout(function() { $bannerPop.fadeOut("slow"); },5000);				
				});
		});
	}
};

lib.carrinho = {
	valores : {
		frete : 0,
		embalagem : 0,
		desconto : 0,
		cupomTipo : 'val'
	},
	itens : [],
	init : function() {
		$(function() {
			var $carrinhoCep = $("#carrinho-entregacep"),
				$formSacola = $("#formsacola");

			// Função que altera a quantidade
			var alteraQuant = function($t) {
				var $div = $t.parent().parent();
				var $v = $div.find("input.quantprod");
				var $prod = $div.find("input.idprod");
				var i = $.grep(lib.carrinho.itens,function(it) { return ( it.IdProd == $prod.val()); });
				if ( i.length == 0 ) {
					alert('erro!');
					return false;
				}
				i = i[0];
				var q = parseInt($v.val());
				var q_old = q;
				var d = $t.attr('alt');
				if ( d == 'aumenta' ) {
					$v.val(++q);
				} else if ( d == 'diminui') {
					if ( q > 0 ) {
						$v.val(--q);
					}
				} else {
					$v.val(q);
				}
				if ( q == 0 ) {
					if ( ! confirm('Este produto será removido do carrinho. Deseja continuar?') ) {
						$v.val(q_old);
						return false;
					}
				}
				$formSacola.submit();
			};

			$carrinhoCep.mask("99999-999");
			$("#status-carrinho div.quantidade-prod")
				.click(function(ev) {
					var $t = $(ev.target);
					if ( $t.is("img") ) {
						alteraQuant($t);
					}
				});
		});
	},
	calcula : function() {
	}
}

lib.produto = {
	permite_zoom : false,
	id_produto : null,
	init : function() {
		$(function() {
			/*var $foto = $("#foto-grande a").jqzoom({
				zoomWidth : 300,
				zoomHeight: 300,
				xOffset : 150
			});
			
			var $thumbFotos = $("#holder-fotos-peq ul");
			
			var timerThumbs;
			var moveDir = -1;
			var moveThumbs = function() {
				$thumbFotos.stop(true);
				var mLeft = parseInt($thumbFotos.css('marginLeft').replace('px',''));
				// seta esquerda
				if ( moveDir < 0 ) {
					if ( mLeft < 0 ) {
						$thumbFotos.css('marginLeft',mLeft+8);
					}
				// seta direita
				} else {
					if ( mLeft-35 > -1*($thumbFotos.width()-200) ) {
						$thumbFotos.css('marginLeft',mLeft-8);
					}
				}

			};
			$("#fotinhas #fechamento")
				.children("#seta-esq")
					.mouseenter(function() {
						moveDir = -1;
						moveThumbs();
						timerThumbs = setInterval(moveThumbs,80);
					}).mouseleave(function() {
						clearInterval(timerThumbs);
					}).end()
				.children("#seta-dir")
					.mouseenter(function() {
						moveDir = 1;
						moveThumbs();
						timerThumbs = setInterval(moveThumbs,80);
					}).mouseleave(function() {
						clearInterval(timerThumbs);
					}).end();
			if ( $foto.hasClass("comZoom") ) {
			}*/
			
			var $fotoZoom = $("#foto-zoom").hide();
			var $imgZoom = $fotoZoom.children("img");
			var $infoLupa = $("#lupinha");
			var $foto = $("#foto-grande img")
				.click(function() {
					if ( lib.produto.permite_zoom = false ) {
						return false;
					}
					if ( $fotoZoom.is(":visible") ) {
						$fotoZoom.fadeOut('slow');
					} else {
						$imgZoom.attr('src',$foto.attr('src').replace('m.jpg','g.jpg'));
						$fotoZoom.fadeIn('slow');
					}
				});

			var fotoAtual = 0;
			var posZoom = $foto.parent().offset();
			$fotoZoom
				.click(function() {
					$fotoZoom.fadeOut('slow');	 
				});
			var $thumbFotos = $("#holder-fotos-peq ul")
				.click(function(e) {
					var $t = $(e.target);
					if ( $t.is("img") ) {
						var i = $t.parent().index();
						$fotoZoom.fadeOut('slow');
						$thumbFotos.animate( { marginLeft : ((i*-1*60)+60) + 'px'}, 1000 );
						$foto.fadeOut('slow',function() {
							$foto.attr('src',$t.attr('src')).fadeIn('slow');
							if ( $foto.width() > 180 ) $foto.width(180);
							// Permite zoom
							if ( $foto.width() == 180 ) {
								$infoLupa.show();							
								lib.produto.permite_zoom = true;
								$foto.addClass("comZoom");
							} else {
								$infoLupa.hide();
								lib.produto.permite_zoom = false;							
								$foto.removeClass("comZoom");
							}
						});
					}
					return false;
				});
			var timerThumbs;
			var moveDir = -1;
			var moveThumbs = function() {
				$thumbFotos.stop(true);
				var mLeft = parseInt($thumbFotos.css('marginLeft').replace('px',''));
				// seta esquerda
				if ( moveDir < 0 ) {
					if ( mLeft < 0 ) {
						$thumbFotos.css('marginLeft',mLeft+8);
					}
				// seta direita
				} else {
					if ( mLeft-35 > -1*($thumbFotos.width()-200) ) {
						$thumbFotos.css('marginLeft',mLeft-8);
					}
				}

			};
			$("#fotinhas #fechamento")
				.children("#seta-esq")
					.mouseenter(function() {
						moveDir = -1;
						moveThumbs();
						timerThumbs = setInterval(moveThumbs,80);
					}).mouseleave(function() {
						clearInterval(timerThumbs);
					}).click(function() {
						
					}).end()
				.children("#seta-dir")
					.mouseenter(function() {
						moveDir = 1;
						moveThumbs();
						timerThumbs = setInterval(moveThumbs,80);
					}).mouseleave(function() {
						clearInterval(timerThumbs);
					}).click(function() {
						var mLeft = parseInt($thumbFotos.css('marginLeft').replace('px',''));
					}).end();
			$("#opcoes-inclusao-divulgacao a")
				.each(function() {
					this.href = incluirAjax(this.href);
					$(this).colorbox({ close : '', opacity : 0.5 });
				});
			$("#ofertas-compre-junto div.comprejunto")
				.click(function() {
					var $this = $(this);
					var id = this.id.replace('cj_','');
					
					$.fn.colorbox({ href : 'http://www.abracadabra.com.br/site/prod-detail-ajax.cfm?IDProdCompreJunto='+lib.produto.id_produto+'&IDProd='+id, width : '50%', height: '50%', opacity : 0.3, close : 'fechar' });
				});
			$("#midias li").click(function() {
				_gaq.push(['_trackEvent', 'MidiasSociais', 'Clique', $(this).data('tipo')]);
			});
	   });
	}
}

lib.resultados = {
	init : function() {
		$(function() {

		});	
	}
};
