/* Product Variations */
var baseProduct = {};

function updateSelectedVariation(parent, variation, id) {
	if(parent == undefined) {
		parent = $('body');
	}
	else {
		parent = $(parent);
	}
	if(typeof(baseProduct.price) == 'undefined') {
		baseProduct = {
			price: $.trim($('#produto_preco', parent).html()),
			image: $.trim($('#pop_image_big', parent).html())
		};
	}
	// Mostra variação padrao
	if(typeof(variation) == 'undefined') { 
		$('#produto_preco', parent).html(baseProduct.price);
		$('#pop_image_big').html(baseProduct.image);
		$('#product_variation', parent).val('');
	} else { 	// Mostra a variação selecionada
		$('#product_variation', parent).val(id);
		$('#produto_preco', parent).html(variation.price);
		if(variation.image != '') {
			$('#pop_image_big', parent).html(variation.image);
		} else 
			$('#pop_image_big', parent).html(baseProduct.image);
		if(variation.instock == true) {
			$('#BotaoComprar', parent).show();
			$('#msg_sem_estoque', parent).hide();
		} else {
			$('#BotaoComprar', parent).hide();
			$('#msg_sem_estoque', parent).show();
		}
		$('#produto_cod_ref', parent).html(variation.cod_ref);
	}
	if (type_zoom==1)
	  $("a[rel^='info_produto']").colorbox();	
	else	
		$("a[rel^='additional_images']").jqzoom();	
}

function initializeVariations(parent, VariationList){
	if(parent == undefined) {
		parent = $('body');
	}
	else {
		parent = $(parent);
	}

	// Select boxes are used if there is more than one variation type
	if($('#ProductOptionList select', parent).length > 0) {
		$('#ProductOptionList select', parent).each(function(index) {
			$(this).change(function() {  
				if($(this).val()) {
					var next = $('#ProductOptionList select', parent).get(index+1);
					if(next) {
						$('#ProductOptionList select', parent).get(index+1).resetNext();
						$('#ProductOptionList select', parent).get(index+1).fill();
						$('#ProductOptionList select', parent).get(index+1).disabled = false;
					}
				} else {
					this.resetNext();
				}

				// Do we have a full match?
				ourCombination = this.getFullCombination();
				for(x in VariationList) {
					variation = VariationList[x];
					if(variation.combination == ourCombination) {
						updateSelectedVariation(parent, variation, x);
						return;
					}
				}
				// No match or incomplete selection
				updateSelectedVariation(parent);
			});

			this.getFullCombination = function() {
				var selected = new Array();
				$('#ProductOptionList select', parent).each(function() {
					selected[selected.length] = $(this).val();
				});
				return selected.join(',');
			}


			this.getCombination = function() {
				var selected = new Array();
				var thisSelect = this;
				$('#ProductOptionList select', parent).each(function() {
					if(thisSelect == this) {
						return false;
					}
					selected[selected.length] = $(this).val();
				});
				// Add the current item
				selected[selected.length] = $(this).val();
				return selected.join(',');
			}

			this.resetNext = function() {
				$(this,parent).nextAll().each(function() {
					this.selectedIndex = 0;
					this.disabled = true;
				});
			};

			this.fill = function(selectedVal) {
				// Remove everything but the first option
				$(this).find('option:gt(0)').remove();

				var show = true;
				var previousSelection;

				// Get the values of the previous selects
				var previous = $('#ProductOptionList select', parent).get(index-1);
//				alert(index);
				if(index>0 && previous) {
					previousSelection = previous.getCombination();
				}
				for(var i = 1; i < this.variationOptions.length; i++) {
					for(x in VariationList) {
						variation = VariationList[x];
						if(previousSelection) {
							var show = false;
							if((variation.combination+',').indexOf(previousSelection+','+this.variationOptions[i].value+',') == 0) {
								var show = true;
								break;
							}
							else {
							}
						}
					}
					if(show) {
						this.options[this.options.length] = new Option(this.variationOptions[i].text, this.variationOptions[i].value);
					}
				}
				if(selectedVal != undefined) {
					$(this).val(selectedVal);
				}
			};

			// Steal the options and store them away for later
			variationOptions = new Array();
			$(this).find('option').each(function() {
				if(typeof(this.text) == undefined) {
					this.text = this.innerHTML;
				}
				variationOptions[variationOptions.length] = {value: this.value, text: this.text };
			});
			selectedVal = $(this).val();
			this.variationOptions = variationOptions;
			if(index == 0) {
				this.fill(selectedVal);
			}
			else if(!selectedVal) {
				this.disabled = true;
			}
		});
	}
	// Otherwise, radio buttons which are very easy to deal with
	else {
		$('#ProductOptionList input[type=radio]', parent).click(function() {
			for(x in VariationList) {
				variation = VariationList[x];
				if(variation.combination == $(this).val()) {
					updateSelectedVariation(parent, variation, x);
					return;
				}
			}
			// No match or incomplete selection
			updateSelectedVariation(parent);
		});
		$('#ProductOptionList input[type=radio]:checked', parent).trigger('click');
	}
}

function CheckProductForm(form,required){
	if(required && !$(form).find('#product_variation').val()) {
		alert("É necessário selecionar a variação do produto desejado!");
		var select = $(form).find('select').get(0);
		if(select) { select.focus(); }
		var radio = $(form).find('input[type=radio]').get(0);
		if(radio) {	radio.focus(); }
		return false;
	} else if(required && !VariationList[$(form).find('#product_variation').val()].instock){
		alert("Este produto está sem estoque disponível!");
		return false;
	}
	return checkRequiredFields();
}

function calcularFrete(id_produto){
	abreDialog('Cálculo de Frete','popup_calcular_frete.php?frame=true&id_produto='+id_produto+'&variacao='+$('#product_variation').val(),800);
}
function formaPagto(id_produto){ 
	abreDialog('Formas de pagamento disponíveis:','popup_formas_pagamento.php?id_produto='+id_produto+'&variacao='+$('#product_variation').val(),400);
}

function addProdutoLista(check_options,id_lista,id_produto){
	if (CheckProductForm(document.forms["cart_quantity"],check_options)){
		document.forms.cart_quantity.action = "minhaconta_listas.php?id_lista="+id_lista+"&id_produto="+id_produto+"&action=add_product_list";
		document.forms.cart_quantity.submit();
	}
	return false;
}
