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 '';
		}
	} else {
		var query = String(document.location).split('/');
		var last = query.pop();

		if (last == 'carrinho-de-compras') return 'checkout/cart';
		if (last == 'finalizar-pedido') return 'checkout/checkout';
	}
}

$(document).ready(function() {

	// Highlight any found errors
	$('.text-danger').each(function() {
		var element = $(this).parent().parent();

		if (element.hasClass('form-group')) {
			element.addClass('has-error');
		}
	});

	// Currency
	$('#currency .currency-select').on('click', function(e) {
		e.preventDefault();

		$('#currency input[name=\'code\']').attr('value', $(this).attr('name'));

		$('#currency').submit();
	});

	// Language
	$('#language .language-select').on('click', function(e) {
		e.preventDefault();

		$('#language input[name=\'code\']').attr('value', $(this).attr('name'));

		$('#language').submit();
	});

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

		var value = $('#search-input').val();

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

		location = url;
	});

	$('#search-input').on('keydown', function(e) {
		if (e.keyCode == 13) {
			$('#search-button').trigger('click');
		}
	});

	// Menu
	$('#header-menu .dropdown-menu').each(function() {
		var menu = $('#header-menu-content').offset();
		var dropdown = $(this).parent().offset();

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

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

	// Product List
	$('#list-view').click(function() {
		$('#content').find('.product-layout').removeClass('product-grid').addClass('product-list col-xs-12');

		localStorage.setItem('display', 'list');
	});

	// Product Grid
	$('#grid-view').click(function() {
		var cols = $('#column-right, #column-left').length;
		var classes = 'product-grid ';

		// if (cols == 2) {
		// 	classes += 'col-lg-6 col-md-6 col-sm-12 col-xs-12';
		// } else if (cols == 1) {
		// 	classes += 'col-lg-4 col-md-4 col-sm-6 col-xs-12';
		// } else {
		// 	classes += 'col-lg-3 col-md-3 col-sm-6 col-xs-12';
		// }
		classes += 'col-xs-12';

		$('#content').find('.product-layout').removeClass('product-list').addClass(classes);

		 localStorage.setItem('display', 'grid');
	});

	if (localStorage.getItem('display') == 'list') {
		$('#list-view').trigger('click');
	} else {
		$('#grid-view').trigger('click');
	}

	// tooltips on hover
	$('[data-toggle=\'tooltip\']').tooltip({container: 'body'});

	// Makes tooltips work on ajax generated content
	$(document).ajaxStop(function() {
		$('[data-toggle=\'tooltip\']').tooltip({container: 'body'});
	});

	// ajuste do rodapé
	var $window = $(window);
	var $body = $('body');
	var $footer = $('footer');

	function adjustFooter() {
		var wHeight = $window.height();
		var bHeight = $body.outerHeight();
		var fHeight = $footer.outerHeight();

		if (wHeight > bHeight) {
			$body.addClass('adjust-footer');
			$body.css('padding-bottom', fHeight + 'px');
		} else {
			$body.removeClass('adjust-footer');
			$body.css('padding-bottom', '0px');
		}
	}

	var adjustFooterTimeout;

	$window.on('resize', function(){
		clearTimeout(adjustFooterTimeout);
		adjustFooterTimeout = setTimeout(function(){
			adjustFooter();
		}, 500);
	});

	$(document).ajaxStop(function() {
		clearTimeout(adjustFooterTimeout);
		adjustFooterTimeout = setTimeout(function(){
			adjustFooter();
		}, 200);
	});

	$('img').on('load', function(){
		clearTimeout(adjustFooterTimeout);
		adjustFooterTimeout = setTimeout(function(){
			adjustFooter();
		}, 500);
	});

	adjustFooter();
	setTimeout(adjustFooter, 5000);
	setTimeout(adjustFooter, 10000);
});

// Cart add remove functions
var cart = {
	'add': function(product_id, quantity) {
		$.ajax({
			url: 'index.php?route=checkout/cart/add',
			type: 'post',
			data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
			dataType: 'json',
			beforeSend: function() {
				$('#cart > button').button('loading');
			},
			complete: function() {
				$('#cart > button').button('reset');
			},
			success: function(json) {
				$('.alert, .text-danger').remove();

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

				if (json['success']) {
					$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>');

					// Need to set timeout otherwise it wont update the total
					setTimeout(function () {
						$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
					}, 100);

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

					$('#cart > ul').load('index.php?route=common/cart/info ul li');

					setTimeout(function(){
						// location = 'index.php?route=checkout/cart';
						location = $('base').attr('href') + 'carrinho-de-compras';
					}, 1000);
				}
			}
		});
	},
	'update': function(key, quantity) {
		$.ajax({
			url: 'index.php?route=checkout/cart/edit',
			type: 'post',
			data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
			dataType: 'json',
			beforeSend: function() {
				$('#cart > button').button('loading');
			},
			complete: function() {
				$('#cart > button').button('reset');
			},
			success: function(json) {
				// Need to set timeout otherwise it wont update the total
				setTimeout(function () {
					$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
				}, 100);

				if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
					// location = 'index.php?route=checkout/cart';
					location = $('base').attr('href') + 'carrinho-de-compras';
				} else {
					$('#cart > ul').load('index.php?route=common/cart/info ul li');
				}
			}
		});
	},
	'remove': function(key) {
		$.ajax({
			url: 'index.php?route=checkout/cart/remove',
			type: 'post',
			data: 'key=' + key,
			dataType: 'json',
			beforeSend: function() {
				$('#cart > button').button('loading');
			},
			complete: function() {
				$('#cart > button').button('reset');
			},
			success: function(json) {
				// Need to set timeout otherwise it wont update the total
				setTimeout(function () {
					$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
				}, 100);

				if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
					// location = 'index.php?route=checkout/cart';
					location = $('base').attr('href') + 'carrinho-de-compras';
				} else {
					$('#cart > ul').load('index.php?route=common/cart/info ul li');
				}
			}
		});
	}
}

var voucher = {
	'add': function() {

	},
	'remove': function(key) {
		$.ajax({
			url: 'index.php?route=checkout/cart/remove',
			type: 'post',
			data: 'key=' + key,
			dataType: 'json',
			beforeSend: function() {
				$('#cart > button').button('loading');
			},
			complete: function() {
				$('#cart > button').button('reset');
			},
			success: function(json) {
				// Need to set timeout otherwise it wont update the total
				setTimeout(function () {
					$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
				}, 100);

				if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
					// location = 'index.php?route=checkout/cart';
					location = $('base').attr('href') + 'carrinho-de-compras';
				} else {
					$('#cart > ul').load('index.php?route=common/cart/info ul li');
				}
			}
		});
	}
}

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

				if (json['success']) {
					$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>');
				}

				if (json['info']) {
					$('#content').parent().before('<div class="alert alert-info"><i class="fa fa-info-circle"></i> ' + json['info'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>');
				}

				$('#wishlist-total span').html(json['total']);
				$('#wishlist-total').attr('title', json['total']);

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

	}
}

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

				if (json['success']) {
					$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>');

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

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

	}
}

/* Agree to Terms */
$(document).delegate('.agree', 'click', function(e) {
	e.preventDefault();

	$('#modal-agree').remove();

	var element = this;

	$.ajax({
		url: $(element).attr('href'),
		type: 'get',
		dataType: 'html',
		success: function(data) {
			html  = '<div id="modal-agree" class="modal">';
			html += '  <div class="modal-dialog">';
			html += '    <div class="modal-content">';
			html += '      <div class="modal-header">';
			html += '        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
			html += '        <h4 class="modal-title">' + $(element).text() + '</h4>';
			html += '      </div>';
			html += '      <div class="modal-body">' + data + '</div>';
			html += '    </div';
			html += '  </div>';
			html += '</div>';

			$('body').append(html);

			$('#modal-agree').modal('show');
		}
	});
});

// Autocomplete */
(function($) {
	$.fn.autocomplete = function(option) {
		return this.each(function() {
			this.timer = null;
			this.items = new Array();

			$.extend(this, option);

			$(this).attr('autocomplete', 'off');

			// Focus
			$(this).on('focus', function() {
				this.request();
			});

			// Blur
			$(this).on('blur', function() {
				setTimeout(function(object) {
					object.hide();
				}, 200, this);
			});

			// Keydown
			$(this).on('keydown', function(event) {
				switch(event.keyCode) {
					case 27: // escape
						this.hide();
						break;
					default:
						this.request();
						break;
				}
			});

			// Click
			this.click = function(event) {
				event.preventDefault();

				value = $(event.target).parent().attr('data-value');

				if (value && this.items[value]) {
					this.select(this.items[value]);
				}
			}

			// Show
			this.show = function() {
				var pos = $(this).position();

				$(this).siblings('ul.dropdown-menu').css({
					top: pos.top + $(this).outerHeight(),
					left: pos.left
				});

				$(this).siblings('ul.dropdown-menu').show();
			}

			// Hide
			this.hide = function() {
				$(this).siblings('ul.dropdown-menu').hide();
			}

			// Request
			this.request = function() {
				clearTimeout(this.timer);

				this.timer = setTimeout(function(object) {
					object.source($(object).val(), $.proxy(object.response, object));
				}, 200, this);
			}

			// Response
			this.response = function(json) {
				html = '';

				if (json.length) {
					for (i = 0; i < json.length; i++) {
						this.items[json[i]['value']] = json[i];
					}

					for (i = 0; i < json.length; i++) {
						if (!json[i]['category']) {
							html += '<li data-value="' + json[i]['value'] + '"><a href="#">' + json[i]['label'] + '</a></li>';
						}
					}

					// Get all the ones with a categories
					var category = new Array();

					for (i = 0; i < json.length; i++) {
						if (json[i]['category']) {
							if (!category[json[i]['category']]) {
								category[json[i]['category']] = new Array();
								category[json[i]['category']]['name'] = json[i]['category'];
								category[json[i]['category']]['item'] = new Array();
							}

							category[json[i]['category']]['item'].push(json[i]);
						}
					}

					for (i in category) {
						html += '<li class="dropdown-header">' + category[i]['name'] + '</li>';

						for (j = 0; j < category[i]['item'].length; j++) {
							html += '<li data-value="' + category[i]['item'][j]['value'] + '"><a href="#">&nbsp;&nbsp;&nbsp;' + category[i]['item'][j]['label'] + '</a></li>';
						}
					}
				}

				if (html) {
					this.show();
				} else {
					this.hide();
				}

				$(this).siblings('ul.dropdown-menu').html(html);
			}

			$(this).after('<ul class="dropdown-menu"></ul>');
			$(this).siblings('ul.dropdown-menu').delegate('a', 'click', $.proxy(this.click, this));

		});
	}
})(window.jQuery);










function sortCustomFields($parent, element) {
	element = !element ? '.form-group' : element + '';

	$parent.find(element + '[data-sort]').detach().each(function() {
		var sort = $(this).attr('data-sort');
		var formGroups = $parent.find(element);

		if (sort >= 0 && sort < formGroups.length) {
			formGroups.eq(sort).before(this);
		}

		if (sort >= formGroups.length) {
			formGroups.filter(':last').after(this);
		}

		if (sort < 0) {
			formGroups.filter(':first').before(this);
		}
	});
}





$(document).on('focus.initDatetimepicker', '.date, .time, .datetime, .birth', function() {
	var $this = $(this);

	if ($this.hasClass('datetimepicker-on')) {
		return;
	}

	$this.addClass('datetimepicker-on');

	if ($this.hasClass('birth')) {
		$this.datetimepicker({
			allowInputToggle: true,
			showClear: true,
			showClose: true,
			locale: current_language_code,
			extraFormats: ['DDMMYY', 'DDMMYYYY', 'DD/MM/YY', 'DD/MM/YYYY', 'DD-MM-YY', 'DD-MM-YYYY', 'DD.MM.YY', 'DD.MM.YYYY', 'DD MM YY', 'DD MM YYYY'],
			viewMode: 'years',
			useCurrent: false,
			maxDate: birth_max_date,
			viewDate: birth_max_date
		});
		return;
	}

	$this.datetimepicker({
		allowInputToggle: true,
		showClear: true,
		showClose: true,
		locale: current_language_code,
		extraFormats: ['DDMMYY', 'DDMMYYYY', 'DD/MM/YY', 'DD/MM/YYYY', 'DD-MM-YY', 'DD-MM-YYYY', 'DD.MM.YY', 'DD.MM.YYYY', 'DD MM YY', 'DD MM YYYY'],
		useCurrent: false
	});
});





function validaCPF(b){if(!RegExp("^[0-9]{11}$").test(b)&&!RegExp("^[0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}$").test(b))return!1;for(b=b.replace(/[^0-9]/g,""),a=0;a<10;a++)if(RegExp("^"+a+"{11}$").test(b))return!1;var c=b.split("",9);for(d=9;d<=10;d++){var e=d+1,f=0;for(a=0;a<d;a++)f+=c[a]*e--;var g=f%11;c[d]=2>g?0:11-g}return b.substr(9,2)!=""+c[9]+c[10]?!1:!0}
function validaCNPJ(b){if(!RegExp("^[0-9]{14,15}$").test(b)&&!RegExp("^[0-9]{2,3}.[0-9]{3}.[0-9]{3}/[0-9]{4}-[0-9]{2}$").test(b))return!1;if(b=b.replace(/[^0-9]/g,""),15==b.length){if(0!=b.substr(0,1))return!1;b=b.substr(1,14)}for(a=0;a<10;a++)if(RegExp("^"+a+"{14}$").test(b))return!1;var c=b.split("",12);for(d=12;d<=13;d++){var e=d-7,f=0;for(a=0;a<d;a++)f+=c[a]*e--,2>e&&(e=9);var g=f%11;c[d]=2>g?0:11-g}return b.substr(12,2)!=""+c[12]+c[13]?!1:!0}





function inputPhoneBrasilChange(e){
	if (e.type == 'keyup' && $.inArray(parseInt(e.keyCode), [9, 16, 17, 18, 35, 36, 37, 38, 39, 40]) > -1){ return true; }
	var length = this.value.replace(/[^0-9]/g, '').length;
	if (e.type == 'keyup' && length < 10) { return true; }
	$(this).mask( length > 10 ? '(99) 99999-999?9' : '(99) 9999-9999?9' );
}





var returnedCeps = {};

function inputPostcodeBrasilChange(e){
	var cep = this.value.replace(/[^0-9]/g, '');
	if (cep.length != 8) { return true; }

	var $this = $(this);

	var lastCep = $this.data('last-cep');
	if (lastCep == cep) { return true; }
	$this.data('last-cep', cep);

	// verifica se esta no cache
	if(returnedCeps[cep] && returnedCeps[cep] != ''){
		afterChangePostcodeBrasil(returnedCeps[cep], $this);
		return true;
	}

	var xhrCep = $this.data('xhr-cep');

	if(xhrCep && xhrCep.readyState != 4){
		xhrCep.abort();
	}

	xhrCep = $.ajax({
		url: 'index.php?route=account/register/consulta_cep&c=' + cep,
		dataType: 'json',
		beforeSend: function() {
			$('.fa-spin').remove();
			$this.parent().prev().append(' <i class="fa fa-circle-o-notch fa-spin country-loading"></i>');
		},
		complete: function() {
			setTimeout(function(){ $('.country-loading').remove(); }, 500);
		},
		success: function(json) {
			afterChangePostcodeBrasil(json, $this);
			returnedCeps[cep] = json;
		},
		error: function(xhr, ajaxOptions, thrownError) {
			if (thrownError != 'abort') {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		}
	});

	$this.data('xhr-cep', xhrCep);
}

function afterChangePostcodeBrasil(json, $this) {
	var $parent = $this.parents('.form-group');
	$parent.find('.text-danger').remove();
	$parent.removeClass('has-error');

	if (json['erro'] == '0') {
		var $form = $this.parents('.form-register');

		$form.find('.input-address-1').val(unescape(json['endereco']));
		$form.find('.input-address-2').val(unescape(json['bairro']));
		$form.find('.input-city').val(unescape(json['cidade']));

		var $inputZone = $form.find('.input-zone');
		$inputZone.find('option').prop('selected', false);
		$inputZone.find('option[data-code=' + unescape(json['uf']) + ']').prop('selected', true);

		$form.find('.input-numero').trigger('focus');
	} else {
		$this.after('<div class="text-danger">Não foi possível encontrar o endereço para o CEP informado! Por favor, confira se o CEP foi digitado corretamente ou então informe manualmente seu endereço.</div>');
		$parent.addClass('has-error');
	}
}





function initFormRegister() {

	$(document).on('keyup.maskPostcode change.maskPostcode' ,'.mask-postcode-on', inputPostcodeBrasilChange);
	$(document).on('keyup.maskPhone blur.maskPhone' ,'.mask-phone-on', inputPhoneBrasilChange);

	$(document).on('change.inputCountry', '.input-country', function() {
		var val = this.options[this.selectedIndex].value;
		var txt = $.trim(this.options[this.selectedIndex].text).toLowerCase();

		var $this = $(this);
		var $form = $this.parents('.form-register');

		var $fieldsetBrasil    = $form.find('.fieldset-brasil');
		var $inputMaskPostcode = $form.find('.mask-postcode');
		var $inputMaskPhone    = $form.find('.mask-phone');

		if (txt == 'brasil' || txt == 'brazil') {
			$fieldsetBrasil.show();
			$inputMaskPostcode.not('.mask-postcode-on').addClass('mask-postcode-on').mask('99999-999');
			$inputMaskPhone.not('.mask-phone-on').addClass('mask-phone-on').mask('(99) 9999-9999?9').trigger('keyup.maskPhone');
		} else {
			$fieldsetBrasil.hide();
			$inputMaskPostcode.removeClass('mask-postcode-on').unmask();
			$inputMaskPhone.removeClass('mask-phone-on').unmask();
		}

		$form.find('.hidden-country').val(val);
	});

	$(document).on('change.inputTipo', '.input-tipo', function() {
		var $this = $(this);
		var $parent = $this.parents('.form-group');
		var val = $parent.find(':checked').val();

		var $form = $this.parents('.form-register');
		var $fieldsetPF = $form.find('.fieldset-pessoa-fisica');
		var $fieldsetPJ = $form.find('.fieldset-pessoa-juridica');

		if (val == 'f') {
			$fieldsetPJ.hide();
			$fieldsetPF.show();
			return true;
		}
		if (val == 'j') {
			$fieldsetPF.hide();
			$fieldsetPJ.show();
			return true;
		}

		$fieldsetPJ.hide();
		$fieldsetPF.hide();
	});

	$(document).on('focus', '.mask-cpf', function() {
		$(this).mask('999.999.999-99').removeClass('mask-cpf').addClass('mask-cpf-on');
	});
	$(document).on('focus', '.mask-cnpj', function() {
		$(this).mask('99.999.999/9999-99').removeClass('mask-cnpj').addClass('mask-cnpj-on');
	});

	$(document).on('change.maskCPFCNPJ' ,'.mask-cpf-on, .mask-cnpj-on', function(){
		var $this = $(this);
		var $parent = $this.parents('.form-group');

		$parent.find('.text-danger').remove();
		$parent.removeClass('has-error');

		var val = $.trim(this.value);

		if (val == '') {
			return;
		}

		if ($this.hasClass('mask-cpf-on')) {
			if (!validaCPF(val)) {
				$this.after('<div class="text-danger">O CPF informado não é válido!</div>');
				$parent.addClass('has-error');
			}
		} else {
			if (!validaCNPJ(val)) {
				$this.after('<div class="text-danger">O CNPJ informado não é válido!</div>');
				$parent.addClass('has-error');
			}
		}
	});

	triggerFormRegister();
}

function triggerFormRegister() {
	$('.input-country').trigger('change.inputCountry');
	$('.input-tipo').trigger('change.inputTipo');
}









