String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}
function basicAcsSort(thisObject,thatObject) {	
	if (thisObject > thatObject)
	{
		return 1;
	}
	else if (thisObject < thatObject)
	{
		return -1;
	}
	return 0;
}
function basicDescSort(thisObject,thatObject) {	
	if (thisObject > thatObject)
	{
		return -1;
	}
	else if (thisObject < thatObject)
	{
		return 1;
	}
	return 0;
}

var TimerQueue = {
    queue: new Array(),
    messages: new Array(),
    enabled: true,
    addTimer: function(timerID)
    {
        if (this.enabled) this.queue.push({
            time: new Date(),
            id: timerID
        })
    },
    dequeueTimer: function()
    {
        if (!this.enabled)             	
            return '';
        var now = new Date();
        var timerObj = this.queue.pop();
        this.messages.push(timerObj.id + ' took ' + (now.getTime() - timerObj.time.getTime()));
    },
    
    getAllMessage: function(deliminator)
    {
        if (!this.enabled)             
            return '';
        var queueLength = this.queue.length;
        for (var i = 0; i < queueLength; i++) 
        {
            this.dequeueTimer();
        }
        
        var returnStr = '';
        for (var i = 0; i < this.messages.length; i++) 
        {
            returnStr += this.messages[i];
        }
        this.queue = new Array();
        this.messages = new Array();
        return returnStr;
    }
};

function PostForm(form, callback)
{
	try
	{
		var inputs = form.getElementsByTagName('input');
		var parameters = {};
		for (var i=0; i<inputs.length; i++)
		{
			var input = inputs[i];
			var type = input.getAttribute('type');
			if (!type)
				type = input.type;
			if (type != 'submit' && type != 'button') 
			{
				var name = input.getAttribute('name');
				var value = input.getAttribute('value');
				if (!name)
					name = input.name;
				if (!value)
					value = input.value;
				parameters[name] = value;
			}
		}
		var selects = form.getElementsByTagName('select');
		for (var i=0; i<selects.length; i++)
		{
			var selectElement = selects[i];
			for (var i = 0; i < selectElement.options.length; i++) 
			{
				var option = selectElement.options[i];
				if (option.selected) 
				{
					if (!parameters[selectElement.name])
						parameters[selectElement.name] = [];
					parameters[selectElement.name].push(option.value);
				}
			}
		}
		
		var action = form.getAttribute('action');
		if (!action)
			action = form.action;
		var request = new Ajax.Request(action, {
			method : 'post',
			parameters : parameters,
			onSuccess: function(transport){
		      	var response =  transport.responseText;
				callback(response);
		    }.bind(this),
			onFailure: function(transport){
		      	var response =  transport.statusText;
				callback(response);
		    }.bind(this)
		});
	}
	catch(e){}
	
	
	return false;
}


function ProductSelector()
{
    var self = this;
    var idItr = 0;
	this.id;
    this.selectors = {};
	this.initing = true;
	var splitChars = '_._';
    var oldSelectorState = {
        state: 'init'
    };
    
    this.printTraceLbl = null;
    this.printTrace = function(message, append)
    {
        if (!this.printTraceLbl)             
            return;
        if (append) 
        {
            this.printTraceLbl.innerHTML += message;
        }
        else this.printTraceLbl.innerHTML = message;
    };
    
    function getNextId()
    {
        return self.container.id + '_' + (idItr++);
    }
    
    function selectItem(selectorItem, unsetCurrent)
    {
        var selector = self.selectors[selectorItem.propertySelected];
        if (unsetCurrent) 
        {
            var oldItem = selector.selectedItem;
            selector.selectedItem = selectorItem;
            if (oldItem) 
            {
                deselectItem(oldItem, false);
            }
            
        }
       selectorItem.element.className = selector.options.selectedItemClass;
    }
    
    function deselectItem(selectorItem, unsetCurrent)
    {
        var selector = self.selectors[selectorItem.propertySelected];
        if (!selector.selectedItem || (selectorItem.element.id != selector.selectedItem.element.id))
		{
			selectorItem.element.className = selector.options.itemClass;
		} 
        if (unsetCurrent && selector.selectedItem) selector.selectedItem = null;
    }
	
	function getElement(selectorItem)
	{
		if (!selectorItem.element)
			selectorItem.element = document.getElementById(selectorItem.elementId);
		return selectorItem.element;
	}
	
    function getSelectorItemFromIdStr(selectorAndItemStr)
	{
		var splitArgs = selectorAndItemStr.split(splitChars);
		var reprocess_name = splitArgs[1].replace(/##/g,"'");
		// GEH BUG processing see other BUG GEH note
		var selectorItem = self.selectors[splitArgs[0]].items[reprocess_name];
		selectorItem.element = getElement(selectorItem);
		return selectorItem;
	}
	
	this.OnMouseOver=function(selectorAndItemStr)
	{
		try
		{
			if (this.hovering)
				return;
			this.hovering = true;
			var selectorItem = getSelectorItemFromIdStr(selectorAndItemStr);
			MouseOver(null, selectorItem);
		}
		catch(ex){}
	};
	this.OnMouseOut=function(selectorAndItemStr)
	{
		try
		{
			var selectorItem = getSelectorItemFromIdStr(selectorAndItemStr);
			MouseOut(null, selectorItem);
			this.hovering = false;
		}
		catch(ex){}
	};
	this.OnClick=function(selectorAndItemStr)
	{
		try
		{
			var selectorItem = getSelectorItemFromIdStr(selectorAndItemStr);
			Click(null, selectorItem);
		}
		catch(ex){}
	};
	
    function MouseOver(event, selectorItem)
    {
        TimerQueue.addTimer('::MouseOverStart');
        TimerQueue.addTimer('::SelectItem');
        selectItem(selectorItem);
        TimerQueue.dequeueTimer();
        showValidSkus(selectorItem);
		var selector = self.selectors[selectorItem.propertySelected];
		selector.selectionText.innerHTML = selectorItem.value;
		
		if (self._handleMouseOverEvent)
			self._handleMouseOverEvent(selectorItem);
        self.printTrace(TimerQueue.getAllMessage());
    }
    
    function MouseOut(event, selectorItem)
    {
        TimerQueue.addTimer('::HandleMouseOut');
        deselectItem(selectorItem, false);
        
        if (oldSelectorState.state == 'saved') 
        {
            for (var i = 0; i < oldSelectorState.items.length; i++) 
            {
                var savedStateItem = oldSelectorState.items[i];
                if (savedStateItem && i < oldSelectorState.items.length && (oldSelectorState.state == 'saved')) 
                {
                    Element.setOpacity(savedStateItem.item.element, savedStateItem.opacity);
					savedStateItem.item.valid = (savedStateItem.opacity>.5);
					savedStateItem.item.element.style.borderStyle = (savedStateItem.item.valid) ? 'solid' : 'dotted';
                }
            }
			
			for (var property in oldSelectorState.itemsText)
			{
				oldSelectorState.itemsText[property].element.innerHTML = oldSelectorState.itemsText[property].text;
			}
            
            if (oldSelectorState.selectedSkuItem) self.SelectedSkuItem = oldSelectorState.selectedSkuItem;
            self.CurrentState = oldSelectorState.CurrentState;
            
            oldSelectorState = {
                state: 'reverted'
            };
            
			if (self._revertSavedState)
				self._revertSavedState();
            
            var selectedSku = {};
            var validCombo = true;
            for (var property in self.selectors) 
            {
                var selector = self.selectors[property];
                if (selector.selectedItem) 
                {
                    selectedSku[selector.selectedItem.propertySelected] = selector.selectedItem.value;
                    if (!selector.selectedItem.valid) validCombo = false;
                }
            }
            
            if (validCombo && self._handleValidCombo) self._handleValidCombo(self.SelectedSkuItem);
            if (!validCombo && self._handleNonValidCombos) self._handleNonValidCombos(selectedSku);
        }
        TimerQueue.dequeueTimer();
        self.printTrace(TimerQueue.getAllMessage(), true);
    }
    
    function Click(event, selectorItem)
    {
        var selector = self.selectors[selectorItem.propertySelected];
		self.blockOOSMessageChange = false;
        if (selector.selectedItem && (selectorItem.element.id == selector.selectedItem.element.id)) 
        {
            selector.selectedItem = null;
            selector.selectionText.innerHTML = '&nbsp';
            deselectItem(selectorItem, true);
            showValidSkus(null);
            oldSelectorState = {
                state: 'reverted'
            };
        }
        else 
        {
            selectItem(selectorItem, true);
            selector = self.selectors[selectorItem.propertySelected];
            selector.selectionText.innerHTML = selector.selectedItem.value;
            showValidSkus(selectorItem);
            
			if (self._selectItemEvent)
				self._selectItemEvent(selectorItem);
        }
        
        if (self._handleSelection) 
		{
			var selectedSkuItem = (self.SelectedSkuItem) ? self.SelectedSkuItem : null;
			self._handleSelection(selectedSkuItem);
		}
    }
    
    this.getDefaultSelectedSku = function()
    {
        return {};
    };
	
	this.SelectValidSkus = function()
	{
		showValidSkus(null);
	};
	
    
    function showValidSkus(selectorItem)
    {
        TimerQueue.addTimer('::showValidSkus');
        TimerQueue.addTimer('::objectBuild');
        oldSelectorState.state = 'saving';
        oldSelectorState.selectedSkuItem = self.SelectedSkuItem;
        oldSelectorState.CurrentState = self.CurrentState;
		oldSelectorState.itemsText = {};
        oldSelectorState.items = [];
        var validSkuItem = true;
		
       	var selectedSku = self.getDefaultSelectedSku();
		if (selectorItem && selectorItem.subSelector)
			selectedSku[selectorItem.subSelector.property] = selectorItem.subSelector.value;
			
		if (selectorItem && selectorItem.secondaryValue) 
		{
			selectedSku[selectorItem.secondaryValueName] = selectorItem.secondaryValue;
		}
		
        if (selectorItem && selectorItem.propertySelected) 
        {
            selectedSku[selectorItem.propertySelected] = selectorItem.value;
            if (!selectorItem.valid) 
            {
                validSkuItem = false;
            }
        }
        else selectorItem = {
            propertySelected: null
        };
        for (var property in self.selectors) 
        {
            if (selectorItem.propertySelected != property) 
            {
                var selector = self.selectors[property];
                if (selector.selectedItem) 
                {
                    selectedSku[selector.selectedItem.propertySelected] = selector.selectedItem.value;
					
					if (selector.options.secondaryValue) 
					{
						selectedSku[selector.options.secondaryValue] = selector.selectedItem.secondaryValue;
					}
                }
				
            }
        }
		
        TimerQueue.dequeueTimer();
        var noMatch = false;
        TimerQueue.addTimer('::setItems');
        //this looks like brute force, but its really not as bas as it seems
        for (var property in self.selectors) 
        {
            var selector = self.selectors[property];
			oldSelectorState.itemsText[property] = {
				element: selector.selectionText,
				text: selector.selectionText.innerHTML
			};
            if (selectorItem.propertySelected != property) 
            {
                for (var itr in selector.items) 
                {
                    var item = selector.items[itr];
					item.element = getElement(item);
                    oldSelectorState.items.push({
                        opacity: Element.getOpacity(item.element),
                        item: item
                    });
                    
                    var toCompare = Object.clone(selectedSku);
                    toCompare[item.propertySelected] = item.value;
					if (item.secondaryValueName) 
					{
						toCompare[item.secondaryValueName] = item.secondaryValue;
					}
                    
                    TimerQueue.addTimer('::innerMatch');
                    var matchingItems = self.FindMatchingItems(toCompare, true);
                    TimerQueue.dequeueTimer();
                    if (matchingItems.length == 1)
                    {
						if (!item.valid) 
						{
							item.valid = true;
							Element.setOpacity(item.element, 1);
							item.element.style.borderStyle = 'solid';
						}
                    }
                    else
                    {
						if (item.valid) 
						{
							item.valid = false;
							Element.setOpacity(item.element, .3);
							item.element.style.borderStyle = 'dotted';
						}
						if (selector.selectedItem && (item.element.id == selector.selectedItem.element.id)) 
                        {
                            validSkuItem = false;
                        }
                    }
                }
            }
        }
        TimerQueue.dequeueTimer();
        
        TimerQueue.addTimer('::mediator');
        self.SelectedSkuItem = null;
        if (validSkuItem) 
        {
            var matchedItems = self.FindMatchingItems(selectedSku, false);
            if (matchedItems.length == 1) 
            {
                self.CurrentState = 'ValidSelection';
                self.SelectedSkuItem = matchedItems[0];
                if (self._handleValidCombo) self._handleValidCombo(self.SelectedSkuItem);
            }
            else 
            {
                self.CurrentState = 'MultipleSelection';
                if (self._handleValidCombo) self._handleValidCombo(selectedSku)
            }
        }
        else 
        {
            self.CurrentState = 'NonValidSelection';
            if (self._handleNonValidCombos) self._handleNonValidCombos(selectedSku);
        }
        
        oldSelectorState.state = 'saved';
        TimerQueue.dequeueTimer();
        TimerQueue.dequeueTimer();
    }
    
	this.FindMatchingItems = function (toCompare, firstOne)
	{
        return MatchItemsInArray(this.jsonData.sku_data, toCompare, firstOne);
	};
	
	this.FindMatchingOOSItems = function(toCompare, firstOne)
	{
        return MatchItemsInArray(this.jsonData.sku_data_oos, toCompare, firstOne);
	};
	
	function MatchItemsInArray(arr, toCompare, firstOne)
    {
        var items = [];
        for (var i = 0; i < arr.length; i++) 
        {
            var skuItem = arr[i];
            var equiv = true;
            for (var prop in toCompare) 
            {
                if (skuItem[prop] != toCompare[prop]) 
                {
                    equiv = false;
                    break;
                }
            }
            
            if (equiv) 
            {
                items.push(skuItem);
                if (firstOne)                     
                    return items;
            }
        }
        
        return items;
    }
    
    this.turnSelectorOff = function(selectorToDisable)
    {
        for (var property in self.selectors) 
        {
            if (property == selectorToDisable) self.selectors[property].selectorContainer.style.display = 'none';
        }
    };
    
    this.hidePrompts = function()
    {
        for (var property in self.selectors) 
        {
            var selector = self.selectors[property];
            selector.rtSelect.style.display = 'none';
        }
    };
    
    this.promptSelections = function()
    {
        var returnArray = [];
        for (var property in self.selectors) 
        {
            var selector = self.selectors[property];
            if (!selector.selectedItem && selector.display == 'block') 
            {
                selector.rtSelect.style.display = 'block';
               // selector.rtSelect.style.left = (Element.getWidth(selector.selectorTitleDivText) + 5) + 'px';
                returnArray.push(selector.displayText);
            }
        }

        return returnArray;
    };
    
    this.functionAddSelector = function(property, displayText, options)
    {
        TimerQueue.addTimer('::startRender-'+property);
        var selectorElement = {};
		var defaultSelector = '_XXdefault';
		
		selectorElement.options = Object.extend({
            itemClass: 'selectItem',
            selectedItemClass: 'selectedItem',
			innerHTMLProp : property,
			equalWidth : true,
			subSelectors : [{}],
			removeSingle : true,
			hideSelector : false,
			titleFormater : function(optionText)
			{
				return 'Select a ' + optionText + ': ';
			}
        }, options || {});
		
		if (selectorElement.options.hideSelector)
		{
			var hiddenToggleId = this.id+"_hiddenToggle_"+property;
			selectorElement.selectorUnhider = document.createElement('div');
			selectorElement.selectorUnhider.innerHTML = "<div onmouseover='$(\""+hiddenToggleId+"\").style.display = \"inline\"' onmouseout='$(\""+hiddenToggleId+"\").style.display = \"none\"' "+
				 "onclick=\"InstanceContainer.FireEvent('"+this.id+"', 'UnhideSelector', '"+property+"')\">[ + ] "+
				 "<span id='"+hiddenToggleId+"' style='display:none'>Show "+displayText+"</span></div><br />";
	        this.container.appendChild(selectorElement.selectorUnhider);
		}
		
        selectorElement.selectorContainer = document.createElement('div');
        selectorElement.selectorContainer.id = getNextId();
        selectorElement.selectorContainer.className = 'selectorContainer';
        this.container.appendChild(selectorElement.selectorContainer);
		if (selectorElement.options.hideSelector)
			 selectorElement.selectorContainer.style.display = 'none';
        
        selectorElement.rtSelect = document.createElement('div');
        selectorElement.rtSelect.className = 'selectRtArrow';
        selectorElement.rtSelect.style.display = 'none';
        selectorElement.rtSelect.innerHTML = '&nbsp;&nbsp;select';
        selectorElement.selectorContainer.appendChild(selectorElement.rtSelect);
        
        selectorElement.selectorTitleDiv = document.createElement('div');
        selectorElement.selectorTitleDiv.className = 'selectorTitle';
        selectorElement.displayText = displayText;
        selectorElement.selectorContainer.appendChild(selectorElement.selectorTitleDiv);
        selectorElement.selectorTitleDivText = document.createElement('span');
        selectorElement.selectorTitleDiv.appendChild(selectorElement.selectorTitleDivText);
        selectorElement.selectorTitleDivText.innerHTML = selectorElement.options.titleFormater(displayText);
        
        selectorElement.selectionText = document.createElement('span');
        selectorElement.selectionText.className = 'selectorText';
		selectorElement.selectionText.innerHTML = ' &nbsp ';
        selectorElement.selectorTitleDiv.appendChild(selectorElement.selectionText);
        
		selectorElement.elementsDivs = {};
		var itr=0;
		selectorElement.options.subSelectors.each(function(subSelector)
			{
				var elementsDivId = defaultSelector;
				var elem  = document.createElement('div');
				
				var subTitlesObj = {};
				if (subSelector.property)
				{
					var subTitle = document.createElement('div');
					subTitle.className = 'subSelectorTitle';
					if (!subSelector.displayText)
					{
						subTitle.style.display = 'none';	
					}
					else
					{
						subTitle.innerHTML = subSelector.displayText;
					}
		        	selectorElement.selectorContainer.appendChild(subTitle);
					elementsDivId = subSelector.property+'_'+itr;
					subTitlesObj.subTitle = subTitle;
				}
				selectorElement.elementsDivs[elementsDivId] = {
					itemContainer: elem,
					HTMLStr : '',
					numElements : 0,
					subTitlesObj : subTitlesObj
				};
				
		        elem.className = 'selectorElements';
		        selectorElement.selectorContainer.appendChild(elem);
				
				if (subSelector.property) 
				{
					if (itr < (selectorElement.options.subSelectors.length - 1)) 
					{
						var brElem = document.createElement('br');
						brElem.style.clear = 'both';
						selectorElement.selectorContainer.appendChild(brElem);
						subTitlesObj.br = brElem;
					}
					itr++;
				}
			}.bind(this)
		);
        
        selectorElement.items = {};
        var largestWidth = 0;
		var elementsDivId = defaultSelector;
		var noItems = true;
        this.jsonData.sku_data.each(function(skuItem)
        {
			for (var i=0; i<selectorElement.options.subSelectors.length; i++)
			{
				var itemId = property + '_' + skuItem[property];
				var subSelector =  selectorElement.options.subSelectors[i];
				if (subSelector.property) 
				{
					if (skuItem[subSelector.property] == subSelector.value)
					{
						elementsDivId = subSelector.property+"_"+i;
						itemId += '_'+subSelector.property+"_"+subSelector.value;
					}
					else
						continue;
				}
				else
					subSelector = null;
					
				
	            if (!selectorElement.items[itemId] && skuItem[property]) 
	            {
	                var selectItemId = getNextId();
					//push new item 
	                selectorElement.items[itemId] = {
	                    propertySelected: property,
						value : skuItem[property],
						exampleSku : skuItem,
						valid : true,
						elementId : selectItemId, 
						subSelector : subSelector
	                };
					
					if (selectorElement.options.secondaryValue)
					{
						selectorElement.items[itemId].secondaryValue = skuItem[selectorElement.options.secondaryValue];
						selectorElement.items[itemId].secondaryValueName = selectorElement.options.secondaryValue;
					}
					
	               //GEH BUG Rework of naming mechanism
	               var unProcessed_selectorAndItemStr = property+splitChars+ itemId;
	               var selectorAndItemStr = unProcessed_selectorAndItemStr.replace(/'/g,"##");

					var selectItemHTML = "<div id='"+selectItemId+"' "+
						"onmouseover=\"InstanceContainer.FireEvent('"+this.id+"', 'OnMouseOver', '"+selectorAndItemStr+"')\""+
						"onmouseout=\"InstanceContainer.FireEvent('"+this.id+"', 'OnMouseOut', '"+selectorAndItemStr+"')\""+
						"onclick=\"InstanceContainer.FireEvent('"+this.id+"', 'OnClick', '"+selectorAndItemStr+"')\""+
						"class='"+selectorElement.options.itemClass+"'>"+
						skuItem[selectorElement.options.innerHTMLProp]+"</div><span> </span>";
					selectorElement.elementsDivs[elementsDivId].HTMLStr += selectItemHTML;
					selectorElement.elementsDivs[elementsDivId].numElements++;
					noItems = false;
				}
        	}
        }.bind(this));
		
		selectorElement.selectorContainer.style.display = 'block';
		if (noItems || (!selectorElement.options.removeSingle && selectorElement.elementsDivs[elementsDivId].numElements == 1)) 
		{
			selectorElement.selectorContainer.style.display = 'none';
		}
		selectorElement.display = selectorElement.selectorContainer.style.display;
        
        var brElem = document.createElement('br');
        brElem.style.clear = 'both';
		for (var selectorDiv in selectorElement.elementsDivs)
		{
			if (selectorElement.elementsDivs[selectorDiv].numElements==0) 
			{
				selectorElement.elementsDivs[selectorDiv].itemContainer.style.display = 'none';
				if (selectorElement.elementsDivs[selectorDiv].subTitlesObj.br)
					selectorElement.elementsDivs[selectorDiv].subTitlesObj.br.style.display = 'none';
				if (selectorElement.elementsDivs[selectorDiv].subTitlesObj.subTitle)
					selectorElement.elementsDivs[selectorDiv].subTitlesObj.subTitle.style.display = 'none';
			}
			else 
			{
				selectorElement.elementsDivs[selectorDiv].itemContainer.innerHTML = selectorElement.elementsDivs[selectorDiv].HTMLStr;
				if (selectorElement.options.onAppendElementToItems)
					selectorElement.options.onAppendElementToItems(selectorElement.elementsDivs[selectorDiv].itemContainer);
				selectorElement.elementsDivs[selectorDiv].itemContainer.appendChild(brElem);
			}
		}
        if (selectorElement.options.equalWidth) 
        {
           	for (var itemId in selectorElement.items) 
            {
	            if (getElement(selectorElement.items[itemId]).clientWidth > largestWidth) 
					largestWidth = selectorElement.items[itemId].element.clientWidth;
           	}  
			for (var itemId in selectorElement.items) 
            {
                selectorElement.items[itemId].element.style.width = largestWidth + 'px';
           	}
        }
        this.selectors[property] = selectorElement;
		
		if (selectorElement.options.hideSelector)
		{
			selectorElement.selectorContainer.style.display = 'none';
		}
        TimerQueue.dequeueTimer();
			
		return selectorElement;
    };
	
	this.UnhideSelector = function(selectorProperty)
	{
		this.selectors[selectorProperty].selectorContainer.style.display = 'block';
		this.selectors[selectorProperty].selectorUnhider.style.display = 'none';
	};
	
    this.SetData = function(element, jsonData)
    {
        this.container = $(element);
        this.jsonData = jsonData;
    };
}

var previousShippingHTML = '';
DetailPageSkuSelector.prototype = new ProductSelector();

function DetailPageSkuSelector(id, pContainerToDraw, productObj)
{
    ProductSelector.call(this);
	var product = productObj;
	this.id = "SkuSelector_"+id;
	this.currentSelectedSku = null;
    var self = this;
    var oosMsg;
	var containerToDraw = $(pContainerToDraw);
    var buyNowBtn;
    var buyContainer;
	var buyNowContainerHeight;
    var buyNowMessageContainer;
    var selectedItemContainer;
    var selectedPriceLbl;
    var selectedItemLbl;
	var selectedSkuLbl;
    var shippingInfo;
    var buyNowMessage;
    var imageBoxId = 'imagebox1';
	var swatchImageId = 'swatchImage';
    var profile = false;
	var oosAdded = false;
    //profile = true;
    
    //alert(product.sku_data.length);
    
    this.init = function()
    {
        for (var i = 0; i < product.sku_data.length; i++) 
        {
			var skuItem =  product.sku_data[i];
			var swatchImg =skuItem.sku_swatch_image;
			if (!swatchImg || swatchImg=='')
			{
				swatchImg = 'http://mirror.altrec.com/images/shop/photos/nophoto_skuselect.gif';
			}
			else
			{
				swatchImg = 'http://mirror.altrec.com' + swatchImg;
			}
          	skuItem.imgHtml = '<div class="cropSwatch" style=\'background-image:url("' +swatchImg+'");\'>&nbsp;</div>';
				 
			var regularImg = skuItem.sku_swatch_image_d;
			if (!regularImg || regularImg=='')
			{
				regularImg = 'http://mirror.altrec.com/images/shop/photos/nophoto_d.gif';
			}
			else
			{
				regularImg = 'http://mirror.altrec.com' + regularImg;
			}
			skuItem.sku_swatch_image_reg = regularImg;
			skuItem.sku_swatch_image_zoomed = ((skuItem.sku_zoom_image && skuItem.sku_zoom_image!='') ? domainPrefix : '') + skuItem.sku_zoom_image;
			
			if (this.initItemItr)
				this.initItemItr(this.id, skuItem, product);
        }
        
        this.SetData(containerToDraw, product);
    };
	
	this.DrawBuyArea = function()
	{
        TimerQueue.addTimer('::startDrawBuyArea');
        oosMsg = document.createElement('div');
        oosMsg.className = 'productImgOOS';
        
        buyContainer = document.createElement('div');
        buyContainer.innerHTML = '&nbsp;';
        buyContainer.className = 'buyContainer';
        buyContainer.style.position = 'relative';
        containerToDraw.appendChild(buyContainer);
        
        buyNowBtn = document.createElement('div');
		buyNowBtn.id = 'buyNowBtn';
		buyNowBtn.innerHTML = "&nbsp;";
        buyNowBtn.className = 'buyNowBtn';
        
        buyNowBtnA = document.createElement('a');
        buyNowBtnA.id = 'buyNowBtnA';
        buyNowBtnA.href = '#';    
        buyNowBtnA.appendChild(buyNowBtn);
        buyContainer.appendChild(buyNowBtnA);
        buyNowBtnA = document.createElement('a');
        
        selectedItemContainer = document.createElement('div');
        selectedItemContainer.className = 'selectedItemContainer';
        buyContainer.appendChild(selectedItemContainer);
        
        selectedItemLbl = document.createElement('div');
        selectedItemLbl.className = 'selectedItemLbl';
        selectedItemContainer.appendChild(selectedItemLbl);
        
        selectedPriceLbl = document.createElement('div');
        selectedPriceLbl.className = 'selectedPriceLbl';
        selectedItemContainer.appendChild(selectedPriceLbl);
		
        selectedSkuLbl = document.createElement('div');
        selectedSkuLbl.className = 'selectedSkuLbl';
        selectedItemContainer.appendChild(selectedSkuLbl);
        
        shippingInfo = document.createElement('div');
        shippingInfo.className = 'shippingInfo';
        buyContainer.appendChild(shippingInfo);
        
        buyNowMessageContainer = document.createElement('div');
        buyNowMessageContainer.className = 'buyNowMessageContainer';
        buyContainer.appendChild(buyNowMessageContainer);
        var topArrow = document.createElement('div');
        topArrow.className = 'buyNowMessageTopArrow';
        topArrow.innerHTML = "&nbsp;";
        buyNowMessageContainer.appendChild(topArrow);
        buyNowMessage = document.createElement('div');
        buyNowMessage.className = 'buyNowMessage';
        buyNowMessageContainer.appendChild(buyNowMessage);
        
        buyNowBtn.onclick = this.clickBuyNowBtn.bindAsEventListener(self, null);
        this.CurrentState = 'MultipleSelection';
        
        // OOSfix
		if(product.pd_oos_sku_flag == 1 && product.sku_data.length == 0){
			buyNowBtn.style.backgroundPosition = '0px -90px';
		} 
		
        if (profile) 
        {
            self.printTraceLbl = document.createElement('div');
            Element.up(buyNowBtn).appendChild(self.printTraceLbl);
        }
        else TimerQueue.enabled = false;
		
        this.printTrace(TimerQueue.getAllMessage(), true);
	};
	
	this.RenderDefaultSelections = function()
	{
		this.SelectValidSkus();
		if (this.SelectedSkuItem) 
		{
			this._handleSelection(this.SelectedSkuItem);
		}
		else if (this.defaultSkuItem)
		{
			//simulate clicks
            for (var property in self.selectors) 
			{
				var selector = self.selectors[property];
				if (selector.display == 'block')
				{
					var str = property+'_._'+property+'_'+this.defaultSkuItem[property];
					
					try
					{
						if (selector.options.subSelectors && selector.options.subSelectors.length > 0 && selector.options.subSelectors[0].property)
						{
							str += '_'+selector.options.subSelectors[0].property+'_'+this.defaultSkuItem[selector.options.subSelectors[0].property];
						}

						str = str.replace(/'/g,"##");
					}
					catch (e)
					{
						//do nothing
					}
					this.OnClick(str);
				}
			}
		}
		this.initing = false;
	};
    
    this.clickBuyNowBtn = function(e, args)
    {
        if (this.CurrentState == 'ValidSelection') 
        {
            //var cartItem = new AltrecItem();
            selectedSKU.href = window.location.href;
            selectedSKU.productName = product.product_name;
			selectedSKU.brandName = product.pd_brand_name;
			selectedSKU.pid = product.pid;
			if (product.sku_data.length==1)
			{
				try
				{
					var imgSrc = $('fullimage').src;
					selectedSKU.sku_swatch_image = imgSrc;
				}
				catch(ex){}
			}
            
            //cartItem.setData(selectedSKU);
            //cart.addToCart(null, cartItem);
            
			var addToCartURL = "http://www.altrec.com" + mp_id + "/shop/cart/?SKU=" + selectedSKU.sid + "&quantity=1&action=Add";
            $('buyNowBtnA').setAttribute('href',addToCartURL);
        }
        else if (this.CurrentState == 'MultipleSelection') 
        {
            var neededSelectors = this.promptSelections();
            buyNowMessageContainer.style.display = 'block';
            buyNowMessageContainer.style.width = '300px';
            buyNowMessage.innerHTML = 'Please select a ';
            
            for (var i = 0; i < neededSelectors.length; i++) 
            {
                if (i > 0 && i < (neededSelectors.length - 1)) buyNowMessage.innerHTML += ', ';
                if (i > 0 && i == (neededSelectors.length - 1)) buyNowMessage.innerHTML += ' and ';
                buyNowMessage.innerHTML += neededSelectors[i];
            }
            buyNowMessage.innerHTML += ' before adding to cart';
            
            // OOSfix
            if(product.pd_oos_sku_flag == 1 && product.sku_data.length == 0){
            	buyNowMessage.innerHTML = 'Product is currently Not Available.';
            }
        }
        else //oos
        {
        	if (SkuSelector.OnOutOfStock && this.hasOOSSku) 
			{
				SkuSelector.OnOutOfStock(this.oosObj);
			}
        }
    };
    
	this._handleMouseOverEvent = function (selectorItem)
	{
        if (selectorItem.propertySelected == 'color' && !this.selectors['color'].selectedItem)
			this._swapColorSwatch(selectorItem.exampleSku.sku_swatch_image_reg);
	};
	
	this._revertSavedState = function ()
	{
      	if (this.selectors['color'].selectedItem) 
			this._swapColorSwatch(this.selectors['color'].selectedItem.exampleSku.sku_swatch_image_reg);
	};
	
	this._selectItemEvent = function ()
	{
		if (this.selectors['color'].selectedItem) 
			this._swapColorSwatch(this.selectors['color'].selectedItem.exampleSku.sku_swatch_image_reg);
	};
    
    this.getDefaultSelectedSku = function()
    {
        return {
            onhand_qty: 1
        };
    };
    
    this._handleSelection = function(sku)
    {
        buyNowMessageContainer.style.display = 'none';
        selectedPriceLbl.innerHTML = '';
        selectedItemLbl.innerHTML = '';
		selectedSkuLbl.innerHTML = '';
        shippingInfo.style.display = 'none';
		buyNowBtn.style.cursor = 'pointer';
		var warningLocation = document.getElementById('popshipMessage');
		if (warningLocation)
			warningLocation.innerHTML = '';	
        
        this.hidePrompts();
        selectedSKU = null;
		this.currentSelectedSku = null;
        if (sku != null) 
        {
        	
        	holidayMessage(sku);
            selectedSKU = sku;
            
            if(selectedSKU.SpecialOrder == "true"){
            	buyNowBtn.style.backgroundPosition = '0px -120px';
            }else{
            	buyNowBtn.style.backgroundPosition = '0px 0px';
            }
            var priceHTML = FormatCurrency(selectedSKU.sku_retail, true);
            if (selectedSKU.sku_price < selectedSKU.sku_retail) priceHTML = 
            	"<span class='saleFont'>" +
           	 	FormatCurrency(selectedSKU.sku_price, true) +
           	 	"</span>&nbsp;<strike>"+ FormatCurrency(selectedSKU.sku_retail, true) +
				"</strike>";
            selectedPriceLbl.innerHTML = priceHTML;
			selectedSkuLbl.innerHTML = "(#"+sku.sid+")";
			
            selectedItemLbl.innerHTML = selectedSKU.color;
			if (selectedItemLbl.innerHTML!='' && selectedSKU.size!='') 
				selectedItemLbl.innerHTML += ', ';
			selectedItemLbl.innerHTML +=  selectedSKU.size;
			if (sku.sk_options!='')
			{		
				if (selectedItemLbl.innerHTML!='')
					selectedItemLbl.innerHTML +=  " - ";		
				selectedItemLbl.innerHTML +=  sku.sk_options;
			}
			if (selectedItemLbl.innerHTML == '')
				selectedItemContainer.style.top = '0px';
            
		   this.currentSelectedSku = selectedSKU;
           this.SetShippingInfo(selectedSKU);
        }
        else if (this.CurrentState == 'MultipleSelection') 
        {
            buyNowBtn.style.backgroundPosition = '0px -30px';
            var warningLocation = document.getElementById('popshipMessage');
            if (warningLocation)
				warningLocation.innerHTML = '';	
            
        }
        else 
        {
			this.oosObj = {};
			
			for (var property in this.selectors) 
			{
				var selector = this.selectors[property];
				if (selector.selectedItem) 
				{
					this.oosObj[property] = selector.selectedItem.value;
				}
				
				if (selector.options.secondaryValue) 
				{
					this.oosObj[selector.options.secondaryValue] = selector.selectedItem.secondaryValue;
				}
			}
			
			this.hasOOSSku = false;
			var itemsMatched = this.FindMatchingItems(this.oosObj, true);
			if (itemsMatched.length == 0)
				itemsMatched = this.FindMatchingOOSItems(this.oosObj, true);
				
			if (itemsMatched.length == 1) 
			{
				this.oosObj = itemsMatched[0];
				this.hasOOSSku = true;
	            buyNowBtn.style.backgroundPosition = '0px -30px'; //OOSfix
			}
			else
			{
				buyNowBtn.style.cursor = 'auto';
	            buyNowBtn.style.backgroundPosition = '0px -90px';
			}
			
			//push product level items on sku
			for (var i in product) 
			{
				if (i != 'sku_data' && i != 'sku_data_oos')
					this.oosObj[i] = product[i];
			}
			
			this._handleNonValidCombos(this.oosObj);
			this.blockOOSMessageChange = true;
        }
    };
	
	this.SetShippingInfo = function(selectedSKU, supressAnimation)
	{
		var shippingHTML='';
        if (selectedSKU.sk_shipping_cost=='0.0' || selectedSKU.sk_shipping_cost=='') 
        {
            shippingHTML += '<li><a href="#" onclick="WebModal.Show(\'free_shipping_popup\',{width:400});return false"><b>FREE Shipping</b></a></li>';
        }
        else 
        {
            shippingHTML += '<li><a href="#" onclick="WebModal.Show(\'free_shipping_popup\',{width:400});return false"><b>'+FormatCurrency(Number(selectedSKU.sk_shipping_cost), true)+' for Ground</b></a></li>';
			shippingHTML += '<li><a href="#" onclick="WebModal.Show(\'free_shipping_popup\',{width:400});return false">Free on $45 Orders</a></li>';
        }
        if (Number(selectedSKU.shipping_extra)>0) 
        {
            shippingHTML += '<li><a href="#" onclick="WebModal.Show(\'free_shipping_popup\',{width:400});return false">'+FormatCurrency(Number(selectedSKU.shipping_extra), true)+' Oversize Charge</a></li>';
        }
		
        var now = new Date();
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
        now.setDate(now.getDate() + Number(selectedSKU.shipping_time));
        //shippingHTML += '<li><a href="#" onclick="WebModal.Show(\'free_shipping_popup\',{width:400});return false">Ships on <b>' + months[now.getMonth()] + ' ' + (now.getDate()) + '</b></a></li>';
		
		if (selectedSKU.sku_vendor_id)
		{
			 shippingHTML += '<li>Ships From : '+selectedSKU.sku_vendor_id+'</li>';
		}
		
		if (selectedSKU.cs_onhand_qty)
		{
			 shippingHTML += '<li>Qty On Hand : '+selectedSKU.cs_onhand_qty+'</li>';
		}
		
		if ($('shippingList')) 
		{
			if (previousShippingHTML == '')
				previousShippingHTML = $('shippingList').innerHTML;
			$('shippingList').innerHTML = shippingHTML;
			
			if (previousShippingHTML != shippingHTML && !supressAnimation) 
			{
				new Effect.Highlight($('shippingList'), {
					startcolor: '#ffff99',
					endcolor: '#fffffff'
				});
				previousShippingHTML = shippingHTML;
			}
		}
	};
    
    
    this.SwapSwatch = function(image)
    {
        try 
        {
            var imageElement = $(swatchImageId);
            if (imageElement.src != image) imageElement.src = image;
			
            if ($(imageBoxId).style.display != 'block') 
			{
				showImage(imageBoxId);
			}
        } 
        catch (e) 
        {
        }
    };
    
    this._swapColorSwatch = function(image)
    {
		InstanceContainer.FireEventAsync(this.id, 'SwapSwatch', 0, image);
		
		
		
		try
		{
			var imageSrcUrl = image;
			var imageKey = imageSrcUrl.substring(imageSrcUrl.indexOf('/images')).toLowerCase();
			if (zoom && (zoom.getZoomUrl() != imageMapForZoomer[imageKey])) 
			{
				var cleanImage = imageMapForZoomer[imageKey]
				zoom.SetAssets(swatchImageId, image, cleanImage.replace('http://www.altrec.com','http://mirror.altrec.com'));
			}
			
		}
		catch(e){}
    };
    
    var selectedSKU = null;
    this._handleNonValidCombos = function(sku)
    {
		if (this.blockOOSMessageChange)
			return;
		if (!oosAdded && $(swatchImageId))
		{
			Element.up($(swatchImageId)).appendChild(oosMsg);
			oosAdded = true;
		}
		
		var message = ' is no longer available';
		var appendTempOOSMessage = false;
		if (sku.sku_status_id)
		{
			if (sku.sku_status_id=='2' || sku.sku_status_id=='3')
			{
				appendTempOOSMessage = true;
				message = ' is currently unavailable'; 
			}
		}
		
		oosMsg.innerHTML = '';
		if (sku.color)
        	oosMsg.innerHTML = sku.color + message;        
		if (sku.size)
		{
			if (sku.color)
				oosMsg.innerHTML += ' in ' + sku.size;
			else
				oosMsg.innerHTML = sku.size + message;
		}
		if (this.selectors['sk_options'] && sku.sk_options && sku.sk_options!='')
		{
			if (oosMsg.innerHTML=='')
				oosMsg.innerHTML = 'This item is longer available ';
			oosMsg.innerHTML += " for "+sku.sk_options;
		}
		if (appendTempOOSMessage)
		{
			oosMsg.innerHTML += ""; //OOSfix
		}
        oosMsg.style.display = 'block';
    };
    
    this._handleValidCombo = function(sku)
    {
    	
		if (!oosAdded && $(swatchImageId))
		{
			Element.up($(swatchImageId)).appendChild(oosMsg);
			oosAdded = true;
		}
		
		if (this.blockOOSMessageChange)
			return;
			
        oosMsg.style.display = 'none';
    };
}
function holidayMessage(sku){
	//I need to figure out how long it is going to take to get a product to a customer
	//time to get to the customer is going to be set to 4 days initially
	
	
	
	var shippingTime = sku.shipping_time;
	
	var isAltrecShipper = sku.sku_alt_warehouse;
	
	var warningLocation = document.getElementById('popshipMessage');
	if (!warningLocation){
		//alert("this code thinks there is no ");
		return;
	}

	warningLocation.innerHTML = "";	
	
	//alert('this function has been called');

	//todays date
	var todayDate = new Date();
	
	//alert("today is: " + todayDate.toString())
	
	//groundShipDate
	var groundShipDate = new Date();
	groundShipDate.setUTCFullYear(todayDate.getUTCFullYear()-0);
	groundShipDate.setUTCMonth(todayDate.getUTCMonth()-0);
	groundShipDate.setUTCDate((todayDate.getUTCDate()-0) + (shippingTime - 0) + 4);	
	
	//threeDayShipDate
	var threeDayShipDate = new Date();
	threeDayShipDate.setUTCFullYear(todayDate.getUTCFullYear()-0);
	threeDayShipDate.setUTCMonth(todayDate.getUTCMonth());
	threeDayShipDate.setUTCDate((todayDate.getUTCDate()-0) + (shippingTime - 0) + 3);	
	
	//twoDayShipDate
	var twoDayShipDate = new Date();
	twoDayShipDate.setUTCFullYear(todayDate.getUTCFullYear()-0);
	twoDayShipDate.setUTCMonth(todayDate.getUTCMonth()-0);
	twoDayShipDate.setUTCDate((todayDate.getUTCDate()-0) + (shippingTime - 0) + 2);		
	
	//overnightShipDate
	var overnightShipDate = new Date();	
	overnightShipDate.setUTCFullYear(todayDate.getUTCFullYear()-0);
	overnightShipDate.setUTCMonth(todayDate.getUTCMonth()-0);
	overnightShipDate.setUTCDate((todayDate.getUTCDate()-0) + (shippingTime - 0) + 1);	
	
	//holiday date
	var holidayDate = new Date();	
	
	//set the holiday for December 25th, 2008
	holidayDate.setUTCFullYear(todayDate.getUTCFullYear());
	holidayDate.setUTCMonth(11);
	holidayDate.setUTCDate(24);

	//alert('ground ship: ' + groundShipDate.toString());

	//alert(holidayDate.toString() + " vs " + groundShipDate.toString());
	
	//empty out the 

	//discern which shipping method will get the product there by christmas
	if(groundShipDate < holidayDate)
	{
		//alert("ground ship");
		if(isAltrecShipper == "true"){
			//put up guaranteed by christmas message
			var newImage = document.createElement("img");		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.guaranteed.png");
			warningLocation.appendChild(newImage);		
		}
	}
	else if(threeDayShipDate < holidayDate)
	{
		//alert("3d ship");
		if(isAltrecShipper == "true"){
			//this product needs three day shipping to arrive on time
			//alert('3 day shipping');
			var newImage = document.createElement("img");
			var newImageLink = document.createElement("a");
			newImageLink.setAttribute("href", "/shop/giftcertificate/");
			newImageLink.appendChild(newImage);		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.2day.altrec.png");
			warningLocation.appendChild(newImageLink);
		}else{
			//this product needs three day shipping to arrive on time
			//alert('3 day shipping');
			var newImage = document.createElement("img");
			var newImageLink = document.createElement("a");
			newImageLink.setAttribute("href", "/shop/giftcertificate/");
			newImageLink.appendChild(newImage);		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.2day.png");
			warningLocation.appendChild(newImageLink);
		}
	}
	else if(twoDayShipDate < holidayDate)
	{
		//alert("2d ship");
		if(isAltrecShipper == "true"){
			//this product needs three day shipping to arrive on time
			//alert('3 day shipping');
			var newImage = document.createElement("img");
			var newImageLink = document.createElement("a");
			newImageLink.setAttribute("href", "/shop/giftcertificate/");
			newImageLink.appendChild(newImage);		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.2day.altrec.png");
			warningLocation.appendChild(newImageLink);
		}else{
			//this product needs two day shipping to arrive on time
			var newImage = document.createElement("img");
			var newImageLink = document.createElement("a");
			newImageLink.setAttribute("href", "/shop/giftcertificate/");
			newImageLink.appendChild(newImage);		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.2day.png");
			warningLocation.appendChild(newImageLink);
		}
	}
	else if(overnightShipDate < holidayDate)
	{
		//alert("ovrngt ship");
		if(isAltrecShipper == "true"){
			//this product needs three day shipping to arrive on time
			//alert('3 day shipping');
			var newImage = document.createElement("img");
			var newImageLink = document.createElement("a");
			newImageLink.setAttribute("href", "/shop/giftcertificate/");
			newImageLink.appendChild(newImage);		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.overnight.altrec.png");
			warningLocation.appendChild(newImageLink);
		}else{
			//this product needs overnight shipping to arrive on time
			var newImage = document.createElement("img");
			var newImageLink = document.createElement("a");
			newImageLink.setAttribute("href", "/shop/giftcertificate/");
			newImageLink.appendChild(newImage);		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.overnight.png");
			warningLocation.appendChild(newImageLink);
		}
	}
	else{
		//alert("wont make it");
			var newImage = document.createElement("img");
			var newImageLink = document.createElement("a");
			newImageLink.setAttribute("href", "/shop/giftcertificate/");
			newImageLink.appendChild(newImage);		
			newImage.setAttribute("src","http://mirror.altrec.com/images/shop/detail/popship.toolate.png");
			warningLocation.appendChild(newImageLink);
	}
		/*alert('normal shipping gets there: ' + (todayDate.getUTCDay()  + groundShipping)+
			  '\n3 day shipping gets there: '+ (todayDate.getUTCDay()  + threeDay)+
			  '\n2 day air gets there: '+(todayDate.getUTCDay()  + twoDay)+ 
			  '\novernight gets there: '+(todayDate.getUTCDay()  + overnight)+
			  '\n\n');	*/
}
var SkuSelector = {};
var skuMetaData = {};
var imageMapForZoomer = {};
var	shppingInfoMap = {};

function initItemItr(id, skuItem, product)
{
	if (product.default_sku && product.default_sku==skuItem.sid)
		InstanceContainer.GetInstance(id).defaultSkuItem = skuItem;
			
	if (skuItem.color_id == '8')
		skuItem.color = '';
		
	if (skuItem.sku_price < skuItem.sku_retail)
	{
		if (skuMetaData.salePrices.indexOf(skuItem.sku_price) == -1) 
		{
			skuMetaData.salePrices.push(skuItem.sku_price);
		}
		
		if (skuItem.sk_discontinued_flag  && skuItem.sk_discontinued_flag=='1')
		{
			skuMetaData.discountinuedTotal += 1;
		}
		skuItem.saleGroup = 'yes';
		
		if (skuItem.sku_retail > skuMetaData.regularPriceToDisplay)
			skuMetaData.regularPriceToDisplay = skuItem.sku_retail;
	}
	else
	{
		if (skuMetaData.regularPrices.indexOf(skuItem.sku_price) == -1) 
		{
			skuMetaData.regularPrices.push(skuItem.sku_price);
		}
		skuItem.saleGroup = 'no';
		
		
		if (skuItem.sku_retail < skuMetaData.lowestRegularPrice)
			skuMetaData.lowestRegularPrice = skuItem.sku_retail;
	}
	
	skuItem.sk_options = skuItem.sk_options.trim();
	skuItem.size = skuItem.size.trim();
	if (skuItem.sk_options && skuItem.sk_options !="")
	{
		skuMetaData.hasOptions = true;
	}
	
	if (skuItem.sku_vendor_id && skuItem.sku_vendor_id != '')
	{
		skuMetaData.hasVendor = true;
	}
	if (skuItem.cs_onhand_qty && skuItem.cs_onhand_qty != '')
	{
		skuMetaData.hasOnHand = true;
	}
	
	
	if (!imageMapForZoomer[skuItem.sku_swatch_image_d.toLowerCase()])
	{
		imageMapForZoomer[skuItem.sku_swatch_image_d.toLowerCase()] = skuItem.sku_swatch_image_zoomed;
	}
	
	var shippingKey = skuItem.sk_shipping_cost+"_"+skuItem.shipping_time;
	if (!shppingInfoMap[shippingKey]) 
	{
		shppingInfoMap[shippingKey] = {
			count: 1,
			item: skuItem
		};
	}
	else 
	{
		shppingInfoMap[shippingKey].count += 1;
	}
	
}

function createSelector(id, product)
{
	skuMetaData = {
		salePrices: [],
		regularPrices: [],
		lowestRegularPrice : 500000,
		regularPriceToDisplay : 0,
		discountinuedTotal: 0,
		hasOptions: false
	};
	var SkuSelectorObj = new DetailPageSkuSelector(id, 'buyNowBox', product);
	InstanceContainer.RegisterInstance(SkuSelectorObj);
	
	SkuSelectorObj.initItemItr = initItemItr;
	SkuSelectorObj.init();
	var pricesSubselctor = [{}];
	
	function formatPriceArr(priceArray)
	{
		var saleHtml = '';
		if (priceArray.length == 1) 
		{
			saleHtml = FormatCurrency(priceArray[0], true);
			return saleHtml;
		}
			
		var saleLow = priceArray[0];
		var saleHigh = priceArray[0];
		priceArray.each(function(price)
		{
			if (price != priceArray[0])
				saleHtml += ', ';
			
			saleHtml += FormatCurrency(price, true);
			if (price < saleLow) saleLow = price;
			if (price > saleHigh) saleHigh = price;
		});
		
		if (priceArray.length == 2 || true) 
		{
			saleHtml = FormatCurrency(saleLow, true) + " - " + FormatCurrency(saleHigh, true);
		}
		
		return saleHtml;
	}
	
	if (skuMetaData.salePrices.length>0 || skuMetaData.regularPrices.length>0) 
	{
		pricesSubselctor = [];
		skuMetaData.salePrices.sort(basicDescSort);
		skuMetaData.regularPrices.sort(basicDescSort);
		if (skuMetaData.salePrices.length == 0 && skuMetaData.regularPrices.length>0)
		{
			skuMetaData.regularPriceToDisplay = skuMetaData.regularPrices[0];
		}
				
		
		var saleHtml = "<span class='saleFont'>"+formatPriceArr(skuMetaData.salePrices)+"</span>";
		if (skuMetaData.regularPriceToDisplay <= skuMetaData.lowestRegularPrice)
			saleHtml += '';//" <b><strike>"+FormatCurrency(skuMetaData.regularPriceToDisplay, true)+"</strike></b>";
		saleHtml +="<span class='saleFont'> On Sale";
		
		/*
		if (skuMetaData.discountinuedTotal == skuMetaData.salePrices.length) 
			saleHtml += '';//" Discontinued Colors";
		else 
		{
			var saleSet = false;
			if (skuMetaData.discountinuedTotal < skuMetaData.salePrices.length) 
			{
				saleHtml += '';//" Sale";
				saleSet = true;
			}
			if (skuMetaData.discountinuedTotal > 0) 
			{
				if (saleSet)
					saleHtml += " &";
				saleHtml += '';//" Discontinued Colors";
			}
		}
		*/
		
		saleHtml +="</span>";
		
		var regularHtml = '<b>' + formatPriceArr(skuMetaData.regularPrices) + ' Reg. Price' + ((skuMetaData.regularPrices.length==1) ? '' : 's')+ '</b>';
		if (skuMetaData.regularPrices.length == 1 &&  skuMetaData.salePrices.length == 0)
		{
			regularHtml = null;	
		}
		if (skuMetaData.salePrices.length == 1 &&  skuMetaData.regularPrices.length == 0)
		{
			saleHtml = null;	
		}
		
		pricesSubselctor.push({
				property: 'saleGroup',
				value: 'no',
				displayText: regularHtml 
			});
		pricesSubselctor.push({
				property: 'saleGroup',
				value: 'yes',
				displayText: saleHtml
			});
	}
	
	if (skuMetaData.hasVendor)
		SkuSelectorObj.functionAddSelector('sku_vendor_id', 'Shipper', {hideSelector:false});
	if (skuMetaData.hasOnHand)
		SkuSelectorObj.functionAddSelector('cs_onhand_qty', 'Stock On Hand', {hideSelector:false});
	
	var colorSelector = SkuSelectorObj.functionAddSelector('color', 'Color', {
		itemClass: 'selectItemImage'
		,selectedItemClass: 'selectedItemImage'
		,innerHTMLProp: 'imgHtml'
		,equalWidth: false
		,secondaryValue : 'color_id'
		,subSelectors: pricesSubselctor
	});
	
	var sizeOptionArg = {secondaryValue : 'size_id', onAppendElementToItems :function(element){		
			if (sizingChartFlag) 
			{
				var imageChart = document.createElement('div');
				imageChart.style.styleFloat = 'left';
				imageChart.style.cssFloat = 'left';
				imageChart.style.marginLeft = '8px';
				imageChart.style.marginTop = '3px';
				
				imageChart.innerHTML = "<a onclick=\"showOne('tab3');\" href=\"#middleTabs\"><img src='http://mirror.altrec.com/images/shop/detail/icon.sizing2.gif' /></a>";
				element.appendChild(imageChart);
			}		
		}
	};
	
	if (colorSelector.selectorContainer.style.display == 'none')
	{
		sizeOptionArg.subSelectors = pricesSubselctor;
	}
	
	var sizeSelector = SkuSelectorObj.functionAddSelector('size', 'Size', sizeOptionArg);
	
	if (skuMetaData.hasOptions) 
	{
		var optionsArg = {
			removeSingle: false,
			titleFormater: function(optionText)
			{
				return "Select an Option: ";
			}
		};
		
		if (colorSelector.selectorContainer.style.display == 'none' && 
			sizeSelector.selectorContainer.style.display == 'none')
		{
			optionsArg.subSelectors = pricesSubselctor;
		}
		
		SkuSelectorObj.functionAddSelector('sk_options', 'Option', optionsArg);
	}
	
	SkuSelectorObj.DrawBuyArea();
	SkuSelectorObj.RenderDefaultSelections();
	
	return SkuSelectorObj.id;
}

var pageSkuSelectorId;
function InitSukSelector()
{
	$('loading_prodSelector').up().removeChild($('loading_prodSelector'));
	
	if (gup('showoos') == 'true') 
	{
		for (var i = 0; i < sku_list.product[0].sku_data_oos.length; i++) 
		{
			sku_list.product[0].sku_data.push(sku_list.product[0].sku_data_oos[i]);
		}
	}
	
	pageSkuSelectorId  = createSelector('inStockSkus', sku_list.product[0]);
}


function SkuInitAfterLoad()
{
	var largestKey = {count: 0, item: null};
	for (var key in shppingInfoMap)
	{
		if (shppingInfoMap[key].count > largestKey.count)
		{
			largestKey.count = shppingInfoMap[key].count;
			largestKey.item = shppingInfoMap[key].item;
		}
	}
	
	if (largestKey.item)
	{
		if (InstanceContainer.GetInstance(pageSkuSelectorId).currentSelectedSku)
			largestKey.item = InstanceContainer.GetInstance(pageSkuSelectorId).currentSelectedSku;
		InstanceContainer.GetInstance(pageSkuSelectorId).SetShippingInfo(largestKey.item, true);
	}
}



