
/*
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
Product.Config.prototype.getMatchingSimpleProduct = function(){

    var childProducts =  this.config.childProducts;
    var childProductIds = [];
    for (var productId in childProducts) {
        childProductIds.push(productId);
    }
    
    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.updateFormProductId = function(productId){
    if (!productId) {
        return false;
    }
    var currentAction = $('product_addtocart_form').action;
    newcurrentAction = currentAction.sub(/product\/\d+\//, 'product/' + productId + '/');
    jQuery("#product_addtocart_form").attr('action', newcurrentAction );
    jQuery("#product_addtocart_form input[name='product']").attr('value', productId );
};

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.showTierPricesBlock = function(productId) {
    config = this.config;
    $$('ul.product-pricing').each(function(label) {
        label.remove();
    });
    
    $$('div.bundle-info').each(function(label) {
    	label.remove();
    });

    if (productId && config.childProductTierPriceHtml[productId]) {
        $$('div.product-options-bottom').each(function(label) {
            label.innerHTML = jQuery.base64Decode(this.config.childProductTierPriceHtml[productId]) + label.innerHTML;
        });
    }
};

Product.Config.prototype.reloadPrice = function(firstInitialisation) {
	

    var childProductId = this.getMatchingSimpleProduct();
    
    // Apparait quand couleur choisie et taille
    if (childProductId){
        //optionsPrice.productPrice = this.config.childProducts[childProductId];
        //optionsPrice.reload();
        //optionsPrice.reloadPriceLabels(true);
    	//Si on veut le fonctionnement de base de magento :
        //this.updateFormProductId(this.config.productId);
        //Si le fonctionnement de l'extension organic 
    	this.updateFormProductId(childProductId);
        this.addParentProductIdToCartForm(this.config.productId);
        
       /* if(!isQuickLookMode)
        {*/
        this.showTierPricesBlock(childProductId);
        //}
        //this.showCustomOptionsBlock(childProductId, this.config.productId);
        if( ! firstInitialisation) this.showCustomPriceBlock(childProductId, this.config.productId);
    } else { 
    	//Apparait quand seul couleur choisie.
        optionsPrice.productPrice = this.getLowestPossiblePrice();
        optionsPrice.reload();
        optionsPrice.reloadPriceLabels(false);
        this.showTierPricesBlock(false);
        if( ! firstInitialisation) this.showCustomOptionsBlock(false, false);
    }
};

Product.Config.prototype.showCustomOptionsBlock = function(productId, parentId) {
    var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
    var prodForm = $('product_addtocart_form');
    if(productId) {
        //Uncomment the line below if you want an ajax loader to appear while any custom 
        //options are being loaded.
        //$$('span.scp-please-wait').each(function(el) {el.show()});
        
        //prodForm.getElements().each(function(el) {el.disable()});
    	
        new Ajax.Updater('SCPcustomOptionsDiv', coUrl, {
          method: 'get',
          evalScripts: true,
          onComplete: function() {
              $$('span.scp-please-wait').each(function(el) {el.hide();});
              //prodForm.getElements().each(function(el) {el.enable()});
          }
        });
    } else {
        $('SCPcustomOptionsDiv').innerHTML = '';
        window.opConfig = new Product.Options([]);
    }
};

//Smile cyqui
Product.Config.prototype.showCustomPriceBlock = function(idchild, idproduct) {
	var lurlPattern = $('product-update-price-urlpattern').innerHTML;
	var lurl = lurlPattern.replace("%CHILDID%", idchild);
	var lurl = lurl.replace("%MODELID%", idproduct);
	$$('span.scp-please-wait').each(function(el) {el.show();});
	jQuery('span.scp-please-wait').activeXOverlap();
	new Ajax.Updater('simpleconfigurable-block-price', lurl, {
		method: 'get',
		asynchronous: false, /* Evite que les prix (couleur+taille) soient affichés avant les prix (tailles only) */
		//evalScripts: true,
		onComplete: function() {
			$$('span.scp-please-wait').each(function(el) {el.hide();});
			$('product-choosedarticle-referenceinfo').innerHTML = $('product-choosed-articleref').innerHTML;
		}
	});
};

Product.OptionsPrice.prototype.reloadPriceLabels = function(productPriceIsKnown) {
    var priceLabel = '';
    if (!productPriceIsKnown) {
        priceLabel = spConfig.config.priceFromLabel;
    }

    var priceSpanId = 'configurable-price-from-' + this.productId;
    var duplicatePriceSpanId = priceSpanId + this.duplicateIdSuffix;

    $(priceSpanId).select('span.configurable-price-from-label').each(function(label) {
        label.innerHTML = priceLabel;
    });

    if ($(duplicatePriceSpanId) && $(duplicatePriceSpanId).select('span.configurable-price-from-label')) {
        $(duplicatePriceSpanId).select('span.configurable-price-from-label').each(function(label) {
            label.innerHTML = priceLabel;
        });
    }
};
