
/**
* Inicializa as funções assim que os elementos (DOM) são carregados
* @author Leonardo Souza <leonardo.souza@agenciaclick.com.br>
*/
jQuery(function() {

	VitrinePix._init();
	
	$('#excluir').click(function(e){
		if (!confirm('Tem certeza que deseja remover esta ocorrência?')){
			return false;
		}
	});
	
	$('#excluir_loja').click(function(e){
		if (!confirm('ATENÇÃO!\n\nTodos os produtos à venda nesta loja serão REMOVIDOS.\n\nPara ocultar temporariamente sua loja basta desativá-la.\n\nTem certeza que deseja remover sua loja?')){
			return false;
		}
	});
    
    $(".btCriarCamisetaTop, .btCriarCamiseta").click(function(){
        $("#div_loading").show();
		var link;
        link = $(this).attr('href');
        self.location.href = link;
        return false;
    })
        
    $(".btCriarCamisetaTop, .btCriarCamiseta").colorbox({width:"400px", inline:true, href:"#div_loading"});
	
	$(".a_info").colorbox({iframe:true,overlayClose:false,opacity:0.5,transition:'elastic',width:"630px",height:"580px"});
});

Number.prototype.formatMoney = function(c, d, t){
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

var VitrinePix = {
	/**
	* Função de chamada das outras funções que inicializam o site
	* @author Leonardo Souza <leonardo.souza@agenciaclick.com.br>
	*/
	_init: function() {
		try {
			//$(document).bind("contextmenu",function(e){return false;});
			
			this._viewProductDetail();
			this._showNavColors();
			this._showHideMenuItens();
			this._selectLayout();
			this._modalItens();
		} catch (e) {
			console.log('Error: ' + e.description);
		}
	},
		
	/**
	* Exibe o detalhe da estampa do camiseta
	* @author Leonardo Souza <webmaster@vitrinepix.com.br>
	*/
	_viewProductDetail: function() {
		try {
			$('.products dt img')
			.mouseover(function() {
			    var swap = $(this).attr('rel');
			    $(this).attr('rel',$(this).attr('src'));
			    $(this).attr('src',swap);
			})
			.mouseout(function() {
			    var swap = $(this).attr('rel');
			    $(this).attr('rel',$(this).attr('src'));
			    $(this).attr('src',swap);
			})
			
		} catch(e) {
			console.log('Error (_viewProductDetail): ' + e.description);
		}
	},
	
	/**
	* Navega entre os produtos a partir da cor
	* @author Leonardo Souza <webmaster@vitrinepix.com.br>
	*/
	_showNavColors: function() {
	    try {
			$('.colors a')
			.each(
			    function() {
			         $(this).css('background',$(this).html());		
			    }
			)
			.click(
			    function() {			    	
			    	if ( ! $(this).is('.noswap') )
			    	{
				    	var id_cor = $(this).attr('id').substring(4);
				        $('.colors a').removeClass('selected');
				        $(this).addClass('selected');
				        $('input#id_cor').val(id_cor);
				        $('#image-product').attr('src',$(this).attr('rel'));
				        
				        try {
					        var cor_tamanhos = eval('(' + 'tamanhos_cor_' + id_cor + ')');
					        
					        $("#tamanho").html('');
					        
					        if ( cor_tamanhos.tamanhos.length > 0 )
					        {
					        	$('p.size, p.othersize, p.price, p.button').show();
					        	$('p.nosize').hide();
					        	$.each(cor_tamanhos.tamanhos, function(i) {
						        	var option = new Option(this.tamanho, this.id_produto_tamanho);
					                // Use Jquery to get select list element
					                var dropdownList = $("#tamanho")[0];
					                
					                
			
					                if ($.browser.msie) dropdownList.add(option);
					                else dropdownList.add(option, null);
						        });
					        	
					        	$("#tamanho option:last").attr('selected',true);
					        	
					        	$('select#tamanho').trigger('change');
					        }
					        else
					        {
					        	$('p.size, p.othersize, p.price, p.button').hide();
					        	$('p.nosize').show();
					        }
				        }
				        catch (e) {  }	
				        return false;
				    }
			    }
			);
			
			try {
	            $('select#tamanho').bind('change click',function(){		            	
	            	var id_cor = $('.colors a.selected').attr('id').substring(4);	            
	            	var cor_tamanhos = eval('(' + 'tamanhos_cor_' + id_cor + ')');
	            	$('input#adicional').val(cor_tamanhos.tamanhos[this.selectedIndex].adicional);
	            	
        			var valor = parseFloat($('#valor').val());
        			var adicional = parseFloat($('#adicional').val());
        			var total = valor + adicional;
        			$('p.price').html('R$ '+total.formatMoney());

                    // mostrando o valor parcelado
                    var vezes = parseInt(total / VALOR_MINIMO_PARCELA);
                    if (vezes > 6)
                    {
                        vezes = 6;
                    }
                    
                    var boleto_com_desconto = total - (total * PORCENTAGEM_DESCONTO_BOLETO);
                    
                    $('p.priceAlt').html('ou '+vezes+'X de <strong class="valorParcela">R$ '+(total/vezes).formatMoney()+'</strong> sem juros no cartão');
                    $('p.priceAlt').append('<p class="precoBoleto">Boleto (à vista): <span>R$ '+ boleto_com_desconto.formatMoney() +'</span></p>');
                    
	            });
			} catch (e) {
				console.log('Error (_showNavColors): ' + e.description);
			}
			
		} catch (e) {
			console.log('Error (_showNavColors): ' + e.description);
		}
	},
	
	/**
	* Adiciona e/ou remove a quantidade de itens para compra
	* @author Leonardo Souza <webmaster@vitrinepix.com.br>
	*/
	_lessMoreItens: function(more,less) {
		try {
			$(more).click(
			    function() {
			        if($('.'+$(this).attr('rel')).val() == '') {
			            $('.'+$(this).attr('rel')).val(0);
			        }
			        $('.'+$(this).attr('rel')).val(parseInt($('.'+$(this).attr('rel')).val())+1);
			            
			        return false;
			    }
			);
			
			$(less).click(
			    function() {
			         if($('.'+$(this).attr('rel')).val() == '') {
			            $('.'+$(this).attr('rel')).val(1);
			        }
			        if(parseInt($('.'+$(this).attr('rel')).val()) > 1) {
			            $('.'+$(this).attr('rel')).val(parseInt($('.'+$(this).attr('rel')).val())-1);
			        }
			        return false;
			    }
			);
			
		} catch (e) {
			console.log('Error: ' + e.description);
		}
	},
	
	/**
	* Exibe/oculta sub
	* @author Leonardo Souza <webmaster@vitrinepix.com.br>
	*/
	_showHideMenuItens: function() {
		try {
		    $('#menu dt a').each(
		        function() {
		            if($(this).parent().next('dd').length == 1) {
		                $(this).click(
		                    function() {
		                        if($(this).parent().parent().hasClass('active')) {
		                            $(this).parent().parent().find('dd').animate({"height": "hide", "opacity": 1}, {"duration": "fast"});
		                            $(this).parent().parent().removeClass();
		                        } else {    		                        
		                            $('.active').removeClass().find('dd').animate({"height": "hide", "opacity": 1}, {"duration": "fast"});
		                            $(this).parent().parent().addClass('active');
		                            $(this).parent().parent().find('dd').animate({"height": "show", "opacity": 1}, {"duration": "fast"});
		                            
                                }
    		                    return false;       	                        
		                    }
		                );
		            }
		           
		        }
		    );
		    
		    $('#menu dt a.selected').each(
		        function() {
		            $(this).click();
		        }
		    );
		} catch (e) {
			console.log('Error: ' + e.description);
		}
	},
	
	/**
	* Marca os layouts corretamente durante a escolha do usu�rio
	* @author Leonardo Souza <webmaster@vitrinepix.com.br>
	*/
	_selectLayout: function() {
	    try {
	        $('.coreslayout input:checked').parent().parent().addClass('selected');
	        
	        $('.coreslayout a').colorbox({overlayClose:false,opacity:0.5,transition:'elastic'});
			
			$('.coreslayout input:radio').add('.coreslayout a').click(function() {
			    $('dl').removeClass('selected');
			    $(this).parent().parent().addClass('selected');
			    $('dl.selected input:radio').attr('checked','checked');
			    if($(this)[0].tagName == 'A') {
                    return false;
                }
			});
			
			
		} catch (e) {
			console.log('Error (_showNavColors): ' + e.description);
		}
	},
	
	_modalItens: function() {	   
		$("a[rel=modal]").colorbox({overlayClose:false,opacity:0.5,transition:'elastic'});
	}	
};


/* Compre - link nos banners de acordo com o href do botão */

$("#vendasuasimagens").click( function() {	
	window.location=$(this).find("a.lnkControl").attr("href");
});

$("#montesualoja").click( function() {			
window.location=$(this).find("a.criarloja").attr("href");
});


/* Combo Fale Conosco */

$("#comboFale").change( function(){
	if ($(this).val() <= '2'){
		$("#numPedido").show();
	}else {
		$("#numPedido").hide();
	}
	$("#pergunta").val($("#comboFale :selected").text());
});


/* Local - Detalhes produtos */

$(".boxPosicaoProduto a").click( function() {	
	$(".boxPosicaoProduto a").removeClass("active");
	$(this).addClass("active");
});

$(".faqPrincipal .perg a").click( function() {
	$("#r"+ this.id).toggle();
});

$(".faq .perg a").click( function() {
	$("#r"+ this.id).toggle();
});

$(".topico a").click( function() {
	$("#f"+ this.id).toggle();
});

$(".helpFormsContent input#valor_comissao").focus( function() {	
	$(".helpForms#valorcomissao").fadeIn();
});

$(".helpFormsContent input,.helpFormsContent textarea").focus( function() {	
	$(".helpForms#"+ this.title).fadeIn();	
});

$(".helpFormsContent input.comiss").focus( function() {
	$(".editarEstampa").css("margin-top","40px");
});

$(".helpFormsContent input,.helpFormsContent textarea").blur( function() {	
	$(".helpForms").fadeOut();
	
});

/*
$(document).ready( function() {		
	$(".alertaNovidades").slideDown();	  	
});
*/

$(".btEspec").mouseover( function() {
	$(".infoEspec").fadeIn();
});
$(".btEspec").mouseout( function() {
	$(".infoEspec").fadeOut();
});

/*
$(document).ready( function() {
	$("input#imagem_topo").filestyle({ 
		 image: "/images/bt/procurar_file.png",
		 imageheight : 19,
		 imagewidth : 85,
		 width : 160
	});
});

$(document).ready( function() {
	$("input#imagem_perfil").filestyle({ 
		 image: "/images/bt/procurar_file.png",
		 imageheight : 19,
		 imagewidth : 85,
		 width : 114
	});
});
*/

