﻿//global variables
var attribSectionID = 'visualAttributes';
var attribContainerClass = 'visualContainer';
var attribIDPrefix = 'attrib';
var attribTagType = 'input';
var selectedClassName = 'select';
var inactiveClassName = 'inactive';
var hoverClassName = 'hover';
var attribState;
var attribStateIdentify ;
var attribStateClassName ;
var previousVariantImage;



//class variant
function Variant(ID,Inventory, Price, Image, Name){ 
			this.ID = ID;
			this.Inventory = Inventory;
			this.Price = Price;
			this.Image = Image;
			this.Name = Name; 
} 


//save the state of every control before hover
function SaveState()
{
   attribStateIdentify = new Array();
   attribStateClassName = new Array();
   var AllInput = $("#"+attribSectionID+" "+attribTagType);
   for(var i=0;i<AllInput.length;i++)
    {
      if(AllInput[i].type=="button" || AllInput[i].type=="image" )
      {
      attribStateIdentify.push(AllInput[i].id);
      attribStateClassName.push(AllInput[i].className);
      }
    }
}

//restore the state of controls after mouse out
function RestoreState()
{
   if(attribStateIdentify != null)
   {
     for(var i=0;i<attribStateIdentify.length;i++)
     {
         document.getElementById(attribStateIdentify[i]).className = attribStateClassName[i];

      }
   }
}


    

//called from onmouseover event
function Hover(elem)
{
	//store the current state
	SaveState();
	
	//get the element being hovered over as a Jquery.js element
	var pElem = $("#"+elem.id);
	
	//if this attribute has a swatch image, show it.
	if(pElem.attr("type")=="image")
	{
	  showSwatchImage(elem.id);
	}
	
	//if the element is active, add the hover class to the element
	if (!pElem.hasClass(inactiveClassName))
	{
		pElem.addClass(hoverClassName);		
	}
	
	//show the other attributes that can be selected with the current attribute
	ShowValidCombosForHover(pElem);
}


//change medium image to swatch image 
function showSwatchImage(id)
{
  var medium = $("#"+id+"SwatchM");
  var large = $("#"+id+"SwatchL");
  if(medium.length > 0)
  {
    
    previousVariantImage = $('#variantImage').attr("innerHTML");
    if(large.length > 0)
    {
      $('#variantImage').attr({innerHTML:'<img style="cursor:pointer" onClick="popupimg(\''+large.val()+'\')" src="'+medium.val()+'" />'});
    }
    else
    {
       $('#variantImage').attr({innerHTML:'<img src="'+medium.val()+'" />'});
    }
  }
  
}

//when mouse out, restore the medium image
function RestoreSwatchImage(id)
{
  var medium = $("#"+id+"SwatchM");
  if(medium.length > 0)
  {
    $('#variantImage').attr({innerHTML: previousVariantImage});
  }
}

//called from onmouseout event
function Off(elem)
{
    //get the element that was just 'moused out' as a as a Jquery.js element
	var pElem = $("#"+elem.id);
	
	//remove the hover class from the element
	pElem.removeClass(hoverClassName);
	
    if (!pElem.hasClass(selectedClassName))
	{
		//if the element that was being hovered over was not selected, 
		//simply restore the state to what it was before the hover action
		//this logic is simpler than having to run through the select logic again
		RestoreState();
	    if(pElem.attr("type")=="image")
	    {
	       RestoreSwatchImage(elem.id);
	    }	
	}
	else
	{
		//otherwise, the hover item was actually selected, so now need to show the valid items
		ShowValidCombosForSelect(GetSelectedAttributes());
	}
	
}

//called from onclick event
function Select(elem)
{	

     //get the element being hovered over as a Jquery.js element
	var pElem = $("#"+elem.id);
	
    var ErrorInfo = $('#errorInfo');
    ErrorInfo.hide();
	
	
	//if the element has the hover class then remove it
	if (pElem.hasClass(hoverClassName))
	{
		pElem.removeClass(hoverClassName);
	}
	

	
	//remove the 'selected' class from all siblings of the currently selected element
	//the logic is that you can only select one attribute from each attributeContainer
	 pElem.siblings().each(function()
	 {
			$(this).removeClass(selectedClassName);
	 });
	 
	//add the 'selected' class to the currently selected element
	pElem.addClass(selectedClassName);
	
	var attribSelectName =  pElem.parent().prev(".attribSelectName");
	if (attribSelectName != null)
	{
	    attribSelectName.attr({innerHTML: "&#160;&#160;"+GetAttributeName(pElem) });				
	}
	
	var selectedAttributes = GetSelectedAttributes();
	
	var variantAttributesText = '';
	for (var i=0; i<selectedAttributes.length; i++)
	{
	    
		variantAttributesText += GetAttributeName($(selectedAttributes[i]));
		if (i < selectedAttributes.length - 1)
		{
			variantAttributesText += ',';
		}
	}
	
	
	
	if (selectedAttributes.length == NumAttributeSections)
	{
		ShowVariantInfo(selectedAttributes, ProductID);
	}
	showAttributesMapImage(variantAttributesText);
	ShowValidCombosForSelect(selectedAttributes);
}

// show all the valid attribute combination when mouse hover
function ShowValidCombosForHover(hoverAttribute)
{
    //extract the numbered ID of the attribute being hovered over	
	var hoverAttributeID = hoverAttribute.attr("id").replace(attribIDPrefix, '');
	
	var validIDs = new Array();
	
     //get an array of ALL the combos that the hovered attribute belongs to
	//this array contains IDs of attributes that need to be 'activated'
	for (var i = 0, len = ValidCombos.length; i < len; i++)
	{
		 var combo = ValidCombos[i].split(',');		
		 if (ArrayContains(combo,hoverAttributeID) != -1)
		 {
		     validIDs = validIDs.concat(combo);			
		 }
     }
     
      var siblings = hoverAttribute.siblings();
     //loop through every attribute in the Attributes container
      $("#"+attribSectionID+" "+attribTagType).each(function()
     {
         //extract the numbered ID of the element currently being iterated through
         var iteratedAttributeID = $(this).attr("id").replace(attribIDPrefix, '');
         if(ArrayContains(validIDs,iteratedAttributeID) == -1)
         {
            $(this).addClass(inactiveClassName);
         }
         else
         {
            $(this).removeClass(inactiveClassName);
         }
      
      });
}

//if the array contains the hoverAttributeID return index,
//else return -1
function ArrayContains(array, hoverAttributeID)
{
   	for (var i = 0, len = array.length; i < array.length; i++)
	{
	   if(array[i] == hoverAttributeID)
	   {
	   return i;
	   }
	}
	return -1;
}

//if the array contains the object hoverAttribute return index,
//else return -1
function ArrayContainsObject(array, hoverAttribute)
{
   	for (var i = 0, len = array.length; i < array.length; i++)
	{
	   if(array[i].id == hoverAttribute.id)
	   {
	    
	   return i;
	   }
	}
	return -1;
}


// show all the valid attributes combination after mouse click
function ShowValidCombosForSelect(selectedAttributes)
{

  if (selectedAttributes.length > 0)
	{		
		if (selectedAttributes.length > 1)
		{
			
		    //loop through every attribute in the Attributes container
            $("#"+attribSectionID+" "+attribTagType).each(function()
            {
             //extract the numbered ID of the element currently being iterated through
              $(this).addClass(inactiveClassName);
      
            });
		}
		else
		{
               $("#"+attribSectionID+" "+attribTagType).each(function()
				{
					if ( ArrayContainsObject($(selectedAttributes[0]).siblings(),this) == -1)
					{
						$(this).addClass(inactiveClassName);
					}
				});
		}
	
	
		//loop through all valid combos
		//	if the combo does not contain ALL of the selectedAttributes 
		//		then parse the combo and 'inactivate' the elements in that combo
	var selectedAttributeIDs = GetSelectedAttributesID();
	
	var validIDs = new Array();
	
	for (var j = 0, len = ValidCombos.length; j < len; j++)
		{
			var combo = ValidCombos[j].split(',');
			var flag = true;
			var selectedAttributeIDslen = selectedAttributeIDs.length;
			for(var i=0; i<selectedAttributeIDslen;i++)
			{
				if (ArrayContains(combo, selectedAttributeIDs[i]) == -1)
				{
					flag = false;
				}
			}
				
			if (flag)
			{
				validIDs = validIDs.concat(combo);
			}									
		}
		
		if (validIDs.length > 0)
		{
		    var validIDsLen = validIDs.length;
			for(var i=0; i<validIDsLen;i++)
				{
					$("#"+attribIDPrefix + validIDs[i]).removeClass(inactiveClassName);
				}
		}			
	}
	else
	{
		//this should occur when the Off method is invoked and no items are selected
		Reactivate();
	}
					 
}

//remove the inactive class from all attribute elements
function Reactivate()
{
  		 //loop through every attribute in the Attributes container
         $("#"+attribSectionID+" "+attribTagType).each(function()
          {
          //extract the numbered ID of the element currently being iterated through
             $(this).removeClass(inactiveClassName);
      
           });	
	
}


//clear all the selections and displayed info
function clearSelection()
{
          
         $("#"+attribSectionID+" "+attribTagType).each(function()
          {
          //extract the numbered ID of the element currently being iterated through
             $(this).removeClass(inactiveClassName);
             $(this).removeClass(selectedClassName);
          });

        var addToCartButton = $('#addToCartButton');
        //var addToWishButton = $('#addToWishButton');
		var availability = $('#availability');
		var price = $('#variantPrice');
		var variantAttributesList = $('#variantAttributes');
		$("#"+attribSectionID+" .attribSelectName").each(function()
		{
		  $(this).attr({innerHTML:''});
		});
		if($("#DDHideAddToCart").val() == 1)
        {
	      addToCartButton.hide();
	    }
		availability.hide();
		if($("#DDHidePrice").val() == 1)
        {
		   price.hide();
		}
		variantAttributesList.html("&nbsp;");
		$('#variantName').hide();
		$('#variantDesc').hide();
		var medium = $('#DefaultImage');
		var large = $('#DefaultLargeImage');
       if(large.length > 0)
       {
        $('#variantImage').attr({innerHTML:'<img id="ProductPic" style="cursor:pointer" onClick="popupimg(\''+large.val()+'\')" src="'+medium.val()+'" />'});
       }
       else
       {
        $('#variantImage').attr({innerHTML:'<img id="ProductPic" src="'+medium.val()+'" />'});
       }
		  
}


//get an array of the selected attribute 
function GetSelectedAttributes()
{

     return $("#"+attribSectionID+" ."+selectedClassName);
}


//get an array of the selected attribute IDs
function GetSelectedAttributesID()
{
     var SelectedAttributes = new Array();

	 $("#"+attribSectionID+" ."+selectedClassName).each(function()
     {
       SelectedAttributes.push($(this).attr("id").replace(attribIDPrefix, ''));
     });
     return SelectedAttributes;
}


//get the name of attribute
function GetAttributeName(element)
{
    var elementName = '';
    if (element != null)
	{		
		if (element.hasClass('attribImage'))
		{
			elementName = element.attr('alt');
		}
		else if (element.hasClass('attribButton'))
		{
			elementName = element.attr('value');
		}
	}
	return elementName;	
}


//after all the selections are made, show the variant info
function ShowVariantInfo(selectedAttributes, productID)
{				
	var attributeIDs = GetSelectedAttributesID();
	
	//generate a list of the selected attributes and display the list
	var variantAttributesList = $('#variantAttributes');
	var variantAttributesText = '';
	for (var i=0; i<selectedAttributes.length; i++)
	{
	    
		variantAttributesText += GetAttributeName($(selectedAttributes[i]));
		if (i < selectedAttributes.length - 1)
		{
			variantAttributesText += ',&#160;';
		}
	}
	variantAttributesList.attr({innerHTML:variantAttributesText});
		//show variant pricing, availability and add to cart button
	if (attributeIDs != null && attributeIDs.length > 0)
	{
		attributeIDs = attributeIDs.sort(sortNumber);

		var addToCartButton = $('#addToCartButton');
		//var addToWishButton = $('#addToWishButton');
		var availability = $('#availability');
		var variantID = $('#VariantID');
		var price = $('#variantPrice');
		
		var comboIndex = ArrayContains(ValidCombos,attributeIDs.join(','));
		
		if (comboIndex != -1)
		{
			var variant = Variants[comboIndex];
			var variantImage = variant.Image;
			if (variantImage.indexOf('nopicture') == -1)
			{
				$('#variantImage').attr({innerHTML:unescapeHTML(variantImage)});
				var allImageDiv = $("#variantMultiImages  div");
		        for(var i=0;i<allImageDiv.length;i++)
                 {
                     $(allImageDiv[i]).hide(); 
                 }
                $('#VariantsImagesDiv' +variant.ID).show();
			}
			if (variant.Inventory > 0)
			{
				variantID.attr({value:variant.ID});
				addToCartButton.show();
				//addToWishButton.show();
				price.html(unescapeHTML(variant.Price));
				price.show();
				availability.attr({innerHTML:""});
			}
			else
			{
			    if($("#ShowAddToCartOnNoStock").val() > 0)
			    {
			       variantID.attr({value:variant.ID});
			       addToCartButton.show();
			       //addToWishButton.show();
				   price.html(unescapeHTML(variant.Price));
				   price.show();
				   availability.attr({innerHTML:""});
			    }
			    else
			    {  
			       
		          if($("#DDHideAddToCart").val() == 1)
                  {
	                addToCartButton.hide();
	            }
	            //if ($("#DDHideAddToWish").val() == 1) {
	            //    addToWishButton.hide();
	            //}
	              
	              if($("#DDHidePrice").val() == 1)
                  { 
				    price.hide();
				  }
				   availability.attr({innerHTML:$("#outStock").val()});
				}
			}
			ShowVariantNameAndDesc();
        }		
		else
		{		
		   if($("#DDHideAddToCart").val() == 1)
            {
	           addToCartButton.hide();
	       }
	       //if ($("#DDHideAddToWish").val() == 1) {
	       //    addToWishButton.hide();
	       //}
	              
	        if($("#DDHidePrice").val() == 1)
             { 
			   price.hide();
		     }
		     availability.attr({ innerHTML: $("#notAvail").val() });
		     $('#variantName').hide();
		     $('#variantDesc').hide();		     
		}
		availability.show();				
	}
}

//transfer the escape character to HTML tag
function unescapeHTML(str) {   
  str = String(str).replace(/&gt;/g, '>').   
    replace(/&lt;/g, '<').   
    replace(/&quot;/g, '"').   
    replace(/&amp;/g, '&');   
  return str;   
}  

function sortNumber(a,b)
{
  return a - b;	
}


//ajax add to cart function for visual version 
function AddToCartAjax()
{
   
    var ErrorInfo = $('#errorInfo');
    var availability = $('#availability');
    ErrorInfo.hide();
    var attributeIDs = GetSelectedAttributesID();
    if(attributeIDs.length < NumAttributeSections)
    {
       ErrorInfo.attr({innerHTML:$('#makeSelections').val()});
       ErrorInfo.show();
       return ;
    }
    if(availability.attr("innerHTML").length > 1)
     {
       
       ErrorInfo.attr({innerHTML:availability.attr("innerHTML")});
       ErrorInfo.show();
       availability.hide();
       return;
     }
     
    if($("#Quantity").val() > 0)
	{
	   var ajaxurl="ajaxAddToCart.aspx";
       var para='&ProductID='+ $('#ProductID')[0].value+'&VariantID='+ $('#VariantID')[0].value+'&Quantity='+$('#Quantity')[0].value;
       myajax(ajaxurl,para);
	}
	else
	{
       ErrorInfo.attr({innerHTML:$('#enterQuantity').val()});
       ErrorInfo.show();
	}	
}

//add to cart function for visual version 
function AddToCart()
{
    var ErrorInfo = $('#errorInfo');
    var availability = $('#availability');
    ErrorInfo.hide();
    
    var attributeIDs = GetSelectedAttributesID();
    if(attributeIDs.length < NumAttributeSections)
    {
       ErrorInfo.attr({innerHTML:$('#makeSelections').val()});
       ErrorInfo.show();
       return ;
    }
     if(availability.attr("innerHTML").length > 1)
     {
       
       ErrorInfo.attr({innerHTML:availability.attr("innerHTML")});
       ErrorInfo.show();
       availability.hide();
       return;
     } 
 	if($("#Quantity").val() > 0)
	{
	   document.AddToCartForm.submit();
	}
	else
	{
       ErrorInfo.attr({innerHTML:$('#enterQuantity').val()});
       ErrorInfo.show();
	}				
}

//ajax add to cart function for dropdown version.
function DDAddToCartAjax()
{
  
  var ErrorInfo = $('#errorInfo');
  ErrorInfo.hide(); 
        
  var istartID=1;
  while($("#attributeGroup"+istartID).length>0)
  {
   if($("#attributeGroup"+istartID).val() == "parentAttr")
   {
     ErrorInfo.attr({innerHTML:$('#makeSelections').val()});
     ErrorInfo.show();
     return ;
   }
   istartID++;
  }  

    if($("#Quantity").val() > 0)
	{
	   var ajaxurl="ajaxAddToCart.aspx";
       var para='&ProductID='+ $('#ProductID')[0].value+'&VariantID='+ $('#VariantID')[0].value+'&Quantity='+$('#Quantity')[0].value;
       myajax(ajaxurl,para);
	}
	else
	{
       ErrorInfo.attr({innerHTML:$('#enterQuantity').val()});
       ErrorInfo.show();
	}	
}


//add to cart function for dropdown version.
function DDAddToCart()
{
     var ErrorInfo = $('#errorInfo');
     ErrorInfo.hide(); 
            
     var istartID=1;
     while($("#attributeGroup"+istartID).length>0)
      {
       if($("#attributeGroup"+istartID).val() == "parentAttr")
       {
         ErrorInfo.attr({innerHTML:$('#makeSelections').val()});
         ErrorInfo.show();
         return ;
       }
       istartID++;
      }  

	if($("#Quantity").val() > 0)
	{
	   document.AddToCartForm.submit();
	}
	else
	{
       ErrorInfo.attr({innerHTML:$('#enterQuantity').val()});
       ErrorInfo.show();
	}				
}
//add to wishlist function for dropdown version.
//function DDAddToWish() {
//    var ErrorInfo = $('#errorInfo');
//    ErrorInfo.hide();

//    var istartID = 1;
//    while ($("#attributeGroup" + istartID).length > 0) {
//        if ($("#attributeGroup" + istartID).val() == "parentAttr") {
//            ErrorInfo.attr({ innerHTML: $('#makeSelections').val() });
//            ErrorInfo.show();
//            return;
//        }
//        istartID++;
//    }

//    if ($("#Quantity").val() > 0) {
//        document.AddToWishForm.submit();
//    }
//    else {
//        ErrorInfo.attr({ innerHTML: $('#enterQuantity').val() });
//        ErrorInfo.show();
//    }
//}

function myajax(ajaxurl,para)
    {
        $('#miniCart').show();
        $('#miniCart').html('<div id="MiniCartLoading"><img src="images/spinner.gif" alt="Loading..." style="vertical-align:middle;" /> <strong>Adding item to cart...</strong></div>') 
        
        $.ajax({
          url: ajaxurl,
          type: 'POST',
          dataType: 'html',
          timeout: 20000,
          data:para,
          error: function(){},
          success: function(html){
         //the logic after success
          $('#miniCart').html(html);
          $('#NUM_CART_ITEMS').attr({innerHTML:$('#itemsCount').attr("innerHTML")});
          
         
                 }
            });
     }
 
function showAttributesMapImage(selectedAttributes)
{
     if(selectedAttributes.length == 0)
      return;
       $('#productMultiImages').hide();
     var hiddenDrop = document.getElementById("attributesMapDD");
    
     for(var i=0; i < hiddenDrop.options.length; i++)
     {
         var text = hiddenDrop.options[i].text;
         var variantID = hiddenDrop.options[i].value;
         
         if(selectedAttributes.toString() == text)
         {
           var variant = GetVariantByID(variantID);
           var variantImage = variant.Image;
			$('#variantImage').attr({innerHTML:unescapeHTML(variantImage)});
			var allImageDiv = $("#variantMultiImages  div");
	        for(var i=0;i<allImageDiv.length;i++)
             {
                 $(allImageDiv[i]).hide(); 
             }
            $('#VariantsImagesDiv' +variant.ID).show();
            return ;
         }
     }
     if($('#AutoFindImage').val() == 1)
     {
     var attributeIDs = DropDownGetSelectedAttr(NumAttributeSections+1);
         for (var i = 0, len = ValidCombos.length; i < ValidCombos.length; i++)
	    {
             if(ArrayIsInArray(attributeIDs, ValidCombos[i].split(",")) >0)
             {
               var variant = Variants[i];
               var variantImage = variant.Image;
               $('#variantImage').attr({innerHTML:unescapeHTML(variantImage)});
               var allImageDiv = $("#variantMultiImages  div");
	            for(var i=0;i<allImageDiv.length;i++)
                 {
                     $(allImageDiv[i]).hide(); 
                 }
                $('#VariantsImagesDiv' +variant.ID).show();
               return;
             }
	     }
	}
  
} 


function GetVariantByID(variantID)
{
      for(var i=0;i<Variants.length;i++)
     {
         if(Variants[i].ID == variantID)
         {
           return Variants[i];
         } 
     }

}

function ArrayIsInArray(arrayChild, array)
{ 
     for (var i = 0, len = arrayChild.length; i < arrayChild.length; i++)
	{
	   if(ArrayContains(array,arrayChild[i]) == -1)
	   {
	      return -1;
	   }
	}
	return 1;
} 
     
 
//called from onchange event 
function DropDownChange(elem)
{
   var pElem = $("#"+elem.id);
   var ErrorInfo = $('#errorInfo');
   ErrorInfo.hide();
   var nextID = elem.id.replace('attributeGroup', '');
    $('#variantName').hide();
    $('#variantDesc').hide();
    
    if(nextID == 1)
    {
      changeSizeLink(pElem.val());
    }
    
   if(pElem.val() == "parentAttr")
   {
      setFollowingDisabled(elem.id);
      //generate a list of the selected attributes and display the list
      var selectedAttributes = DropDownGetSelectedText(nextID);
       showAttributesMapImage(selectedAttributes);
	  var variantAttributesList = $('#variantAttributes');
	  var variantAttributesText = '';
	  for (var i=0; i<selectedAttributes.length; i++)
          {
        	  variantAttributesText += selectedAttributes[i];
	          if (i < selectedAttributes.length - 1)
	          {
		            variantAttributesText += ',&#160;';
	          }
          }
       variantAttributesList.attr({innerHTML:variantAttributesText});
       $('#variantName').hide();
       $('#variantDesc').hide();
     if($("#DDHideAddToCart").val() == 1)
    {
      $('#addToCartButton').hide();
    }
  
    if($("#DDHidePrice").val() == 1)
    {
      $('#variantPrice').hide();
    }
   }
   else
   {
     
      if(NumAttributeSections == nextID)
      {
      ShowDropDownVariantInfo();
      nextID++;
      var selectedAttributes = DropDownGetSelectedText(nextID);
      showAttributesMapImage(selectedAttributes);
      
      
      return;
      }
      nextID++;
      if($("#attributeGroup"+nextID).length>0)
      {
              $("#attributeGroup"+nextID).attr('disabled',false);
              var selectedAttributeIDs = DropDownGetSelectedAttr(nextID);
              
              var validIDs = new Array();
              var selectedAttributes = DropDownGetSelectedText(nextID);
              showAttributesMapImage(selectedAttributes);
              //generate a list of the selected attributes and display the list
	          var variantAttributesList = $('#variantAttributes');
	          var variantAttributesText = '';
	          for (var i=0; i<selectedAttributes.length; i++)
	          {
            	  variantAttributesText += selectedAttributes[i];
		          if (i < selectedAttributes.length - 1)
		          {
			            variantAttributesText += ',&#160;';
		          }
	           }
            variantAttributesList.attr({innerHTML:variantAttributesText});
        	
              for (var j = 0, len = ValidCombos.length; j < len; j++)
	            {
		            var combo = ValidCombos[j].split(',');
		            var flag = true;
		            var selectedAttributeIDslen = selectedAttributeIDs.length;
		            for(var i=0; i<selectedAttributeIDslen;i++)
		            {
			            if (ArrayContains(combo, selectedAttributeIDs[i]) == -1)
			            {
				            flag = false;
			            }
		            }
        				
		            if (flag)
		            {
			            validIDs = validIDs.concat(combo);
		            }									
	             }
              
              var validIDsLen = validIDs.length;
		      if(validIDsLen > 0)
		      {
		         document.getElementById("attributeGroup"+nextID).options.length=1;
		         var hiddenDrop = document.getElementById("attributeGroupHidden"+nextID);
		         for(var i=0; i < hiddenDrop.options.length; i++)
		         {
		             var id = hiddenDrop.options[i].value;
		             if(ArrayContains(validIDs, id) != -1)
		             {
		                document.getElementById("attributeGroup"+nextID).options.add(new Option(hiddenDrop.options[i].text,hiddenDrop.options[i].value));

		             }
		         }
		     
		      }
	         
              setFollowingDisabled("attributeGroup"+nextID);
              if(document.getElementById("attributeGroup"+nextID).options.length == 2)
              {
                 document.getElementById("attributeGroup"+nextID).selectedIndex = 1;
                 DropDownChange(document.getElementById("attributeGroup"+nextID));
              } 

	           	            
		}  
   } 
}

//get the all the values of selected options
function DropDownGetSelectedAttr(nextID)
{
  
  var SelectedAttrIDs = new Array();
  for(var i=1; i<nextID;i++)
  {
    if($("#attributeGroup"+i).val()!= "parentAttr")
    {
      SelectedAttrIDs.push($("#attributeGroup"+i).val());
    }
  }
  return SelectedAttrIDs;
}

//get the all the text of selected options
function DropDownGetSelectedText(nextID)
{
  
  var SelectedAttrIDs = new Array();
  for(var i=1; i<nextID;i++)
  {
    SelectedAttrIDs.push(document.getElementById("attributeGroup"+i).options[document.getElementById("attributeGroup"+i).selectedIndex].text);
  }
  return SelectedAttrIDs;
}


//diable all the following dropdown lists
function setFollowingDisabled(startID)
{
  
  var istartID = startID.replace('attributeGroup', '');
  istartID++;
  while($("#attributeGroup"+istartID).length>0)
  {
   $("#attributeGroup"+istartID).val("parentAttr");
   $("#attributeGroup"+istartID).attr('disabled',true);
   istartID++;
  }
  
  
}

//show variant info once you change the option 
function ShowDropDownVariantInfo()
{				
	var attributeIDs = DropDownGetSelectedAttr(NumAttributeSections+1);
	var selectedAttributes = DropDownGetSelectedText(NumAttributeSections+1);
	//generate a list of the selected attributes and display the list
	var variantAttributesList = $('#variantAttributes');
	var variantAttributesText = '';
	for (var i=0; i<selectedAttributes.length; i++)
	{   
		variantAttributesText += selectedAttributes[i];
		if (i < selectedAttributes.length - 1)
		{
			variantAttributesText += ',&#160;';
		}
	}
	variantAttributesList.attr({innerHTML:variantAttributesText});
		//show variant pricing, availability and add to cart button
	if (attributeIDs != null && attributeIDs.length > 0)
	{
		attributeIDs = attributeIDs.sort(sortNumber);

		var addToCartButton = $('#addToCartButton');
		//var addToWishButton = $('#addToWishButton');
		var availability = $('#availability');
		var variantID = $('#VariantID');
		var price = $('#variantPrice');
		
		var comboIndex = ArrayContains(ValidCombos,attributeIDs.join(','));
		
		if (comboIndex != -1)
		{
			var variant = Variants[comboIndex];
			
			var variantImage = variant.Image;

		    $('#variantImage').attr({innerHTML:unescapeHTML(variantImage)});
		    var allImageDiv = $("#variantMultiImages  div");
            for(var i=0;i<allImageDiv.length;i++)
             {
                 $(allImageDiv[i]).hide(); 
             }
            $('#VariantsImagesDiv' +variant.ID).show();
               

				
			
			if (variant.Inventory > 0)
			{
				variantID.attr({value:variant.ID});
				addToCartButton.show();
				//addToWishButton.show();
				price.html(unescapeHTML(variant.Price));
				price.show();
				availability.attr({innerHTML:""});
			}
			else
			{
			    if($("#ShowAddToCartOnNoStock").val() > 0)
			    {
			       variantID.attr({value:variant.ID});
			       addToCartButton.show();
			       //addToWishButton.show();
				   price.html(unescapeHTML(variant.Price));
				   price.show();
				   availability.attr({innerHTML:""});
			    }
			    else
			    {
			       variantID.attr({value:variant.ID});   
				   addToCartButton.hide();
				   price.hide();
				   availability.attr({innerHTML:$("#outStock").val()});
				}
			}
		}
		else
		{		
			addToCartButton.hide();
			price.hide();
			availability.attr({ innerHTML: $("#notAvail").val() });
			$('#variantName').hide();
		}
		availability.show();
		ShowVariantNameAndDesc();		
	}
}

//clear all the selections and displayed info
function clearDropDownSelection()
{
	 var allImageDiv = $("#variantMultiImages  div");
    for(var i=0;i<allImageDiv.length;i++)
     {
         $(allImageDiv[i]).hide(); 
     }
    $('#productMultiImages').show();
    setFollowingDisabled("attributeGroup1");
    document.getElementById("attributeGroup1").options.selectedIndex=0;
    var addToCartButton = $('#addToCartButton');
    //var addToWishButton = $('#addToWishButton');
    var availability = $('#availability');
    var price = $('#variantPrice');
    var variantAttributesList = $('#variantAttributes');
    if($("#DDHideAddToCart").val() == 1)
    {
      addToCartButton.hide();
    }
    availability.hide();
    if($("#DDHidePrice").val() == 1)
    {
      price.hide();
    }
    variantAttributesList.html("&nbsp;");
    $('#variantName').hide();
    $('#variantDesc').hide();
    var medium = $('#DefaultImage');
	var large = $('#DefaultLargeImage');
       if(large.length > 0)
       {
        $('#variantImage').attr({innerHTML:'<img id="ProductPic" style="cursor:pointer" onClick="popupimg(\''+large.val()+'\')" src="'+medium.val()+'" />'});
       }
       else
       {
        $('#variantImage').attr({innerHTML:'<img id="ProductPic" src="'+medium.val()+'" />'});
       }

       
}

//use appconfig ddoption to create the quantity dropdownlist 
function createQuantityDD(ddoption)
{
  var list = ddoption.split(',');
  document.write('<select  name="Quantity" id="Quantity">');
  for(var i=0;i<list.length;i++)
  {
    document.write('<option value="'+list[i]+'">'+list[i]+'</option>');
  }
  document.write("</select>");
  
} 

//ShowVariantDesc
function ShowVariantNameAndDesc()
{
  var vid = $('#VariantID').val();
  var variant;
  for(var i=0;i<Variants.length;i++)
  {
    if(Variants[i].ID == vid)
    {
     variant = Variants[i];
     break; 
    }
  }
  $('#variantName').attr({innerHTML:variant.Name});
  if(variant.Name.length > 0)
  {
    $('#variantName').show();
  }
  else
  {
    $('#variantName').hide();
  }
  
  var desc = $('#variantDesc'+vid).attr('innerHTML');
  $('#variantDesc').attr({innerHTML:desc});
  if(desc.length > 0)
 {
    $('#variantDesc').show();
  }
  else
  {
    $('#variantDesc').hide();
  }
  
}  


function swapImages(mediumPath, largePath)
{
   document.getElementById("ProductPic").src = mediumPath;
   document.getElementById("ProductPic").onclick = function(){popupimg(largePath)};     
}
     
function changeSizeLink(selectedValue)
{
  if(selectedValue == 3)
  {
     $('#sizeChart').attr("innerHTML",$('#sizeChart1').attr('innerHTML'));
  }
  else if(selectedValue == 20)
  {
     $('#sizeChart').attr("innerHTML",$('#sizeChart6').attr('innerHTML'));
  }
   else if(selectedValue == 4)
  {
     $('#sizeChart').attr("innerHTML",$('#sizeChart2').attr('innerHTML'));
  }
  else if(selectedValue == 5)
  {
     $('#sizeChart').attr("innerHTML",$('#sizeChart3').attr('innerHTML'));
  }
  
}