/*
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--){
		try {
       		 var selected = this.settings[s].options[this.settings[s].selectedIndex];
		}
		catch (err) {
			break;
		}		
        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 + '/');
    $('product_addtocart_form').action = newcurrentAction;
    $('product_addtocart_form').product.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();
    });
    if (productId && config.childProductTierPriceHtml[productId]) {
        $$('div.product-options-bottom').each(function(label) {
            label.innerHTML = this.config.childProductTierPriceHtml[productId];
			document.getElementById("qty1").style.display = "block"; 
			document.getElementById("add-to-cart-submit").disabled = false;
			document.getElementById("add-to-cart-submit").style.cursor = "pointer";
			if(this.config.childProducts[productId]<=0) {
				label.innerHTML = "<span style='color:#A50327;font-size: 0.9em;'><strong>Call 1-800-442-3633 for pricing<br/>and ordering</strong></span>";
				document.getElementById("qty1").style.display = "none"; 
				document.getElementById("add-to-cart-submit").disabled = true;
				document.getElementById("add-to-cart-submit").style.cursor = "default";
			}
        });
    }
}




Product.Config.prototype.reloadPrice = function() {	
    var childProductId = this.getMatchingSimpleProduct();
    if (childProductId){
        optionsPrice.productPrice = this.config.childProducts[childProductId];
        optionsPrice.reload();
        optionsPrice.reloadPriceLabels(true);
		optionsPrice.reloadSku(true);
		optionsPrice.reloadUom(true);
        this.updateFormProductId(childProductId);
        this.addParentProductIdToCartForm(this.config.productId);
		$$('div.product-options-bottom').innerHTML = '';
        this.showTierPricesBlock(childProductId);
		// call image block
		//this.showImagesBlock(childProductId);
    } else {
        optionsPrice.productPrice = this.getLowestPossiblePrice();
        optionsPrice.reload();
        optionsPrice.reloadPriceLabels(false);
		optionsPrice.reloadSku(false);
		optionsPrice.reloadUom(false);
        this.showTierPricesBlock(false);
		$$('div.product-options-bottom').innerHTML = '';
    }
}


Product.OptionsPrice.prototype.reloadPriceLabels = function(productPriceIsKnown) {
    var priceLabel = '';
    if (!productPriceIsKnown) {
        priceLabel = spConfig.config.priceFromLabel;
    } else {
	
		var priceId = 'product-price-' + this.productId;
		Element.addClassName($(priceId), 'display');
	
		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;
			});
		}
	}
}

Product.OptionsPrice.prototype.reloadSku = function(productIsKnown) {
	var pid = spConfig.getMatchingSimpleProduct();
	$("productid").value = pid;
	var skuDivId = 'product-sku';
	if ($(skuDivId)) {
		var productSku = '';
		productSku = spConfig.config.childProductsSku[spConfig.getMatchingSimpleProduct()];
		if (!productIsKnown) {
			productSku = spConfig.config.ProductsSku;
		}
		$(skuDivId).innerHTML = productSku;
	}
}


Product.OptionsPrice.prototype.reloadUom = function(productIsKnown) {
	var uomDivId = 'product-uom';
	if ($(uomDivId)) {
		var productUom = '';
		productUom = spConfig.config.childProductsUom[spConfig.getMatchingSimpleProduct()];
		if (!productIsKnown) {
			productUom = spConfig.config.ProductsUom;
		}
		$(uomDivId).innerHTML = productUom;
	}
}

/****************** ConfigurableToSimple Module - End *************************/

/**
*	Function - to wrap the text
**/
function wordwrap( str, width, brk, cut ) {
	brk = brk || '\n';
	width = width || 75;
	cut = cut || false;
 
	if (!str) { return str; }
 
	var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
 
	return str.match( RegExp(regex, 'g') ).join( brk );
 
}
/**
*	Function - to display selected text below select box
**/
function checkvalue(att, num) {
	var x1 = document.getElementById('attribute'+att).selectedIndex;
	document.getElementById('attval'+att).innerHTML = wordwrap(document.getElementById('attribute'+att).options[x1].text, 25, '<br>', 1);
	document.getElementById('qty').value = 1;
	document.getElementById('qty1').disabled = false;
	
	for (var i=1; i<=document.getElementById("att_count").value; i++) {
		if ( i > num ) {
			document.getElementById('attval'+document.getElementById("att_value_"+i).value).innerHTML = "";
			document.getElementById("product_option_bottom").style.visibility ="hidden";
			document.getElementById("product-uom").style.visibility = "hidden";
		}
		else {
			document.getElementById("product_option_bottom").style.visibility = "visible";
			document.getElementById("product-uom").style.visibility = "visible";
		}
		document.getElementById('qty').value = 0;
		document.getElementById('qty1').value = 1;
	}
	
}

/**
*	Function - function differ recommanded and optional producuts
**/
function showhide() {
	if (document.getElementById('qty').value == 0) {
		for (var i=1; i<=document.getElementById("att_count").value; i++) {
			document.getElementById('attribute'+document.getElementById("att_value_"+i).value).disabled = false;
			document.getElementById('attval'+document.getElementById("att_value_"+i).value).disabled = false;
			if(i==1) break;
		}
		document.getElementById('qty1').disabled = false;
	}
	else {
		for (var i=2; i<=document.getElementById("att_count").value; i++) {
			document.getElementById('attribute'+document.getElementById("att_value_"+i).value).disabled = true;
			document.getElementById('attval'+document.getElementById("att_value_"+i).value).disabled = true;
			
			document.getElementById('attval'+document.getElementById("att_value_"+i).value).innerHTML = "";
			document.getElementById('attribute'+document.getElementById("att_value_"+i).value).value = "";
			document.getElementById('productid').value = "";
			
		}
		document.getElementById("product_option_bottom").innerHTML ="";
		document.getElementById("product-uom").innerHTML ="";
		document.getElementById('qty1').value = 0;
		document.getElementById('qty1').disabled = true;
	}
}

/**
*	Function - To apply validation during add to cart
**/
function chkvalidation( rec ) {
	if ( rec != "" ) {
		// Apply validations while recommandation present
		for (var i=1; i<=document.getElementById("att_count").value; i++) {
			if ( document.getElementById('qty').value == 0 ) {
				document.getElementById('attribute'+document.getElementById("att_value_"+i).value).className = "required-entry";
			}
			else {
				document.getElementById('attribute'+document.getElementById("att_value_"+i).value).className = "";
			}
		}
	} else {
		for (var i=1; i<=document.getElementById("att_count").value; i++) {
			document.getElementById('attribute'+document.getElementById("att_value_"+i).value).className = "required-entry";
		}
	}
}
