$(document).ready(function() {

	// COMECO - FancyBox Login por Henrique R. Pohl

		var nav = $('.menu-stick-base');

			$(window).scroll(function () {

				if ($(this).scrollTop() > 192) {
					nav.addClass("menu-stick").fadeIn( 200 );
                                        $('#topcontrol').css('opacity', '100');
				} else {
					nav.removeClass("menu-stick").fadeOut( 200 );
                                        $('#topcontrol').css('opacity', '0');
				}

			});

	// FIM - FancyBox Login por Henrique R. Pohl


	$('#login2').live('click', function(){
		validatesuspenso(false);
	});

	$('.js-newsletter-login').on('click', function(){
		validatesuspenso(true);	
	});

	function validatesuspenso(verify){
		$.ajax({
			url		 : 'index.php?route=account/login/validate_suspenso',
			type	 : 'POST',
			data     : $('#frm_account input[type=\'text\'], input[type=\'hidden\'], input[type=\'password\']'),
			dataType : 'json',
			success  : function(json){
				if(json['error']){
					if (json['error']['warning'] || json['warning']){
						$('#msg_user').html('<span class="error"><b>Atenção: </b>Usuário ou senha inválidos.</span><br>');
						$(".password_input").val( '' );

						if( $("input[name=\'password\']").val() === "")
							{
								$("input[name=\'password\']").css({"border-color" : "#da251c"});
							}else{

								$("input[name=\'password\']").css({"border-color" : "#D4D4D4"});

							}

						var email = $("input[name=\'email\']").val();
						if(email !== "")
							{

							var filtro = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
							if(filtro.test(email))
							{
							$("input[name=\'email\']").css({"border-color" : "#D4D4D4"});
							return true;

							} else {

							$("input[name=\'email\']").css({"border-color" : "#da251c"});
							return false;
							}

							}else{

							$("input[name=\'email\']").css({"border-color" : "#da251c"});
						}



						//parent.$.fancybox.resize();
					}

				}else if(json['redirect']){
					if(verify){
						function setCookie(cname, cvalue, exdays) {
							var d = new Date();
							d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
							var expires = "expires="+d.toUTCString();
							document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
						}
						setCookie('close_newsletter', true, 10);							
					}	
					location = json['redirect'];
				}
			}
		});		
	}

	// FIM - FancyBox Login na HOME por Henrique R. Pohl


	/* Search */
	$('.button-search').bind('click', function() {
		url = $('base').attr('href') + 'index.php?route=product/search';

		var search = $('input[name=\'search\']').attr('value');

		if (search) {
			url += '&search=' + encodeURIComponent(search);
		}

		location = url;
	});

	$('#header input[name=\'search\']').bind('keydown', function(e) {
		if (e.keyCode === 13) {
			url = $('base').attr('href') + 'index.php?route=product/search';

			var search = $('input[name=\'search\']').attr('value');

			if (search) {
				url += '&search=' + encodeURIComponent(search);
			}

			location = url;
		}
	});

	$('.button-search-stick').bind('click', function() {
			url = $('base').attr('href') + 'index.php?route=product/search';

			var search = $('input[name=\'search_stick\']').attr('value');

			if (search) {
				url += '&search=' + encodeURIComponent(search);
			}

			location = url;
	});

	$('#search input[name=\'search_stick\']').bind('keydown', function(e) {
		if (e.keyCode === 13) {
			url = $('base').attr('href') + 'index.php?route=product/search';

			var search = $('input[name=\'search_stick\']').attr('value');

			if (search) {
				url += '&search=' + encodeURIComponent(search);
			}

			location = url;
		}
	});

	/* Ajax Cart */
	$('#cart > .heading a').live('click', function() {
		$('#cart').addClass('active');

		$('#cart').load('index.php?route=module/cart #cart > *');

		$('#cart').live('mouseleave', function() {
			$(this).removeClass('active');
			$('.cart-stick #cart').removeClass('active');
		});
	});


	/* Ajax Cart */
	$('.cart-stick #cart > .heading a').live('click', function() {
		$('.cart-stick #cart').addClass('active');

		$('.cart-stick #cart').load('index.php?route=module/cart #cart > *');

		$('.cart-stick #cart').live('mouseleave', function() {
			$(this).removeClass('active');
			$('#cart').removeClass('active');
		});
	});

	/* Mega Menu */
	$('#menu ul > li > a + div').each(function(index, element) {
		// IE6 & IE7 Fixes
		if ($.browser.msie && ($.browser.version == 7 || $.browser.version == 6)) {
			var category = $(element).find('a');
			var columns = $(element).find('ul').length;

			$(element).css('width', (columns * 143) + 'px');
			$(element).find('ul').css('float', 'left');
		}

		var menu = $('#menu').offset();
		var dropdown = $(this).parent().offset();

		i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());

		if (i > 0) {
			$(this).css('margin-left', '-' + (i + 5) + 'px');
		}
	});

	// IE6 & IE7 Fixes
	if ($.browser.msie) {
		if ($.browser.version <= 6) {
			$('#column-left + #column-right + #content, #column-left + #content').css('margin-left', '195px');

			$('#column-right + #content').css('margin-right', '195px');

			$('.box-category ul li a.active + ul').css('display', 'block');
		}

		if ($.browser.version <= 7) {
			$('#menu > ul > li').bind('mouseover', function() {
				$(this).addClass('active');
			});

			$('#menu > ul > li').bind('mouseout', function() {
				$(this).removeClass('active');
			});
		}
	}

	$('.success img, .warning img, .attention img, .information img').live('click', function() {
		$(this).parent().fadeOut('slow', function() {
			$(this).remove();
		});
	});
});

function getURLVar(key) {
	var value = [];

	var query = String(document.location).split('?');

	if (query[1]) {
		var part = query[1].split('&');

		for (i = 0; i < part.length; i++) {
			var data = part[i].split('=');

			if (data[0] && data[1]) {
				value[data[0]] = data[1];
			}
		}

		if (value[key]) {
			return value[key];
		} else {
			return '';
		}
	}
}

function addToCart(product_id, quantity) {
  if ($('body').data('login') == false) {
    $('#logar').trigger('click');
    return;
  }
	
	quantity = typeof(quantity) != 'undefined' ? quantity : 1;
    $.ajax({
		url: 'index.php?route=checkout/cart/add',
		type: 'post',
		data: 'product_id=' + product_id + '&quantity=' + quantity,
		dataType: 'json',
		success: function(json) {


		$('.success, .warning, .attention, .information, .error').remove();


            if(json['error']){

				$('#notification').css( "position", "absolute" );
				 $('#notification').css( "margin-left", "auto" );
				 $('#notification').css( "margin-right", "auto" );
				 $('#notification').css( "margin-bottom", "auto" );
				 $('#notification').css( "margin-top", "auto" );
				 $('#notification').css( "left", "0" );
				 $('#notification').css( "right", "0" );
				 $('#notification').css( "top", "0" );
				 $('#notification').css( "bottom", "0" );
				 $('#notification').css( "width", "725px" );
				 $('#notification').css( "max-width", "90%" );
				 $('#notification').css( "height", "42px" );

                if(json['error']['prodcart']){
     				$('#notification').html('<div class="warning" style="display: none; position:relative; z-index:9999; border: 1px solid #E76453;' +
				'-webkit-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); -moz-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30);">' + json['error']['prodcart'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
    				$('#cart-total').html(json['total']);

    				//$('.success').fadeIn('slow');

					//$('.success').offset({ top: 10, left: 30});
					$('.warning').fadeIn('slow');
					$('.warning').animate({
					top: $(document).scrollTop()
					});
					var y_fixo = $('.warning').offset().top;
					$(window).scroll(function () {
					$('.warning').animate({
					top: $(document).scrollTop()
					},{duration:500,queue:false}
					);
					});

					//$('html, body').animate({ scrollTop: 0 }, 'slow');

                }

                if(json['error']['error_logged']){

					//alert("wow");

					$('#notification').css( "position", "absolute" );
					 $('#notification').css( "margin-left", "auto" );
					 $('#notification').css( "margin-right", "auto" );
					 $('#notification').css( "margin-bottom", "auto" );
					 $('#notification').css( "margin-top", "auto" );
					 $('#notification').css( "left", "0" );
					 $('#notification').css( "right", "0" );
					 $('#notification').css( "top", "0" );
					 $('#notification').css( "bottom", "0" );
					 $('#notification').css( "width", "725px" );
					 $('#notification').css( "max-width", "90%" );
					 $('#notification').css( "height", "42px" );

     				$('#notification').html('<div class="warning" style="display: none; position:relative; z-index:9999; border: 1px solid #E76453;' +
					'-webkit-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); -moz-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30);">' +  json['error']['error_logged'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

    				$('#cart-total').html(json['total']);

    				//$('html, body').animate({ scrollTop: 0 }, 'slow');

					//$('.warning').fadeIn('slow');

					//$('.success').offset({ top: 10, left: 30});
					$('.warning').fadeIn('slow');
					$('.warning').animate({
					top: $(document).scrollTop()
					});
					var y_fixo = $('.warning').offset().top;
					$(window).scroll(function () {
					$('.warning').animate({
					top: $(document).scrollTop()
					},{duration:500,queue:false}
					);
					});

					}


                if(json['error']['error_ncad']){

					$('#notification').css( "position", "absolute" );
					 $('#notification').css( "margin-left", "auto" );
					 $('#notification').css( "margin-right", "auto" );
					 $('#notification').css( "margin-bottom", "auto" );
					 $('#notification').css( "margin-top", "auto" );
					 $('#notification').css( "left", "0" );
					 $('#notification').css( "right", "0" );
					 $('#notification').css( "top", "0" );
					 $('#notification').css( "bottom", "0" );
					 $('#notification').css( "width", "725px" );
					 $('#notification').css( "max-width", "90%" );
					 $('#notification').css( "height", "42px" );

     				$('#notification').html('<div class="warning" style="display: none; position:relative; z-index:9999; border: 1px solid #E76453;' +
					'-webkit-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); -moz-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30);">' +  json['error']['error_ncad'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

    				$('#cart-total').html(json['total']);

    				//$('html, body').animate({ scrollTop: 0 }, 'slow');

					//$('.warning').fadeIn('slow');

					//$('.success').offset({ top: 10, left: 30});
					$('.warning').fadeIn('slow');
					$('.warning').animate({
					top: $(document).scrollTop()
					});
					var y_fixo = $('.warning').offset().top;
					$(window).scroll(function () {
					$('.warning').animate({
					top: $(document).scrollTop()
					},{duration:500,queue:false}
					);
					});

					}

                if(json['error']['errmaxitemcart']){

					$('#notification').css( "position", "absolute" );
					 $('#notification').css( "margin-left", "auto" );
					 $('#notification').css( "margin-right", "auto" );
					 $('#notification').css( "margin-bottom", "auto" );
					 $('#notification').css( "margin-top", "auto" );
					 $('#notification').css( "left", "0" );
					 $('#notification').css( "right", "0" );
					 $('#notification').css( "top", "0" );
					 $('#notification').css( "bottom", "0" );
					 $('#notification').css( "width", "725px" );
					 $('#notification').css( "max-width", "90%" );
					 $('#notification').css( "height", "42px" );

     				$('#notification').html('<div class="warning" style="display: none; position:relative; z-index:9999; border: 1px solid #E76453;' +
					'-webkit-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); -moz-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30);">' +  json['error']['errmaxitemcart'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

    				//$('#cart-total').html(json['total']);

    				//$('html, body').animate({ scrollTop: 0 }, 'slow');

					//$('.warning').fadeIn('slow');

					//$('.success').offset({ top: 10, left: 30});
					$('.warning').fadeIn('slow');
					$('.warning').animate({
					top: $(document).scrollTop()
					});
					var y_fixo = $('.warning').offset().top;
					$(window).scroll(function () {
					$('.warning').animate({
					top: $(document).scrollTop()
					},{duration:500,queue:false}
					);
					});
			}

            }

			if (json['redirect']) {
				location = json['redirect'];
			}

			if (json['success']) {

				//$('#notification').css( "position", "absolute", "margin-left", "auto", "margin-right", "auto", "margin-bottom", "auto", "margin-top", "auto", "left", "0", "right", "0","top", "0", "bottom", "0", "width", "725px", "max-width", "90%", "height", "42px");

				 $('#notification').css( "position", "absolute" );
				 $('#notification').css( "margin-left", "auto" );
				 $('#notification').css( "margin-right", "auto" );
				 $('#notification').css( "margin-bottom", "auto" );
				 $('#notification').css( "margin-top", "auto" );
				 $('#notification').css( "left", "0" );
				 $('#notification').css( "right", "0" );
				 $('#notification').css( "top", "0" );
				 $('#notification').css( "bottom", "0" );
				 $('#notification').css( "width", "725px" );
				 $('#notification').css( "max-width", "90%" );
				 $('#notification').css( "height", "42px" );

				$('#notification').html('<div class="success" style="display: none; position:relative; z-index:9999; border: 1px solid #E76453;' +
				'-webkit-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); -moz-box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); box-shadow: 6px 6px 14px 0px rgba(0,0,0,0.30); ">'
				+ json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				//$('.success').fadeIn('slow');

				//$('.success').offset({ top: 10, left: 30});
				$('.success').fadeIn('slow');
				$('.success').animate({
				top: $(document).scrollTop()
				});
				var y_fixo = $('.success').offset().top;
				$(window).scroll(function () {
					$('.success').animate({
						top: $(document).scrollTop()
					},{duration:500,queue:false});
				});



				$('#cart-total').html(json['total']);
				$('.cart-stick #cart-total').html(json['total']);

				//$('html, body').animate({ scrollTop: 0 }, 'slow');

            	var x = document.getElementsByClassName("product-block pro" + product_id);
            	var i;

            	for (i = 0; i < x.length; i++) {
            	   x[i].style.borderColor = '#00a550';
               	}


               	$('#product_carrinho' + product_id).val("1");// 1= está no carrinho
				if (G_AnalyticsHabilitado){
					analyticsAddProduto(json['infosProduto']);
				}
			}

			/*Feito para remover a mensagem ao clicar fora ca nofificação*/
			$('body').append('<div id="bloq-notification-overlay" style="height: 100%;width: 100%;position: fixed;z-index: 1000;top: 0;left: 0;display: block;" /></div>');
			$('#notification').slideDown( 300 ).delay( 5000 ).fadeOut( 400 , function(){ $('#bloq-notification-overlay').remove(); });
			/*Feito para remover a mensagem ao clicar fora ca nofificação*/

		}
	});
}

$('#bloq-notification-overlay').live('click',function(){
	$( '#notification').stop();
	$('#notification').fadeOut( 400 );
	$('#bloq-notification-overlay').remove();
});

function addToWishList(product_id) {
	$.ajax({
		url: 'index.php?route=account/wishlist/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.success').fadeIn('slow');

				$('#wishlist-total').html(json['total']);

				//$('html, body').animate({ scrollTop: 0 }, 'slow');
			}
		}
	});
}

function addToCompare(product_id) {
	$.ajax({
		url: 'index.php?route=product/compare/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.success').fadeIn('slow');

				$('#compare-total').html(json['total']);

				//$('html, body').animate({ scrollTop: 0 }, 'slow');
			}
		}
	});
}


function onAction(prodid, v1, ptag) {
	var elm = $('#htop' + ptag + '_' + prodid);

	if ((elm.prop("value") > 1) || (parseInt(v1, 10) == 1)){
	    elm.val( parseInt( elm.val(), 10 ) + parseInt(v1, 10) );
		}
};


function onActionList(prodid, v1, ptag) {
	var elm = $('#htopList' + ptag + '_' + prodid);

	if ((elm.prop("value") > 1) || (parseInt(v1, 10) == 1)){
	    elm.val( parseInt( elm.val(), 10 ) + parseInt(v1, 10) );
		}
};


// troca cor da borda caso produto esteja no carrinho...
function addCarrinho(product_id, ptag){
	var elm = $('#htop' + ptag + '_' + product_id);
	addToCart(product_id, parseInt(elm.prop("value")))

};

//troca cor da borda caso produto esteja no carrinho...
function addCarrinholist(product_id, ptag){

	var elm = $('#htopList' + ptag + '_' + product_id);
	addToCart(product_id, parseInt(elm.prop("value")))

};

$( window ).resize(function() {
  $('[class^=product-block]').css('height', '');
  $('[id^=desc_produto]').toggle(false);

});


function descprod(pprod){
	$('#desc_produto'+pprod).toggle();

    $('.product-block.pro' + pprod).css('height', '');

    var vhide = false;     // verifica se existe pelo menos uma div da mesma linha aberto com descricao do produto
    var vcontador = 0;     // contador para inserir na lista
    var lista = [];        // lista dos produtos que estao na mesma linha
    var vMaiorAltura = 0;  // captura maior div, para redimensionar todas igualmente
    $(".product-block").each(function( index, element ) {
        if($(element).offset().top == $(".product-block.pro" + pprod).offset().top){
            lista[vcontador] = '.product-block.pro' + $(element).children('#product_idhidden').val();

            if($('#desc_produto' + $(element).children('#product_idhidden').val()).css('display') == 'block'){
              vhide = true;
            }
        }
        vcontador ++;
    });

    for(i =0; i <= lista.length; i++){
      $(lista[i]).css('height', '');
    }

    for(i =0; i <= lista.length; i++){
      if ($(lista[i]).height() > vMaiorAltura){
        vMaiorAltura = $(lista[i]).height();
      }
    }

    for(i =0; i <= lista.length; i++){
            if(!vhide){
                $(lista[i]).css('height', $(lista[i]).css('min-height'));
                $(lista[i]).css('height', '');
            } else{
              $(lista[i]).css('height', vMaiorAltura);
            }
    }

};

(function($){
	$.fn.serializeObject = function () {
		"use strict";

		var result = {};
		var extend = function (i, element) {
			var node = result[element.name];

	// If node with same name exists already, need to convert it to an array as it
	// is a multi-value field (i.e., checkboxes)

			if ('undefined' !== typeof node && node !== null) {
				if ($.isArray(node)) {
					node.push(element.value);
				} else {
					result[element.name] = [node, element.value];
				}
			} else {
				result[element.name] = element.value;
			}
		};

		$.each(this.serializeArray(), extend);
		return result;
	};
})(jQuery);
