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

function updateSelectedVariation(parent, variation, id) {
    	
    var flagReloadJqzoom = false; /* MAICON041020111006 */
    
	if(parent == undefined) {
		parent = $('body');
	}
	else {
		parent = $(parent);
	}

	if(typeof(baseProduct.price) == 'undefined') {
		if($('.AddCartButton', parent).css('display') == "none") {
			var cartVisible = false;
		}
		else {
			var cartVisible = true;
		}
		baseProduct = {
			price: $('.VariationProductPrice', parent).html(),
			sku: $('.VariationProductSKU', parent).html(),
			weight: $('.VariationProductWeight', parent).html(),
			image: $('.JqzoomSetHrefImage', parent).attr('href'), /* MAICON260920111016 */
			thumb: $('.ThumbImageTag', parent).attr('src'), /* MAICON260920111016 */
			thumbLink: $('.ProductThumb .ViewLarger', parent).html(),
			cartButton: cartVisible
		};
		atualizaTabela();
	}

	// Show the defaults again
	if(typeof(variation) == 'undefined') {
		$('.VariationProductPrice', parent).html(baseProduct.price);
		$('.VariationProductSKU', parent).html(baseProduct.sku);
		$('.VariationProductWeight', parent).html(baseProduct.weight);
		$('.CartVariationId', parent).val('');
		$('.JqzoomSetHrefImage', parent).attr('href', baseProduct.image); /* MAICON260920111016 */
		$('.ThumbImageTag', parent).attr('src', baseProduct.thumb); /* MAICON260920111016 */
		$('.ProductThumb .ViewLarger', parent).html(baseProduct.thumbLink);
		$(parent).attr('currentVariation', '');
		$(parent).attr('currentVariationImage', '')
		$('.VariationOutOfStockMessage', parent).remove();
		if(baseProduct.sku == '') {
			$('.ProductSKU', parent).hide();
		}
		if(baseProduct.cartButton) {
			$('.AddCartButton', parent).show();
			if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
				$('.QuantityInput', parent).show();
			}
		}

		// AMERICO - formas de pagamento
		$('.Formas_Pgto_Bloco').show();
		$('.Formas_Pgto_Bloco').html();
		
		atualizaTabela();
		
		$('.InventoryLevel', parent).hide();
	}
	// Othersie, showing a specific variation
	else {
                
		$('.VariationProductPrice', parent).html(variation.price);
		if(variation.sku != '') {
			$('.VariationProductSKU', parent).html(variation.sku);
			$('.ProductSKU', parent).show();
		}
		else {
			$('.VariationProductSKU', parent).html(baseProduct.sku);
			if(baseProduct.sku) {
				$('.ProductSKU', parent).show();
			}
			else {
				$('.ProductSKU', parent).hide();
			}
		}
		$('.VariationProductWeight', parent).html(variation.weight);
		$('.CartVariationId', parent).val(id);
		if(variation.instock == true) {
			$('.AddCartButton', parent).show();
			if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
				$('.QuantityInput', parent).show();
			}
			$('.VariationOutOfStockMessage', parent).remove();
		}
		else {
			$('.AddCartButton, .QuantityInput', parent).hide();
			$('.VariationOutOfStockMessage', parent).remove();
			$('.AddCartButton', parent).before('<p class="VariationOutOfStockMessage">'+lang.VariationSoldOutMessage+'</p>');
		}
		if(variation.thumb != '') {
			$('.JqzoomSetHrefImage', parent).attr('href', variation.image); /* MAICON260920111016 */
			$('.ThumbImageTag', parent).attr('src', variation.thumb); /* MAICON260920111016 */
			$('.ProductThumb .ViewLarger', parent).html('Veja imagem ampliada');
			$(parent).attr('currentVariation', id);
			$(parent).attr('currentVariationImage', variation.image);
                        flagReloadJqzoom = true; /* MAICON041020111006 */
		}
		else {
			$('.JqzoomSetHrefImage', parent).attr('href', baseProduct.image); /* MAICON260920111016 */
			$('.ThumbImageTag', parent).attr('src', baseProduct.thumb); /* MAICON260920111016 */
			$('.ProductThumb .ViewLarger', parent).html(baseProduct.thumbLink);
			$(parent).attr('currentVariation', '');
			$(parent).attr('currentVariationImage', '');
                        if($.trim(baseProduct.thumb)!='')
                            flagReloadJqzoom = false; /* MAICON041020111006 */
		}
		if(variation.stock) {
			$('.InventoryLevel', parent).show();
			$('.VariationProductInventory', parent).html(variation.stock);
		}
		else {
			$('.InventoryLevel', parent).hide();
		}
		
		// AMERICO - variacoes de produto
		$('.Formas_Pgto_Bloco').show(); //ProductFormasPagamento formaspgto
		$('.Formas_Pgto_Bloco').html(variation.formaspgto);
		$('.Comprar_Valores_Valor').show();
		$('.Comprar_Valores_Valor').html('De: ' + variation.price);
		$('.Comprar_Valores_Desconto').show(); 
		$('.Comprar_Valores_Desconto').html($('span[title=valoravista]').html() + '<div class="avista">a vista (* '+ $('span[title=valordescontoporcentagem]').html() +') </div>');

		atualizaTabela();
                
                if($.jqzoom && flagReloadJqzoom!=false) /* MAICON041020111006 */
                    $.jqzoom.reload('.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).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);
				if(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');
	}
}

/* MAICON 041020111658 */
function checkCombinationCurrentVariation(parent)
{
        if(parent == undefined)
            parent = $('body');
        else 
            parent = $(parent);
        
        if($('.ProductOptionList', parent).length > 0) {                                   
            var ourCombinationList = new Array();
            $('.ProductOptionList .lstOptionsVariations input[type=radio]:checked', parent).each(function(){
                ourCombinationList[ourCombinationList.length] = $(this).val();
            });
            
            if(ourCombinationList.length > 0){               
                var ourCombination = ourCombinationList.join(',');
			
                for(x in VariationList) {
                    variation = VariationList[x];
                    if(variation.combination == ourCombination) {
                        $('.AddCartButton input[type=image]').show();
                        updateSelectedVariation(parent, variation, x);
                        return true;
                    }
                }              
            }
        }           
        return false; 
}

function setThumbCor(value){
        if($.trim(value)!='' && value > 0){
            for(x in VariationList) {
                variation = VariationList[x];
                var listOfValues = variation.combination.split(",");
                flagOk = false;
                for(y in listOfValues) {
                    if(value == listOfValues[y]){
                       flagOk = true;
                       break;
                    }
                }
                if(flagOk == true){                    
                    updateSelectedVariation('body', variation, x);
                    return true;
                }
            }	
        }
        return false;
}

function setOptionVariation(variationIndex, variationValue, cor)
{    		
        if(variationIndex > 0 && $.trim(variationValue)!=''){
            var inputSet = $('#variation_'+variationIndex+'_'+variationValue);            
            $(inputSet).attr("checked", "checked");
        }
        
        if(checkCombinationCurrentVariation('body')==false){        	
            var value = variationValue;            
            if(cor==true){
                setThumbCor(value)
            }   
        }        
        return void(0);
}
/* MAICON 280920111622 */

$(document).ready(function() {
        if(typeof VariationList == 'undefined') {
                return;
        }
        //initializeVariations('body', VariationList);
        
        /* MAICON 041020111709 */        
        $('ul.lstOptionsVariations input[type=radio]').click(function(){
            var numberVariation = $(this).attr('name');
            numberVariation = numberVariation.match(/\d+/);
            var valVariation = $(this).val();

            if(numberVariation > 0 && valVariation!='')
                setOptionVariation(numberVariation, valVariation);
        });
        $('ul.VariationListCores li').each(function(){
            if($(this).find('.variationColorOption').length > 0){
                $(this).find('.variationColorOption').show();
                $(this).find('.variationLinkOption').hide();
            }
        });
        $('ul.VariationListCor li').each(function(){
            if($(this).find('.variationColorOption').length > 0){
                $(this).find('.variationColorOption').show();
                $(this).find('.variationLinkOption').hide();
            }
        });
        
        $('.AddCartButton input[type=image]').hide();
    	   
        
            $("ul.lstOptionsVariations li input[type=radio]").click(function(){
            var value = $(this).val();         
            var li = $(this).parents('li:first');

            if(li.find('a.variationColorOption').length==1 && checkCombinationCurrentVariation('body')==false && value > 0){
                setThumbCor(value)
            }
            
        });        
        /* MAICON 041020111709 */
});


function atualizaTabela(){           
        /*$lista = "<ul>"	

        jQuery.each($('.Right #ProductFormasPagamento table tr td'), function()
        {
                alert(this.innerHTML);
                $lista = $lista + "<li>"+this.innerHTML+"</li>";
        }) 
        $lista = $lista + "</ul>";

        $('.Right .parcelas_pagamento').html($lista);*/
}
