Event.observe(window, 'load',
	function() { if ($('ImageCarousel')) { new Carousel('ImageCarousel', 246); } }
);

function selectTab(tabElement) {	
	tabID = tabElement.id;
	if (tabID == "") { tabID = tabElement.href; }
	
	if (tabID.match(/(http)s?\:/gi)){
		baseNameRegExp = /[^\#]*\#/gi
		tabID = tabID.replace(baseNameRegExp, "");
	}
	baseNameRegExp = /^\#?(\D+)(\d+)/gi
	baseTabName = tabID.replace(baseNameRegExp, "$1");
	selectedTab = tabID.replace(baseNameRegExp, "$2");
	
	//Assumes <ul><li><href> tab structure...
	otherTabs = $(tabElement).up().siblings();
	otherTabs.each(function(tabItem) {
		$(tabItem).select('a.Tab')[0].removeClassName('active');
	})
	
	iTabCount = 1;
	do {
		$(baseTabName + "content" + iTabCount).removeClassName('active');
		iTabCount++;
	} while ($(baseTabName + "content" + iTabCount) != undefined)
	
	if($(baseTabName + "content0") != undefined) {
		$(baseTabName + "content0").removeClassName('active');	
	}
	
	$(baseTabName + "content" + selectedTab).addClassName('active');
	$(tabElement).addClassName('active');
}
function replaceMainImage(element, source) {
    if ($(element) && $(element).src != source) $(element).src = source;
}
function replaceMainImageAndAnchor(element, imageName) {
    var anchorSource = '/getdynamicimage.aspx?path=' + imageName + '&w=600&h=600';
    var imageSource = '/getdynamicimage.aspx?path=' + imageName + '&w=348&h=348';
    
    if ($(element) && $(element).href != anchorSource) {
        $(element).href = anchorSource;
        $(element).childElements()[0].src = imageSource;
    }
}

function validateOptions(value) {
    var iCount = value.split(';').length;
    if (iCount == $('OptionCount').value) {
        this.isValid = false;  // was $('ProductOptionValues') v
        $('ProductOptions').getElementsBySelector('input').each(function(value, element) {
            //  check if value exists
            if (value.split(';').uniq().sort().join(';') == element.value.split(';').uniq().sort().join(';')) {
                //  check if value extra exists
                if ($(element.identify() + '_extra')) {
                    //  change price
                    changePrice(parseFloat($(element.identify() + '_extra').value.split(';')[0]));
                    //  change image
                    changeImage($(element.identify() + '_extra').value.split(';')[1]);
                    //  change stock status
                    changeStockStatus();
                    //  change options
                    changeOptions(getOptionValue(value));
                    this.isValid = true;
                }
            }
            else {
                //  TODO:  awaiting stock status logic
            }
        } .bind(this, value));
		
        if (!this.isValid) {
            //  set defaults
            changePrice(0);
            changeImage($('DefaultImage').value);
            changeStockStatus();
            changeOptions('');
        }
    }
}


function changePrice(offset) {
    if ($('OriginalPrice') && $('OriginalPriceLabel'))
        $('OriginalPriceLabel').innerHTML = '$' + formatCurrency(parseFloat($('OriginalPrice').value) + offset);

    if ($('SalePrice') && $('SalePriceLabel'))
        $('SalePriceLabel').innerHTML = '$' + formatCurrency(parseFloat($('SalePrice').value) + offset);
}

function changeImage(image) {
    if ($('imgMain'))
        $('imgMain').src = '/getdynamicimage.aspx?path=' + image + '&w=250&h=250';
	if ($('mainImage'))
        $('mainImage').src = '/getdynamicimage.aspx?path=' + image + '&w=250&h=250';
}

function changeStockStatus() {
    //  TODO:  awaiting stock status logic
}

function changeOptions(value) {
    if ($('options'))
        $('options').value = value;
}

function setExtra(multiple) {
    var optionCount = ($('optionCount')) ? (parseInt($('optionCount').value)) : (0);
    var extra = '';
    var val = '';
    
    for (var y = 0; y < optionCount; y++) {
        var optionsBoxName = 'optionsBox_' + y + '_' + multiple;
        if ($(optionsBoxName)) {
            val += $(optionsBoxName).value + ((y < (optionCount - 1)) ? (';') : (''));
        }
    }

    $('ProductOptions').childElements().each(function(element) {
        if (element.value.split(';').uniq().sort().join(';') == val.toLowerCase().split(';').uniq().sort().join(';')) {
            var extraID = element.identify() + '_extra'
            if ($(extraID)) {
                setPrice($(extraID).value.split(';')[0]);
                //  TODO:  setImage($(extraID).value.split(';')[1]);
                //  TODO:  setStockStatus($(extraID).value.split(';')[3]);
            }
        }
    } .bind(this));
}


function setOption(optValue, changePrice) {
	$('options').value = $('option_' + optValue).value;
	
	validateOptions(aValues.join(';'));
	
	if (changePrice) 
	{
		if ($('option_' + optValue + '_extra')) 
		{
			var offset = $('option_' + optValue + '_extra').value;
    	if (parseFloat(offset) >= 0)
    	{
    		var newList = parseFloat($('baseList').value) + parseFloat(offset);
    		var newPrice = parseFloat($('basePrice').value) + parseFloat(offset);

    		if ($('ListPrice')) { $('ListPrice').innerHTML = 'List Price: $' + formatCurrency(newList); }    	
    		$('Price').innerHTML = 'Our Price: $' + formatCurrency(newPrice);
  		}
  	}
  }
}

var aValues = new Array();
function setOption(optValue, changePrice, switchImage) {
	//alert('option_' + optValue);
	//$('options').value = $('option_' + optValue).value;
	//$('options').value = $('option_' + optValue).value;
	//alert("?");
	var optionComplete = "option_";
	for (var i = 0; i < $('OptionCount').value; i++)
	{
		if(i != $('OptionCount').value - 1)
		{
			optionComplete = optionComplete + $('optionsBox_' + i + '_').value + ';';
		}
		else
		{
			optionComplete = optionComplete + $('optionsBox_' + i + '_').value;
		}
	}
	if($(optionComplete))
	{
		$('options').value = $(optionComplete).value;
		$('cartButton').show();
	}
	else
	{
		$('cartButton').hide();
		
	}
	if (optValue.length > 0) {
        var sOption = optValue.split('=')[0];
        var sValue = optValue.split('=')[1];

        var bReplaced = false;

        for (var i = 0; i < aValues.length; i++) {
            if (aValues[i].split('=')[0] == sOption) {
                aValues[i] = optValue;
                bReplaced = true;
            }
        }

        if (!bReplaced) {
            aValues[aValues.length] = optValue;
        }
	}
	
	//validateOptions(aValues.join(';'));
	if (switchImage) {
		$('ImageManipulators').getElementsBySelector('input').each(function(value, element) {
			if (element.value.split(';')[0] == value) {
				var image = element.value.split(';')[1];
				if (image != null && image.length > 0 && image.indexOf('noimage') < 0)
					changeImage(image);
			}
		} .bind(this, sValue));
	}
	
	if (changePrice) 
	{
		//if ($('option_' + optValue + '_extra')) 
		if ($(optionComplete + '_extra')) 
		{
			//var offset = $('option_' + optValue + '_extra').value;
			
			var offset = $(optionComplete + '_extra').value.split(';')[0];
			
			if (parseFloat(offset) >= 0)
			{

				//var newList = parseFloat($('baseList').value) + parseFloat(offset);
				//var newPrice = parseFloat($('basePrice').value) + parseFloat(offset);
				var newPrice = parseFloat($('productPrice').value) + parseFloat(offset);

				//if ($('ListPrice')) { $('ListPrice').innerHTML = 'List Price: $' + formatCurrency(newList); } 
				$('Price').innerHTML = '<strong>Price:<em><span class="Price"> $' + CurrencyFormatted(newPrice) + '</span></em></strong>';			
				//$('Price').innerHTML = 'Our Price: $' + formatCurrency(newPrice);
			}
  	}
	else
	{
		$('Price').innerHTML = '<strong>Price:</strong><span class="ProductStatus">Sorry, this option combination is not available</span>';			
		//$('Price').innerHTML = '<strong>Price:<em><span class="Price"> $' + CurrencyFormatted($('productPrice').value) + '</span></em></strong>';						
	}
  }
}
