/*  editor:cls, date:14.MAY.2008 - edited 05.JUN.2008 - Removed check for only in Stock
edited 05.JUN.add check for in stock

	To use this file, include it AFTER any call to any other include that has draw_sku_option.
	Then add an onClick call to findsku() from all 4 add buttons.
	
	Desc: draw_sku_option draws out a dropdown for each different attribute set (size, color, etc).
	Size dropdown draws out first, then color. (goes in order of attribute types as entered for skus)
	Once a size is selected, ONLY colors available in the selected size will appear in color dropdown.
	(To turn off the hiding of out of stock options, comment out or remove any ifs that check availability--.avail!='0'--.)
	
	If the attribute name is Attribute, Color is displayed instead of Attribute as a label.
	
	If you want pricing and availability messaging to appear after all attributes have been selected, 
	then add a div with id set to "prod_price" to the product page softcode.
	
*/

//array to hold all attributes
var product_attributes = new Array();

/* JMS NOTE: Add function to get all attributes to replace product_attributes array (structure the same as product_attributes) */
function getAttributes(){
	//see which variables we should fill and create array structure
	var int = 0;
	while (int<5){ //go through all 5 attributes of first sku
		if((product_var[0])["attr_value"+(int+1)] != "") 
			product_attributes[int] = new Array();
		int++;
	}
		
	var curAttr = "";
	//go through product_var	
	for(pv=0; pv<product_var.length;pv++) {
		int = 0; //reset int
		if(product_var[pv].avail!='0'){ //if available (comment this if out if you don't want to filter by availability)			
			//go through all 5 attributes
			while (int<5){
				//add each attribute if not empty
				curAttr = (product_var[pv])["attr_value"+(int+1)];
				
				if(curAttr != ""){
					//add attribute if not already in array
					if(!contains(product_attributes[int],curAttr)) 
						product_attributes[int].push(curAttr);
				}//end if curAttr != ""
				int++;
			}//end while
		}//end if available (comment this if out if you don't want to filter by availability)		
	}//end for
	
}//end getAttributes


/**
 * Returns true if 'e' is contained in the array 'a'
 * @author Johan Känngård, http://dev.kanngard.net
 */
function contains(a, e) {
	if(a!=null)
		for(j=0;j<a.length;j++)if(a[j]==e)return true;
	return false;
}

function initCap(str) {
 /* First letter as uppercase, rest lower */
 var str = str.substring(0,1).toUpperCase() + str.substring(1,str.length).toLowerCase();

 return str;
} 

/* JMS NOTE:  Need to change this to handle 0, 1, and multiple attributes */
function draw_sku_option()
{
	//get attributes
	getAttributes();
       var textFldCnt = 0;
	
	var dropdownattr1 = "";
	var attrname = "";
	var dropdown_label="";
	//document.write("<TABLE BORDER=0 CELLPADDING=2 CELLSPACING=0>");
	var selectionLabel = "";
	/* COMMENTED OUT to remove text above drop downs 
	if(product_attributes.length>0){
		selectionLabel = "Please select the following options:";
	}
	*************/
	document.write("<TR VALIGN=TOP ><TD class=\"ProductAttrlabel\">"+selectionLabel+"</td></tr>");
	for (outer=0;outer<product_attributes.length;outer++)
	{
		attrname = "attr" + (outer+1);		
		document.write("<TR VALIGN=TOP ><TD>");				
		
		
		if (attr_label[outer]=="Attribute")
		{
			dropdown_label="Color";
		}else
		{
			dropdown_label=attr_label[outer];
		}

              //WJS - Just write value if there's only one selection to choose from.
              
              if ( product_attributes[outer].length == 1 ) {
                 document.write("<div id=\"ddDiv\">"+dropdown_label+" : "+product_attributes[outer][0]+" </div>");
		   document.write("<input type=hidden id=attr"+(outer + 1)+" value='"+product_attributes[outer][0]+"'>");
                 textFldCnt ++;

                 if (textFldCnt == product_attributes.length) findprice();
          
                 continue;
              }	
              
              document.write("<select name="+attrname+" id="+attrname+" onchange=\"get_values("+(outer+1)+");findprice();\" class=\"ProductAttr\">");

		// add test Select before attribe label (Select Color) confirm label is initial Caps see initCap function above
		dropdown_label = "Select " + initCap(dropdown_label);
		document.write('<option value="" selected>'+dropdown_label+"</option>");
		product_attributes[outer].sort(smart_sort);
		
		for(innerarr=0;innerarr<product_attributes[outer].length;innerarr++)
		{
		  dropdownattr1=product_attributes[outer][innerarr];
		  document.write('<option value=\''+dropdownattr1+'\'>'+dropdownattr1+'</option>');
		}
		
		document.write("</select>");
		
		//document.write("<span id=single_option"+(outer+1)+"></span>");
	
		document.write("</TD></TR>");
	}
	document.write("<tr><td>Qty: <input type=text name=qty value=1 size=1></TD></TR>");
	//document.write("</table>");
	document.write("<INPUT TYPE='HIDDEN'  NAME='sku' id='sku' VALUE=''>");
} //end draw_sku_option

//get_values receives the attr number of the dropdown that has changed.
function get_values(ddnum)
{
  var thisattr,nextdd,tempattr,tempdd;
  var ctr = 0;
  var optstr = "";
  var tempopt;
  var attr_flag = true;
  var selection = "";
  var sel_flag = false;


  switch(product_attributes.length)
  {
    case 5:
      var dd5 = document.getElementById('attr5');
    case 4:
      var dd4 = document.getElementById('attr4');
    case 3:
      var dd3 = document.getElementById('attr3');
    case 2:
      var dd2 = document.getElementById('attr2');
      var dd1 = document.getElementById('attr1');

      for (i=ddnum+1;i<=product_attributes.length;i++)
      {
        //clear out the next dropdown
        nextdd = eval("dd"+i);
		
        //store the selected value so that it will remain selected if available
        selection = nextdd.value;
		//WJS - This may not even be a drop down menu if only 1 attribute exists..
		if (nextdd.type == "hidden") continue;
             
		//clear out select
		nextdd.options.length = 0;
       
		var sortarray= new Array();
		
        //loop thru product array
        for (atn=0;atn< product_var.length;atn++)
        {
          attr_flag = true;

          //loop through attribute values to see if there is NOT a match
		  for (k=1;k<=i-1;k++)
          {
            //check each dropdown up to one before nextdd
            tempattr = (product_var[atn])["attr_value"+k];
            tempdd = eval("dd"+k).value;
            if (tempattr != tempdd)
            {
              //this product doesn't match our selected values
              attr_flag = false;
            }
          }
		  
		  
          if (attr_flag == true)
          {
              //store the attr if it is new AND if available
              thisattr = (product_var[atn])["attr_value"+i];
              if (optstr.indexOf(";" + thisattr + ";") == -1)//removed to show all skus this checks availability && parseInt(product_var[atn].avail)>0)
              {
                optstr += ";" + thisattr + ";";
                //add to array here and sort instead of writing option
				sortarray[ctr]=thisattr;
                ctr++;
              }
          }
        }
		
		//write options here and clear array
		//change attribute to color
		if (attr_label[i-1]=="Attribute")
		{
			tempopt = new Option("Color","Color",false);
		}else
		{

			tempopt = new Option("Select " + initCap(attr_label[i-1]),attr_label[i-1],false);
		}        
        
		nextdd.options[0] = tempopt;
		
		sortarray.sort(smart_sort);
		
		/*if (sortarray.length==0)
		{
			nextdd.style.display = "none";
			
		}else
		{
			nextdd.style.display = "block";
			document.getElementById("single_option"+i).innerHTML="";
		}*/
		
		for (s=0;s<sortarray.length;s++){
			if (sortarray[s] == selection) { sel_flag = true; }else{ sel_flag = false; }
			tempopt = new Option(sortarray[s],sortarray[s],sel_flag);
			nextdd.options[s+1] = tempopt;
		}

        optstr = "";
        ctr = 0;
        selection = "";
      }
      break;
    case 1: //1 dropdown - do nothing here
    case 0: //no dropdowns - do nothing here
    default:

      break;
  }
}//end get_values

function findsku()
{
	if (typeof product_attributes!="undefined"){
		if(product_var.length>1){

			var matchsku=false;
			var eachsku=0;
			var selectedsku;
			while (matchsku==false && eachsku<product_var.length)
			{
				var matching=true;
				
				for (drop=1;drop<=product_attributes.length ;drop++)
				{					

				//document.getElementById('this').value=document.getElementById('dropsku'+drop).options[document.getElementById('dropsku'+drop).selectedIndex].value;          
                            
                            //WJS - Some attributes may be text / hidden elements
				if ( document.getElementById('attr'+drop).type == "hidden" ){
				     if ((product_var[eachsku])["attr_value"+drop]!=document.getElementById('attr'+drop).value){matching=false;}
				} else {
				     if ((product_var[eachsku])["attr_value"+drop]!=document.getElementById('attr'+drop).options[document.getElementById('attr'+drop).selectedIndex].value){matching=false;}
				}
                            }
				if (matching==true)
				{
					selectedsku=product_var[eachsku].sku;
					matchsku=true;
	
					//alert(selectedsku);
					document.getElementById("sku").value=selectedsku;
	
					return true;		
				}
				eachsku=eachsku+1;
			}//end while
		}//end if
		else{
			document.getElementById("sku").value=product_var[0].sku;
			return true;
		}
	}//end if
}//end findsku

function findprice(){
	if (typeof product_attributes!="undefined" && document.getElementById("prod_price")){
	
		var matchsku=false;
		var eachsku=0;
		var selectedskuprice;
		var listprice;
		var avail_message;
		while (matchsku==false && eachsku<product_var.length)
		{
			var matching=true;
			for (drop=1;drop<=product_attributes.length ;drop++)
			{
                            
				//document.getElementById('this').value=document.getElementById('dropsku'+drop).options[document.getElementById('dropsku'+drop).selectedIndex].value;          //WJS
				
                            //WJS - Some attributes may be text / hidden elements

                            if ( document.getElementById('attr'+drop).type == "hidden" ){
				     if ((product_var[eachsku])["attr_value"+drop]!=document.getElementById('attr'+drop).value){matching=false;}
				} else {
				     if ((product_var[eachsku])["attr_value"+drop]!=document.getElementById('attr'+drop).options[document.getElementById('attr'+drop).selectedIndex].value){matching=false;}
				}
			}
			if (matching==true){
                        avail_message = product_var[eachsku].avail_msg;

                      // hide Out of stock messages
                      //WJS - Why? Customer wants out of stock to be shown 
                      //if (avail_message=="Out of stock") { avail_message = "";}
            
            
			if (product_var[eachsku].price_sale!="" && product_var[eachsku].price_sale!="0" && parseInt(product_var[eachsku].price_sale) < parseInt(product_var[eachsku].price_list)){
			
				listprice=OKStrOfPenny(product_var[eachsku].price_list);
				matchsku=true;
				selectedskuprice=OKStrOfPenny(product_var[eachsku].price_sale);
				matchsku=true;				
				document.getElementById("prod_price").innerHTML = "<font class='ListPricewSale'>"+rel_our_pricelab+"$"+listprice+"</font><font class='SalePrice'><br>"+rel_sale_pricelab+"$"+selectedskuprice+"</font><br>"+avail_message; 
			}else{
				selectedskuprice=OKStrOfPenny(product_var[eachsku].price_list);
				matchsku=true;
				document.getElementById("prod_price").innerHTML = "<font class='ListPricewoSale'><br>"+rel_our_pricelab+"$"+selectedskuprice+"</font><br>"+avail_message;
			}
			
			
			return true;
	
			}
			eachsku++;
		}
	}
}//end findprice