/*
Some of these override earlier varien/product.js methods, therefore
varien/product.js must have been included prior to this file.
*/


//Helper function which works out which productId all passed attributes match.
//Assumes array(productIds), array(array(productIds))
Product.Config.prototype.getProductByAttributes = function(productIds, attributes){
    for (var i=0;i<productIds.length;i++) {
        var foundMatchingProduct = true;
        for (var a=0;a<attributes.length;a++) {
            if (attributes[a].indexOf(productIds[i]) == -1) {
                foundMatchingProduct = false;
                break;
            }
        }
        if (foundMatchingProduct) {
            return productIds[i];
        }
    }
    return false;
}

//Determines which simple product the currently selected configurable attributes
//map to
Product.Config.prototype.getMatchingSimpleProduct = function(){

    var childProducts =  this.config.childProducts;
    var childProductIds = [];
    for (var x in childProducts) {
        childProductIds.push(x);
    }

    var attributeProducts = [];
    for(var s=this.settings.length-1;s>=0;s--){
        var selected = this.settings[s].options[this.settings[s].selectedIndex];
        if (!selected.config){
            return false;
        }
        attributeProducts.push(selected.config.products);
    }
    
    
    return this.getProductByAttributes(childProductIds, attributeProducts);
}


Product.Config.prototype.getLowestPossiblePrice = function() {
    var childProducts =  this.config.childProducts;
    var minPrice = Infinity;
    var minPriceString = "";
    //Be careful here to return the exact input price value,
    //not some (possibly badly) converted version
    for (var x in childProducts) {
        var thisPrice = Number(childProducts[x]);
        if (thisPrice < minPrice) {
            minPrice = thisPrice;
            minPriceString = childProducts[x];
        }
    }
    return minPriceString;
}


Product.Config.prototype.reloadPriceLabels = function(productPriceIsKnown) {
    var priceLabel = '';
    if (!productPriceIsKnown) {
        priceLabel = this.config.priceFromLabel;
    	
		//a-t-on trouve un prix barré pour ce produit ?
		basePrice =  this.config.basePrice;
		oldPrice  =  this.config.oldPrice;
		

		if(basePrice != oldPrice)
			{
			basePrice = this.config.basePriceHTML;
			oldPrice = this.config.oldPriceHTML;
			
			
			$$('.info-box span.configurable-price-from-label').each(function(label) {
				label.innerHTML = priceLabel;
			});
	
			$$('.info-box .price').each(function(element) {
				element.style.display = 'inline';
				element.innerHTML = basePrice;
			});
			
			
				len = (oldPrice.length)*8+ 5;
				img = '<img style="position:absolute;top:7px;left:0;width:'+len+'px; height:8px;" src="/skin/frontend/matelpro/theme_matelpro/images/prix_barre.png"  alt="Prix Barré" />' ;
		
		
			$$('.info-box .old-price').each(function(element) {
                element.innerHTML = '<span><span class="oldprice conf-old-price" style="position:relative;margin-right: 6px; font-size: 18px;">' +img+ oldPrice + '</span></span>';
				element.style.display = 'inline';
			});
			
			}
		else
			{
			$$('.info-box .old-price').each(function(element) {
				element.style.display = 'none';
			});
			}
    	
    	 $$('.info-box span.configurable-price-from-label').each(function(label) {
    	        label.style.display = 'inline';
    	 });
    	 
    }
    else
    	{
    	 $$('.info-box span.configurable-price-from-label').each(function(label) {
    		 label.style.display = 'none';
    	    });
    	}
    

    //Replace the content of any spans with the css class
    //"configurable-price-from-label"
    
    $$('.info-box span.configurable-price-from-label').each(function(label) {
        label.innerHTML = priceLabel;
    });
    
    
    
    diff_pb_pm = this.config.allPrices[this.config.minId]['diff_pb_pm'] ;
	prix_public = this.config.allPrices[this.config.minId]['prix_public'] ;
	if($('pb') != null)
		$('pb').update(prix_public);
		
	if($('dpbpm') != null)
		$('dpbpm').update(diff_pb_pm);
    
    
    
    if(!productPriceIsKnown && this.config.tauxdemarque != '')
		{/*
		taux = this.config.tauxdemarque;
		$$('.info-box .picto-promo').each(function(element) {
			element.style.display = "inline";
			element.update('-' + taux + '%');
			});
		*/
		}
	else
		{
		$$('.info-box .picto-promo').each(function(element) {
			element.style.display ="none";
			});
		}
    $('wee-container').update('');
    
    
    if(this.config.delaiLivraisonConf != null)
		{
		delai = this.config.delaiLivraisonConf;
		$$('.info-box .delivery-delay').each(function(element) {
        element.update(delai);
        });
		}
    
    
}


Product.Config.prototype.updateFormProductId = function(productId){
    if (!productId) {
        return false;
    }

    diff_pb_pm = this.config.allPrices[productId]['diff_pb_pm'] ;
	prix_public = this.config.allPrices[productId]['prix_public'] ;

	
	$('wee-container').update(this.config.allPrices[productId]['weee']);
	
	
	if(this.config.allPrices[productId]['delai'] != null && this.config.allPrices[productId]['delai'] != '')
		{
		delai = this.config.allPrices[productId]['delai'];
		$$('.info-box .delivery-delay').each(function(element) {
			element.update(delai);
        	});
		}
	else
	{
		if(this.config.delaiLivraisonConf != null && this.config.delaiLivraisonConf != '')
		{
		delai = this.config.delaiLivraisonConf;
		$$('.info-box .delivery-delay').each(function(element) {
        element.update(delai);
        });
		}
		
	}
	

	if(this.config.allPrices[productId]['reduction'] != 0 && this.config.allPrices[productId]['reduction'] != '' && this.config.allPrices[productId]['reduction'] != null)
		{
		
		reduc = this.config.allPrices[productId]['reduction']
		/*
		$$('.info-box .picto-promo').each(function(element) {
			element.style.display = "inline";
	        element.update('-'+reduc+'%');
	        });
			*/
		}
	else
		{
		$$('.info-box .picto-promo').each(function(element) {
	        element.style.display ="none";
	        });
		}
	
	
	
    if(this.config.allPrices[productId]['special_price'] != null)
    	{
    	oldprice = this.config.allPrices[productId]['old_price'] ;	
		
		len = (oldprice.length-1)*10;
		img = '<img style="position:absolute;top:7px;left:0;width:'+len+'px; height:8px;" src="/skin/frontend/matelpro/theme_matelpro/images/prix_barre.png"  alt="Prix Barré" />' ;
    	$$('.info-box .conf-old-price').each(function(element) {		
                element.innerHTML = img+oldprice;
           });
    	
    	$$('.info-box .old-price').each(function(element) {
            element.style.display = 'inline';
       });
    	}
    else
    	{
    	$$('.info-box .old-price').each(function(element) {
            element.style.display = 'none';
    	});
    	
    	}
    
	if($('pb') != null && prix_public != null)
		{
		$('pb').update(prix_public);
		$('pb').up().show();
		}
	else
		{
		if($('pb') != null)
			$('pb').up().hide();
		}
		
	if($('dpbpm') != null && diff_pb_pm != null && diff_pb_pm != 0)
		{
		$('dpbpm').update(diff_pb_pm);
		$('dpbpm').up().show();
		}
    else
		{
		if($('dpbpm') != null)
			$('dpbpm').up().hide();
		}
    
   
    if(this.config.images[productId] != '')
    	{
    	if($('default-product-img-box-fade-box').style.opacity == '0' || $('default-product-img-box-fade-box').style.display == 'none')
    		{
    		$('image').src = this.config.images[productId];
    		Effect.Fade($('tmp-product-img-box-fade-box'), { duration:1, from:1.0, to:0.0 });
    		Effect.Appear($('default-product-img-box-fade-box'), { duration:1, from:0.0, to:1.0  });
    		}
    	else
    		{
    		$('tmp-image').src = this.config.images[productId];
    		Effect.Appear($('tmp-product-img-box-fade-box'), { duration:1, from:0.0, to:1.0 });
    		Effect.Fade($('default-product-img-box-fade-box'), { duration:1, from:1.0, to:0.0  });
    		}
    	}
    else
    	{
    	if($('default-product-img-box-fade-box').style.opacity == '0' || $('default-product-img-box-fade-box').style.display == 'none')
    		{
    		if($('tmp-image').src !=  this.config.images['main'])
    			{
    			$('image').src = this.config.images['main'];
        		Effect.Fade($('tmp-product-img-box-fade-box'), { duration:1, from:1.0, to:0.0 });
        		Effect.Appear($('default-product-img-box-fade-box'), { duration:1, from:0.0, to:1.0  });
    			}
    		}
    	else
    		{
    		if($('image').src !=  this.config.images['main'])
				{
    			$('tmp-image').src = this.config.images['main'];
    			Effect.Fade($('default-product-img-box-fade-box'), { duration:1, from:1.0, to:0.0 });
    			Effect.Appear($('tmp-product-img-box-fade-box'), { duration:1, from:0.0, to:1.0  });
				}
    		}    		
    	}
    
    var currentAction = $('product_addtocart_form').action;
    newcurrentAction = currentAction.sub(/product\/\d+\//, 'product/' + productId + '/');

    last = currentAction.lastIndexOf('/product/');
    oldpid = currentAction.substr(last +9, currentAction.length - last-10);
    
    
    $('product_addtocart_form').action = newcurrentAction;
    $('product_addtocart_form').product.value = productId;
    return true;
}


Product.Config.prototype.addParentProductIdToCartForm = function(parentProductId) {
    if (typeof $('product_addtocart_form').cpid != 'undefined') {
        return; //don't create it if we have one..
    }
    var el = document.createElement("input");
    el.type = "hidden";
    el.name = "cpid";
    el.value = parentProductId.toString();
    $('product_addtocart_form').appendChild(el);
}


Product.Config.prototype.reloadPrice = function() {
    var childProductId = this.getMatchingSimpleProduct();
    if (childProductId){
        optionsPrice.productPrice = this.config.childProducts[childProductId];
        optionsPrice.reload();
        this.reloadPriceLabels(true);
        this.updateFormProductId(childProductId);
        this.addParentProductIdToCartForm(this.config.productId);
    } else {
        optionsPrice.productPrice = this.getLowestPossiblePrice();
        optionsPrice.reload();
        this.reloadPriceLabels(false);
    }
}






function gup2(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

Product.Config.prototype.selectDeclinaison = function(){
	pid = gup2('d');
	
	var selected = this.config.pid_to_attributes[pid];
	for(att in selected)
		{
		value = selected[att];
		if($('attribute'+att))
			{
			$$('select#attribute'+att +' option').each(function(o){
				if(o.value==value)
					{
					o.selected = true;
					}
				else
					{
					o.selected = false;
					}
				});
			this.configureElement($('attribute'+att));
			}
		}
	this.reloadPrice();
}

/****************** ConfigurableToSimple Module - End *************************/