
Event.observe(window, 'load', function() {
    new Ajax.Autocompleter('tSearch', 'tSearchUpdate', '/User-Search-Parameters.aspx', {
        paramName: 'tSearch',
        tokens: ',',
        afterUpdateElement: function(text, li) {
            if ($('tSearchGo')) {
                var searchParameter = $('tSearch').value;
                var href = '/SearchResults.aspx?tSearch=' + searchParameter;
                window.location = href;
            }
        } .bind(this)
    });
    
    if ($('SubcatCarousel')) {
        new Carousel('SubcatCarousel', 570);
    }
});

var currentProductDetailsNav='Tab1Details';
var currentTab='Tab1';

///////////////////////  LEFT IMAGE HERE   ////////////////////
var t1,t2;	// for setTimeouts
var tipOn = false;	// check if over tooltip link
var dom = (document.getElementById) ? true : false;
var ns5 = (!document.all && dom || window.opera) ? true: false;
var ie5 = ((navigator.userAgent.indexOf("MSIE")>-1) && dom) ? true : false;
var ie4 = (document.all && !dom) ? true : false;
var nodyn = (!ns5 && !ie4 && !ie5 && !dom) ? true : false;
var origWidth, origHeight;

// avoid error of passing event object in older browsers
if (nodyn) { event = "nope" }


var tipFollowMouse= true;	
var tipWidth= 200;
var offX= 200;	// how far from mouse to show tip
var offY= -380; 
var tipFontFamily= "Verdana, arial, helvetica, sans-serif";
var tipFontSize= "8pt";
var tipFontColor= "#000000";
var tipBgColor= "#ffffff"; 
var tipBorderColor= "#666666";
var tipBorderWidth= 1;
var tipBorderStyle= "solid";
var tipPadding= 0;

var mouseX, mouseY;
var startStr = '<table width="' + tipWidth + '"><tr><td align="center" width="100%"><img src="';
var midStr = '" border="0"></td></tr><tr><td valign="top">';
var endStr = '</td></tr></table>';
var tooltip, tipcss;

function hideTip() {
	if (!tooltip) return;
	t2=setTimeout("tipcss.visibility='hidden'",100);
	tipOn = false;
}

function initTip() {
	if (nodyn) return;
	tooltip = (ie4)? document.all['tipDiv']: (ie5||ns5)? document.getElementById('tipDiv'): null;
	tipcss = tooltip.style;
	if (ie4||ie5||ns5) {	// ns4 would lose all this on rewrites
		tipcss.width = tipWidth+"px";
		tipcss.fontFamily = tipFontFamily;
		tipcss.fontSize = tipFontSize;
		tipcss.color = tipFontColor;
		tipcss.backgroundColor = tipBgColor;
		tipcss.borderColor = tipBorderColor;
		tipcss.borderWidth = tipBorderWidth+"px";
		tipcss.padding = tipPadding+"px";
		tipcss.borderStyle = tipBorderStyle;
	}
	if (tooltip&&tipFollowMouse) {
		document.onmousemove = trackMouse;
	}
}

function showBlinds(evt,imagePath) {
	if (!tooltip) initTip();
	if (!tooltip) return;
	if (t1) clearTimeout(t1);	if (t2) clearTimeout(t2);
	tipOn = true;
	//// set colors if included in messages array
	//if (messages[num][2])	var curBgColor = messages[num][2];
	curBgColor = tipBgColor;
	//if (messages[num][3])	var curFontColor = messages[num][3];
	//curFontColor = tipFontColor;
	if (ie4||ie5||ns5) {
		var tip = startStr + imagePath + midStr + endStr;
		tipcss.backgroundColor = curBgColor;
	 	tooltip.innerHTML = tip;
	}
	if (!tipFollowMouse) positionTip(evt);
	else t1=setTimeout("tipcss.visibility='visible'",100);
}


function trackMouse(evt) {
	standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
	mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
	mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;
	if (tipOn) positionTip(evt);
}

function positionTip(evt) {
	if (!tipFollowMouse) {
		standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body
		mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
		mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;
	}
	var tpWd = (ie4||ie5)? tooltip.clientWidth: tooltip.offsetWidth;
	var tpHt = (ie4||ie5)? tooltip.clientHeight: tooltip.offsetHeight;
	// document area in view (subtract scrollbar width for ns)
	var winWd = (ns5)? window.innerWidth-20+window.pageXOffset: standardbody.clientWidth+standardbody.scrollLeft;
	var winHt = (ns5)? window.innerHeight-20+window.pageYOffset: standardbody.clientHeight+standardbody.scrollTop;
	if ((0+offX+tpWd)>winWd) 
		tipcss.left = mouseX-(tpWd+offX)+"px";
	else tipcss.left = 0+offX+"px";
	if ((mouseY+offY+tpHt)>winHt) 
		tipcss.top = winHt-(tpHt+offY)+"px";
	else tipcss.top = mouseY+offY+"px";
	if (!tipFollowMouse) t1=setTimeout("tipcss.visibility='visible'",100);
}

function selectProductDetailsNav(container, element) {
	if (element != currentProductDetailsNav) {
	
		//  Step 1 (change the tab to current)
		$(currentProductDetailsNav).className=currentProductDetailsNav;
		$(element).className=element+'Current';
		
		//step 1a.  (container
		$(container).className=container+'Selected';
		$(currentTab).className=currentTab;
		
		
		
		//  Step 5 (change out the current tab)
		currentProductDetailsNav = element;
		currentTab = container;
    }

    //  For requirement "add to cart is only visible on tab 3"
    if ($('btnAddToCart')) {
        if ($('btnAddToCart').hasClassName('Description')) $('btnAddToCart').hide().removeClassName('Description');

        if (container == 'Tab3') $('btnAddToCart').show();
        else {
            if ($('btnAddToCart').visible()) $('btnAddToCart').hide();
        }
    }
    
    
}
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;
}

var aValues = new Array();
function setOption(value, switchImage) {
    if (value.length > 0) {
        var sOption = value.split('=')[0];
        var sValue = value.split('=')[1];

        var bReplaced = false;

        for (var i = 0; i < aValues.length; i++) {
            if (aValues[i].split('=')[0] == sOption) {
                aValues[i] = value;
                bReplaced = true;
            }
        }

        if (!bReplaced) {
            aValues[aValues.length] = value;
        }

        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.length > 0 && image.indexOf('noimage') < 0)
                        changeImage(image);
                }
            } .bind(this, sValue));
            populateSizes(sValue);
        }
        else {
            populateColors(sValue);
        }
    }
    else {
        if (switchImage){
            populateSizes("");
        }
        else{
            populateColors("");
        }
    }
}

function validateOptions(value) {
    var iCount = value.split(';').length;
    if (iCount == $('OptionCount').value) {
        this.isValid = false; 
        $('ProductOptionValues').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 validateOptions2() {
    if ($('OptionCount') && $('options')) {
        //  If the product has no options
        if (parseInt($('OptionCount').value) == 0) {
            return true;
        }
        else {
            //  If the product has options, and at least one is filled in
            if ($('options').value.length > 0 && aValues.length == parseInt($('OptionCount').value)) {
                return true;
            }
        }
    }
    alert("This product has options.  Please select options, then add this product to your bag.");
    return false;
}

function changePrice(offset) {
    if ($('OriginalPrice') && $('OriginalPriceLabel'))
        $('OriginalPriceLabel').innerHTML = '$' + formatCurrency(parseFloat($('OriginalPrice').value) + offset);

    if ($('SalePrice') && $('SalePriceLabel'))
        $('SalePriceLabel').innerHTML = '$' + formatCurrency(parseFloat($('SalePrice').value) + (offset * $('discount').value));
}

function changeImage(image) {
    if ($('imgMain'))
        $('imgMain').src = '/getdynamicimage.aspx?path=' + image + '&w=298&h=298';
}

function changeStockStatus() {
    //  TODO:  awaiting stock status logic
}

function changeOptions(value) {
    if ($('options'))
        $('options').value = value;
}

function formatCurrency(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

function validateForm() {
    if ($('OptionCount') && $('options')) {
        if ($('options').value.split(';').length == parseInt($('OptionCount').value))
            document.form2.submit();
    }
}

function getOptionValue(value) {
    this.optionValue = '';
    
    if ($('ProductOptionValues')) {
        $('ProductOptionValues').getElementsBySelector('input').each(function(value, element) {
            if (value.split(';').uniq().sort().join(';') == element.value.split(';').uniq().sort().join(';')) {
                if ($('OptionGroupID')) {
                    this.optionValue = $('OptionGroupID').value + ';' + element.identify();
                    return;
                }
            }
        } .bind(this, value));
    }

    return this.optionValue;
}

function HCF(u, v) {
    var U = u, V = v
    while (true) {
        if (!(U %= V)) return V
        if (!(V %= U)) return U
    }
}

function formatFraction(fraction) {
    var x = fraction.split('/')[0];
    var y = fraction.split('/')[1];

    var t = HCF(x, y); x /= t; y /= t;
    return x.toString() + '/' + y.toString();
}

function formatDimensions(w, we, h, he) {
	var widthWhole = w.toString();
  var widthEighths = '';        
  if (we.toString().length > 0 && we.toString() != '0') { widthEighths = ' ' + formatFraction(we.toString() + '/8'); }
  var heightWhole = h.toString();
  var heightEighths = '';
  if (he.toString().length > 0 && he.toString() != '0') { heightEighths = ' ' + formatFraction(he.toString() + '/8'); }

  return widthWhole + widthEighths + '" x ' + heightWhole + heightEighths + '"';
}

function updateSpecifiedDimensions() {
    var changedWidth = false;
    var changedHeight = false;
    
    if (parseInt($('width_whole_value_hidden').value) == parseInt($('width_max_hidden').value)) {
    	$('width_eighths_value_hidden').value = '0';
    	if ($('widthEighths')) {
    		$('widthEighths').selectedIndex = 0;
    		$('widthEighths').disable();
    	}
		} else {
			if ($('widthEighths')) {
				$('widthEighths').enable();
			}
    }

    if (parseInt($('height_whole_value_hidden').value) == parseInt($('height_max_hidden').value)) {
    	$('height_eighths_value_hidden').value = '0';
    	if ($('heightEighths')) {
    		$('heightEighths').selectedIndex = 0;
    		$('heightEighths').disable();
    	}
		} else {
			if ($('heightEighths')) {
				$('heightEighths').enable();
			}
    }
    
    if ($('specifiedDimensions')) {    	
        $('specifiedDimensions').innerHTML = formatDimensions($('width_whole_value_hidden').value, $('width_eighths_value_hidden').value, $('height_whole_value_hidden').value, $('height_eighths_value_hidden').value);
    }
    
    
    setParameter($('width_id_hidden').value, parseInt($('width_whole_value_hidden').value) + (parseInt($('width_eighths_value_hidden').value) / 8), false);
    setParameter($('height_id_hidden').value, parseInt($('height_whole_value_hidden').value) + (parseInt($('height_eighths_value_hidden').value) / 8), false);
    setPrice();
}

function selectColor(value, switchSelect) {
    var parameterID = value.split(';')[0];
    var valueID = value.split(';')[1];
    var valueName = value.split(';')[2];
    var valueImplementation = value.split(';')[3];
    
    if ($('ListColor')) {
        $('ListColor').getElementsBySelector('li').each(function(element) {
            element.removeClassName('selected');
            if (element.identify() == 'color_' + valueID.toString())
                element.addClassName('selected');
        });
    }
    
    if (switchSelect && $('ListColorSelect')) {
        for (var i = 0; i < $('ListColorSelect').options.length; i++) {
            if ($('ListColorSelect').options[i].value == value) {
                $('ListColorSelect').options[i].selected = true;
            }
        }
    }

    if ($('color_hidden'))
        $('color_hidden').value = valueName + ';' + valueID;
    if ($('specifiedColor'))
        $('specifiedColor').innerHTML = valueName;
        
    setParameter(parameterID, valueID.toString() + ';' + valueName.toString() + ';' + valueImplementation.toString(), true);
}

function selectTapeColor(value, switchSelect) {
    var parameterID = value.split(';')[0];
    var valueID = value.split(';')[1];
    var valueName = value.split(';')[2];
    var valueImplementation = value.split(';')[3];

    if ($('TapeColor')) {
        $('TapeColor').getElementsBySelector('li').each(function(element) {
            element.removeClassName('selected');
            if (element.identify() == 'tape_color_' + valueID.toString())
                element.addClassName('selected');
        });
    }

    if (switchSelect && $('TapeColorSelect')) {
        for (var i = 0; i < $('TapeColorSelect').options.length; i++) {
            if ($('TapeColorSelect').options[i].value == value) {
                $('TapeColorSelect').options[i].selected = true;
            }
        }
    }

    if ($('tape_color_hidden'))
        $('tape_color_hidden').value = valueName + ';' + valueID;
    if ($('specifiedTapeColor'))
        $('specifiedTapeColor').innerHTML = valueName;

    setParameter(parameterID, valueID.toString() + ';' + valueName.toString() + ';' + valueImplementation.toString(), true);
}

function setParameter(parameterID, value, _setPrice) {
    if ($(parameterID + '_value')) { $(parameterID + '_value').value = value; }
    if ($(parameterID + '_dirty')) { $(parameterID + '_dirty').value = "yes"; }
    if (_setPrice) { setPrice(); }
}

function setPrice() {
    if ($('PriceLabel')) {
        //$('PriceLabel').showLoading('/images/design/loadingMedium.gif');
        new Ajax.Request('/custom/PaylessDecor/pricePost.asp', {
            method: 'post',
            parameters: $('form2').serialize(true),
            onSuccess: function(transport) {
                var prices = transport.responseText.split('|');
                var price = 0;
                var cost = 0;
                if (prices.length >= 2) {
                    price = prices[0];
                    cost = (prices[1] == prices[0]) ? (0) : (prices[1]);
                    if (prices.length > 2) { resetParameters(prices[2]); }
                }
                else if (prices.length == 1) {
                    price = prices[0];
                    cost = 0;
                }

                setPriceLabel(price, cost);
                //$('PriceLabel').hideLoading();
            }
        });
    }
}

function resetParameters(paramList) {
	var obj = json_parse(paramList, function(key,value) { return value; });
	for(var i=0; i<obj.params.length; ++i) { 
		if ($(obj.params[i].ID + '_state')) { $(obj.params[i].ID + '_state').value = obj.params[i].State; }
		if ($(obj.params[i].ID + '_dirty')) { $(obj.params[i].ID + '_dirty').value = "no"; }
		if ($('optionbox_' + obj.params[i].ID)) {								
			if ($('option_' + obj.params[i].ID)) {
				if (obj.params[i].State != 'normal')
					$('option_' + obj.params[i].ID).disabled = true;
				else
					$('option_' + obj.params[i].ID).disabled = false;	
				
				switch(obj.params[i].Implementation){
					case 'dropdownparameter':
						var opt = obj.params[i].Value + ';' + obj.params[i].Description + ';' + obj.params[i].ValueImp;
						var sel = $('option_' + obj.params[i].ID);
						for(var j=0; j<sel.length; ++j) {
   						if(sel[j].value == opt) {
     						sel.selectedIndex = j;
     						if ($(obj.params[i].ID + '_value')) { $(obj.params[i].ID + '_value').value = opt; }
     					}
   					}
   					break;
					case 'checkboxparameter':					
					case 'labelcheckboxparameter':
					case 'userlabelcheckboxparameter':
						var opt = obj.params[i].Value + ';' + obj.params[i].Description + ';' + obj.params[i].ValueImp;
						var chk = $('option_' + obj.params[i].ID);
						chk.checked = (obj.params[i].Description == 'On');
						if ($(obj.params[i].ID + '_value')) { $(obj.params[i].ID + '_value').value = opt; }
						break;
					default:
						break;
				}
			} else {
				if (obj.params[i].State != 'normal')
					$$('#optionbox_' + obj.params[i].id + ' input').invoke('disabled','true');					
				else
					$$('#optionbox_' + obj.params[i].id + ' input').invoke('disabled','false');
				
				if ($('option_' + obj.params[i].ID + '_' + obj.params[i].Value)) {
					$('option_' + obj.params[i].ID + '_' + obj.params[i].Value).checked = true;
				}
			}
		}
	}
}

function setPriceLabel(price, cost) {
    $('PriceLabel').innerHTML = '';
    
    var priceLabel = Builder.node('strong');

    if (cost > 0 && price > 0) {
        priceLabel.innerHTML += 'Regular Price: <span id="Price" class="Strikeout"> $' + formatCurrency(price) + '</span><br />';
        priceLabel.innerHTML += 'Sale Price: <span id="SalePrice" class="Price"> $' + formatCurrency(cost) + '</span>';
    }
    else if (price > 0) {
        priceLabel.innerHTML += 'Price: <span id="Price" class="Price"> $' + formatCurrency(price) + '</span>';
    }
    else {
        priceLabel.innerHTML += 'Call for Details';
    }

    $('PriceLabel').appendChild(priceLabel);
}

function quickEstimate() {
    var fQuick = $('fQuick').serialize(true);
    document.location = '/' + fQuick.subcat + '/' + fQuick.subcat + '.asp?width=' + fQuick.width + '&widthpart=' + escape(fQuick.widthpart) + '&height=' + fQuick.height + '&heightpart=' + escape(fQuick.heightpart);
}

function setEstimates(setLower) {

    var hash = $H({
        pid: 0,
        width: $('width').value,
        widthpart: $('widthpart').value,
        height: $('height').value,
        heightpart: $('heightpart').value
    });

    var aProducts = $('ProductsWithParameters').value.split(',');
    var sPrices = '';

    for (var i = 0; i < aProducts.length; i++) {
        hash.set('pid', aProducts[i]);
        new Ajax.Request('/custom/paylessdecor/quickPost.asp', {
            method: 'post',
            parameters: hash,
            onSuccess: function(productID, transport) {
                var laPrices = transport.responseText.split('|');
                if (laPrices.length >= 2) {
                    if ($('PriceContainer_' + productID)) {
                        if (parseFloat(laPrices[1]) > 0 && parseFloat(laPrices[1]) < parseFloat(laPrices[0])) {
                            $('PriceContainer_' + productID).innerHTML = 'Regular Price: <span class="Strikeout">$' + formatCurrency(laPrices[0]) + '</span><br />Sale Price: $' + formatCurrency(laPrices[1]);
                        }
                        else {
                        	if (parseFloat(laPrices[0]) > 0) {
                            $('PriceContainer_' + productID).innerHTML = 'Price: $' + formatCurrency(laPrices[0]);
                        	}
                        	else {
                            $('PriceContainer_' + productID).innerHTML = 'CALL';
                        	}
                        }
                    }
                }
            } .bind(this, hash.get('pid'))
        });
    }
    
    if (setLower) {
        if ($('width2') && $('width')) $('width2').value = $('width').value
        if ($('widthpart2') && $('widthpart')) $('widthpart2').value = $('widthpart').value
        if ($('height2') && $('height')) $('height2').value = $('height').value
        if ($('heightpart2') && $('heightpart')) $('heightpart2').value = $('heightpart').value
    }
    else {
        if ($('width2') && $('width')) $('width').value = $('width2').value
        if ($('widthpart2') && $('widthpart')) $('widthpart').value = $('widthpart2').value
        if ($('height2') && $('height')) $('height').value = $('height2').value
        if ($('heightpart2') && $('heightpart')) $('heightpart').value = $('heightpart2').value
    }
}

function setProducts(subcatID) {
    resetProducts();
    if (subcatID.length > 0) {
        new Ajax.Request('/GetProducts.asp', {
            method: 'post',
            parameters: { subcatID: subcatID },
            onSuccess: function(transport) {
                var aOptions = transport.responseText.evalJSON();

                if (aOptions.length > 0) {
                    for (var i = 0; i < aOptions.length; i++) {
                        $('ddlProduct').insert('<option value="' + aOptions[i].value + '">' + aOptions[i].innerHTML + '</option>');
                    }
                    $('ddlProduct').selectedIndex=1;
                    setColors($('ddlProduct').value);
                }
            }
        });
        
    }
}

function resetProducts() {
    resetColors();
    $('ddlProduct').innerHTML = '';
    $('ddlProduct').insert('<option> -- Select a Color/Material</option>');
}

function setColors(paramID) {
    resetColors();
    if (paramID.length > 0) {
        new Ajax.Request('/GetColors.asp', {
            method: 'post',
            parameters: { paramID: paramID },
            onSuccess: function(transport) {
                var aOptions = transport.responseText.evalJSON();

                if (aOptions.length > 0) {
                    for (var i = 0; i < aOptions.length; i++) {
                        var sample = Builder.node('div', { 'class': 'Sample' }, [
                            Builder.node('a', { href: '/itemimages/parameters/' + aOptions[i].imageURL, rel: 'bloobox{bloom:1,width:400,height:400}', title: aOptions[i].name }, [
                                Builder.node('img', { id: 'Image_' + aOptions[i].name, src: '/getdynamicimage.aspx?dir=itemimages/parameters&path=' + aOptions[i].imageURL + '&width=100&height=100', alt: aOptions[i].name })
                            ]),
                            Builder.node('br'),
                            Builder.node('a', { href: '/itemimages/parameters/' + aOptions[i].imageURL, rel: 'bloobox{bloom:1,width:400,height:400}', title: aOptions[i].name }, [
                                Builder.node('strong', aOptions[i].name)
                            ]),
                            Builder.node('br'),
                            Builder.node('input', { 'class': 'SampleCheckbox', type: 'checkbox', name: 'Samples', value: aOptions[i].id + '|' + aOptions[i].name + '|' + aOptions[i].imageURL, 'onclick': 'javascript:setSamples();' }),
                            ' Add Sample'
                        ]);
                        $('SampleContainer').insert(sample);
                    }

                    var bloobox = new Bloobox();
                }
            }
        });
    }
}

function resetColors() {
    //resetSamples();
    $('SampleContainer').innerHTML = '';
}

function setSamples(element) {
    var aSampleAggregate = $('SamplesAggregate').value.split(';');
    if (aSampleAggregate.length == 1) {
        aSampleAggregate[0] = $('ddlSubcat')[$('ddlSubcat').selectedIndex].value;
        aSampleAggregate[1] = $('ddlProduct')[$('ddlProduct').selectedIndex].value;
    }

    var aSamples = new Array();
    $$('input.SampleCheckbox').each(function(element) {
        if (element.checked) {
            aSamples.push(element.value);
        }
    });
	if(aSampleAggregate[2])
	{
		aSampleAggregate[2] = aSampleAggregate[2] + ',' + aSamples.uniq().sort().join(',');
	}
	else
	{
		aSampleAggregate[2] = aSamples.uniq().sort().join(',');
	}
	aSampleAggregate[2] = aSampleAggregate[2].split(',').uniq().join(',');
	
    $('SamplesAggregate').value = aSampleAggregate.join(';');
    
    displaySamples();
}

function resetSamples() {
    //$('SamplesAggregate').value = '';
    displaySamples();
}

function displaySamples() {
    $('SampleSelections').innerHTML = '';
    
    var aSampleAggregate = $('SamplesAggregate').value.split(';');
    if (aSampleAggregate.length > 1) {
        var aSamples = aSampleAggregate[2].split(',');

        if (aSamples.length > 0) {

            for (var i = 0; i < aSamples.length; i++) {
                var sID = aSamples[i].split('|')[0];
                var sName = aSamples[i].split('|')[1];
                var sImageUrl = aSamples[i].split('|')[2];

                var selection = Builder.node('div', { 'class': 'ProductOptionBox1' }, [
                Builder.node('h4', [
                    Builder.node('img', { src: '/getdynamicimage.aspx?dir=itemimages/parameters&path=' + sImageUrl + '&width=60&height=60', alt: sName }),
                    Builder.node('span', [sName]),
                    Builder.node('input', { type: 'button', onclick: 'javascript:removeSample(' + sID + ');return false;', value: 'Remove' }),
                    Builder.node('div', { 'class': 'ClearFloat' })
                ])
            ]);

                $('SampleSelections').insert(selection);
            }
        }
    }
}

function toggleCCTable(show) {
    if (show) {
        $('CCTable').slideDown({ duration: 0.3 });
    }
    else {
        $('CCTable').slideUp({ duration: 0.3 });
    }
}

function toggleBillingTable(show) {
    if (show) {
        $('billingTable').slideDown({ duration: 0.3 });
    }
    else {
        $('billingTable').slideUp({ duration: 0.3 });
    }
}

function removeSample(sampleID) {
    var aSampleAggregate = $('SamplesAggregate').value.split(';');
    var aSamples = aSampleAggregate[2].split(',');

    for (var i = 0; i < aSamples.length; i++) {
        var aSampleValues = aSamples[i].split('|');

        if (aSampleValues[0] == sampleID) {
            uncheckSample(aSamples[i]);
            aSamples = aSamples.without(aSamples[i]);
        }
    }

    aSampleAggregate[2] = aSamples.uniq().sort().join(',');
    $('SamplesAggregate').value = aSampleAggregate.join(';');

    displaySamples();
}

function uncheckSample(value) {
    $$('.SampleCheckbox').each(function(value, element) {
        if (element.value == value) {
            element.checked = false;
        }
    } .bind(this, value));
}

function populateColors(selectedSize) {
    var otherIndex = document.getElementById("option_Color").selectedIndex;
    var otherItem = document.getElementById("option_Color")[otherIndex].value;

    while (document.getElementById("option_Color").options.length > 1) {
        document.getElementById("option_Color").remove(1);
    }
    var items = document.getElementById("ProductOptionValues").getElementsByTagName("input");
    var itemCount = items.length;
    var idRegEx = "_extra";
    var colors = "";
    var currentColor;
    var currentSize;
    for (var i = 0; i < itemCount; i++) {
        var itema = items.item(i).attributes;
        if (itema.getNamedItem("id").nodeValue.toString().match(idRegEx)) {
            if (itema.getNamedItem("value").nodeValue.toString().split(";")[2] > 0 && currentColor != "null") {
                var optOption = document.createElement("option");
                if (!colors.match(currentColor)) {
                    optOption.value = currentColor;
                    optOption.text = currentColor.replace("Color=", "");
                    document.getElementById("option_Color").options.add(optOption);
                    colors = colors + ";" + currentColor;
                }
            }
        }
        else {
            if (itema.getNamedItem("value").nodeValue.toString().toLocaleUpperCase().match(selectedSize.toString().toLocaleUpperCase())) {
                currentColor = items.item(i).attributes.getNamedItem("value").nodeValue.toString().split(";")[0];
            }
            else {
                currentColor = "null";
            }
        }
    }

    if (otherIndex != 0) {
        for (var i = 0; i < document.getElementById("option_Color").options.length; i++) {
            if (document.getElementById("option_Color")[i].value == otherItem) {
                document.getElementById("option_Color")[i].selected = true;
            }
        }
    }
}

function populateSizes(selectedColor) {
    var otherIndex = document.getElementById("option_Size").selectedIndex;
    var otherItem = document.getElementById("option_Size")[otherIndex].value;
    
    while (document.getElementById("option_Size").options.length > 1) {
        document.getElementById("option_Size").remove(1);
    }
    var items = document.getElementById("ProductOptionValues").getElementsByTagName("input");
    var itemCount = items.length;
    var idRegEx = "_extra";
    var sizes = "";
    var currentSize;
    for (var i = 0; i < itemCount; i++) {
        var itema = items.item(i).attributes;
        var t = items.item(i).attributes.getNamedItem("value").nodeValue.toString().split(";")[1];
        var u = selectedColor.toString().toLocaleUpperCase();
        var v = itema.getNamedItem("value").nodeValue.toString().toLocaleUpperCase();
        if (itema.getNamedItem("value").nodeValue.toString().split(";").length == 3)
            var w = itema.getNamedItem("value").nodeValue.toString().split(";")[2];
        if (itema.getNamedItem("id").nodeValue.toString().match(idRegEx) && currentSize != "null") {
            if (itema.getNamedItem("value").nodeValue.toString().split(";")[2] > 0) {

                var optOption = document.createElement("option");
                if (!sizes.match(currentSize)) {
                    optOption.value = currentSize;
                    optOption.text = currentSize.replace(" Size=", "").replace("Size=","");
                    document.getElementById("option_Size").options.add(optOption);
                    sizes = sizes + ";" + currentSize;
                }
            }
        }
        else {
            if (itema.getNamedItem("value").nodeValue.toString().toLocaleUpperCase().match(selectedColor.toString().toLocaleUpperCase())){
                currentSize = items.item(i).attributes.getNamedItem("value").nodeValue.toString().split(";")[1];
            }
            else{
                currentSize = "null";
            }
        }
    }

    if (otherIndex != 0) {
        for (var i = 0; i < document.getElementById("option_Size").options.length; i++) {
            if (document.getElementById("option_Size")[i].value == otherItem) {
                document.getElementById("option_Size")[i].selected = true;
            }
        }
    }
}

function submitProduct(loc) {
	if (loc == 'b') {document.getElementById("qty").value = document.getElementById("qtyBottom").value}
	else {document.getElementById("qty").value = document.getElementById("qtyTop").value}
	document.form2.submit();
}