/**
 * Parses collection with delimiter
 * 
 * @param collection	Collection of HTML elements
 * @param delimiter		String delimiter to split the collection
 * @return	collectionString	Parsed collection String
 */
function CMParseCollection(collection, delimiter)
{
	var collectionString = "";
	for (var i=0; i<collection.length; i++)
	{
		collectionString += jQuery.trim(jQuery(collection[i]).text());
		if (collection.length != i + 1)
		{
			collectionString += delimiter;
		}
	}
	return collectionString;
}

/**
 * Formats any price string to required default Coremetrics price: "xx.xx"
 * @param str		Price string to parse
 * @return	str 	Parsed price string
 */
function CMPrice(str) {
	if (str) {
		str = str.replace(/[^0-9,.-]/g, '');
		if (str.indexOf(',') > -1) {
			if (str.indexOf('.') > -1) {
				intComaLastIndex = str.lastIndexOf(',');
				intDotLastIndex = str.lastIndexOf('.');
				if( intComaLastIndex > intDotLastIndex ) {
					str = str.replace(/\./g, '');
					str = str.replace(/,/g, '.');
				} else {
					str = str.replace(/,/g, '');
				}
			} else {
				str = str.replace(/,/g, '.');
			}
		}
	}
	return str;
}

/**
 * Gets SKU availability information, relative to color and customer vision.
 * Depends on product.js, full information retrieved after "VariantsLoaded" event
 * 
 * Note: This is very important analytics data!
 * 
 * @return	str 	Parse Availability string in the format xx of yy|oossku:oossku1..:ooskuN
 * 					Where: 	x - number of purchasable SKUs (color relative)
 * 							y - number of possible SKU variations (color relative)
 * 							oosku1..N - out of stock SKUs visible by the customer (color relative)
 */
function CMGetSKUAvailability()
{
	// One big try catch - we don't want Coremetrics to break the page.
	try {
		
		if (app.ProductCache && (app.ProductCache.master || app.ProductCache.variant))
		{
			var skuString = CMGetSkusInStock() + " of ";
			skuString += CMGetSkusOutOfStock();
			
			var swatches = jQuery(".variationattributes .swatches:not(.color)");
			var visibleOutOfStockSkus = "";
			
			if (swatches.length > 0)
			{
				var swatches1 = jQuery(swatches[0]).find(".swatchesdisplay li");
				jQuery.each( swatches1, function(valueIndex, swatchValue)
				{
					if (visibleOutOfStockSkus == "") visibleOutOfStockSkus = "|";
					
					if (swatches.length == 1 && jQuery(swatchValue).hasClass("unselectable"))
					{
						visibleOutOfStockSkus += (visibleOutOfStockSkus=="|"? "" : ":")+jQuery.trim(jQuery(swatchValue).text());
					}
					else
					{
						if (!swatches1.hasClass(".selected") || jQuery(swatchValue).hasClass(".selected"))
						{
							jQuery.each( jQuery(swatches[1]).find(".swatchesdisplay li.unselectable"), function(valueIndex, secondSwatchValue)
							{
								visibleOutOfStockSkus += (visibleOutOfStockSkus=="|"? "" : ":")+jQuery.trim(jQuery(swatchValue).text()) + jQuery.trim(jQuery(secondSwatchValue).text());
							});
						}
					}
				});
			}
			//if list is empty, remove the extra '|' symbol
			if(jQuery.trim(visibleOutOfStockSkus) == "|"){ 
				visibleOutOfStockSkus="";
			}
			return skuString + visibleOutOfStockSkus;
		}
		// Variation unavailable at this point.
		else if (jQuery(".variationattributes .swatches").length > 0) return "";
		else if (jQuery("div.addtocart button:not(:disabled)").length > 0) return "1 of 1";
		else return "0 of 1";
	}
	catch (error)
	{
		console.log("Coremetrics script encountered error - " + error);
		return "";
	}
}

/**
 * Gets the availability levels for this product.
 * @return	Number 	Number of SKUs
 */
function CMAvailabilityLevels()
{
	try 
	{
		if (app.ProductCache && (app.ProductCache.master || app.ProductCache.variant)) return Math.round(CMGetSkusInStock()/CMGetSkusOutOfStock()*100);
		else if (jQuery(".variationattributes .swatches").length > 0) return "";
		else if (jQuery("div.addtocart button:not(:disabled)").length > 0) return "100";
		else return "0";
	}
	catch (error)
	{
		console.log("Coremetrics script encountered error - " + error);
		return "";
	}
	return "";
}

/**
 * Gets the selected color (gets color list with "|" as a separator in case of product set).
 * @return	color text
 */
function CMSelectedColor()
{
	try 
	{
		var selectedColors = "";
		var swatches = jQuery(".variationattributes .swatches.color .value.selectedvarval");
		jQuery.each(swatches, function(valueIndex, swatchValue)
		{	
			//for each selected color, add its text along with "|" separating them.
			if(jQuery.trim(jQuery(swatchValue).text())!=""){
				selectedColors += jQuery.trim(jQuery(swatchValue).text());	
				selectedColors += "|";
			}
		});	
		
		if(selectedColors!=""){
			//remove last extra pipe ("|")
			selectedColors = selectedColors.slice(0,-1);
		}
	}
	catch (error)
	{
		console.log("Coremetrics script encountered error - " + error);
		return "";
	}
	return selectedColors;
}

/**
 * Gets the Price Displayed for this product
 * @return string with the price
 */

function CMPriceDisplayed()
{
	try 
	{
		if (app.ProductCache.subProducts.length > 0 && jQuery.trim(jQuery(".productdetail .cm-hidden-data.producttype").val())!="Bundle")
		{
			//product set
			return "";
		}else{
			//master product or variation or single or bundle
			var val = (CMPrice(jQuery('.productdetail .productdetailcolumn .pricing .salesprice').text()))+
				(jQuery('.productdetail .productdetailcolumn .pricing .standardprice').text().length>0 ? '|' : '') +
				(CMPrice(jQuery('.productdetail .productdetailcolumn .pricing .standardprice').text()));
			return val;
		}
	}
	catch (error)
	{
		console.log("Coremetrics script encountered error - " + error);
		return "";
	}
}


/**
 * Gets number of SKUs that are in stock, relative to color.
 * @return	Number 	Number of SKUs
 */
function CMGetSkusInStock()
{
	var variations = app.Product.productjson.data.variations;
	var skuString = 0;
	var selectedColor = app.ProductCache.selectedVarAttribs.color;
	var skusInstock = new Array();
	if (selectedColor != "")
	{
		skusInstock = app.ProductCache.findVariations({id: "color", val: selectedColor});
		skuString = skusInstock.length;
	}
	else
	{
		if (variations && variations.variants.length > 0)
		{
			for (var i=0; i<variations.variants.length; i++)
			{
				var variant = variations.variants[i];
				if (variant.avStatus != app.constants.AVAIL_STATUS_NOT_AVAILABLE)
				{
					skuString++;
				}
			}
		}
	}
	
	return skuString;
}

/**
 * Gets numbers SKU combinations that are visible by the customer, relative to color;
 * @return	Number 	Number of SKUs
 */
function CMGetSkusOutOfStock()
{
	var variations = app.Product.productjson.data.variations;
	var totalVarAttributes = variations.attributes;
	var totalDisplayedVariants = 1;
	if (totalVarAttributes && totalVarAttributes.length > 0)
	{
		for (var i=0; i <  totalVarAttributes.length; i++)
		{
			var attribute = totalVarAttributes[i];
			if (attribute.id != "color")
			{
				var allvalues = attribute.vals;
				if (allvalues && allvalues.length > 0)
				{
					totalDisplayedVariants = totalDisplayedVariants*(allvalues.length);
				}
			}
		}
	}	
	return totalDisplayedVariants;
}

