/* JAT 11/06/07 - customized this for Erie site which does NOT use product_var */

/*
	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).
	Color dropdown draws out first, then size. (goes in REVERSE order of attribute types as entered for skus)
	Once a color is selected, ONLY sizes available in the selected color will appear in size 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();
product_attributes = attr_values;

//Custom Kid Club Product
var kc_pid = 1000003342;
var custom_color = "Shirt Color";
var custom_size = "Shirt Size - Choose Color First";

/* 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;
}

/*  */
var hasColor = false;
var anyAvail = true;
function draw_sku_option()
{
	//get attributes
	//getAttributes(); //*** jat 11/06/07 - because cavs does not use product_var array, we will use the special attr_values array that is created in cavs_product_include.js which does the same thing (product_attributes is set at the very top of this script)
	
	var dropdownattr1 = "";
	var attrname = "";
	var dropdown_label="";
	//document.write("<TABLE BORDER=0 CELLPADDING=2 CELLSPACING=0>");
	var selectionLabel = "";

	/*** jat 11/6/07 - added stopSelects var in case as a flag in case a product has no attributes to select (ex. basketball) ***/
	var stopSelects = (colors.length > 0 || sizes.length > 0)? false : true;	
	
	// only show the 'please select.. ' message if there are attributes to select
	if(product_attributes.length>0){
		selectionLabel = "Please select the following options:";
	}
	
	if(!stopSelects){	/*** jat 11/6/07 - only continue if there are sizes/colors/attributes to display in the dropdowns ***/
		document.write("<TR VALIGN=TOP ><TD class=\"ProductAttrlabel\">"+selectionLabel+"</td></tr>");

		for (outer=product_attributes.length-1;outer>-1;outer--)
		{
			attrname = "attr" + (outer+1);
			document.write("<TR VALIGN=TOP ><TD>");
					
			document.write("<select name="+attrname+" id="+attrname+" onchange=\"get_values("+(outer+1)+");findprice();\" class=\"ProductAttr\">");

			if (attr_label[outer]=="Attribute")
			{
				if ( pf_id == kc_pid ) {
                               dropdown_label = custom_color;
                            } else {
                               dropdown_label="Color";
                            }
                            hasColor = true;
			}else
			{
				//dropdown_label=attr_label[outer];
				if(hasColor){
                                   if ( pf_id == kc_pid ) {
                                      dropdown_label = custom_size + '</option>';
                                   } else {
					   dropdown_label = 'Size - Please Choose Color First</option>';
                                   }
				}else{
					dropdown_label = '<option value=\'\' selected>'+attr_label[outer]+'</option>';
				}
			}
			
			document.write('<option value=\'\' selected>'+dropdown_label+'</option>');
			//console.log(hasColor + " : " + dropdown_label);
			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("<div id=single_option"+(outer+1)+"></div>");
			
			document.write("</TD></TR>");
		}
		//* jat - refreshing sku dropdown 
		get_values(product_attributes.length);
		findprice();
              if ( pf_id == kc_pid ) {
                 document.write("<tr><td><input type=hidden name=qty value=1 size=1></TD></TR>");
              } else {
		   document.write("<tr><td>Qty: <input type=text name=qty value=1 size=1></TD></TR>");
              }
	}else{
		// see if all products are sold out - if so, display sold out message.
		for(var i = 0; i < product_var.length; i++){
			if(product_var[i] != "0"){//not sure what this does, so i'm leaving it and by-passing it in the next if (WCD - 20090320)
				anyAvail = false;
			}
			if((product_var[i].avail != "0")){ //if the product has no attributes but has available product then set it's any avail to true.
				anyAvail = true;
			}
		}
		
		if(!anyAvail){
			document.write("<tr><td>Sorry, this product is sold out.</TD></TR>");
		}else{
			//edited to allow for users to select more than one product - WCD 20090320
		document.write("<tr><td>Qty: <input type=text id=qty name=qty value=1 size=1></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

/* JAT 11/06/07 - added tolowercase() to string comparisons to fix bug */
//get_values receives the attr number of the dropdown that has changed.
var currentDropSelection;	// *** JAT 11/06/07 - moved this var to global so it can be used in the findprice() function ***/
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>0;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;

		//clear out select
		nextdd.options.length = 1;
              if ( pf_id == kc_pid ){
                 nextdd.options[0].innerHTML = custom_size;
              } else {
		   nextdd.options[0].innerHTML = "Size - Please Choose Color First";
              }
		/*** JAT 11/6/07 - added currentDropSelection code from old double dropdown code.  (next 2 lines) ***/
		// get current selection
		currentDropSelection = eval("dd"+ddnum).value;
		
		//only continue populating the next dropdown if current selection is not blank 
		// (ie, user actually selected a specific size, color, etc. and did not select the 'Color' or 'Size' option in the select box)
		if(currentDropSelection != ""){
			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=product_attributes.length;k>i;k--)
	          {
	            //check each dropdown up to one before nextdd
				tempattr = (product_var[atn])["attr_value"+k];
	            tempdd = eval("dd"+k).value;
				
				/*** jat 11/6/07 - added tolowercase ***/
				if (tempattr.toLowerCase() != tempdd.toLowerCase() && tempdd!=""){
		            //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 && 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(attr_label[i-1],attr_label[i-1],false);
				if(hasColor){
					tempopt = new Option(attr_label[i-1],"Please Choose Color First",false);
				}else{
					tempopt = new Option(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=product_attributes.length;drop>0;drop--)
				{			
					/*** JAT 11/6/07 - added .toUpperCase()  in following if statement***/
					if (((product_var[eachsku])["attr_value"+drop]).toUpperCase()!=(document.getElementById('attr'+drop).options[document.getElementById('attr'+drop).selectedIndex].value).toUpperCase()){matching=false;}
				}
				if (matching==true)
				{
					selectedsku=product_var[eachsku].sku;
					matchsku=true;

					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

/* JAT 11/06/07 - added tolowercase() to string comparisons to fix bug */
function findprice(){	
	if(currentDropSelection != ""){	/*** JAT 10/6/07 - added this line. Checks if we actually need to find a price in case user selects an empty value option ***/
		//if (typeof product_attributes!="undefined" && document.getElementById("prod_price")){
		/*** JAT 11/6/07 - changing document.getElementById('prod_price') to document.getElementById('availability_message') as this is where we will be putting the avail_message instead ***/
		if (typeof product_attributes!="undefined" && document.getElementById("availability_message")){
			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=product_attributes.length;drop>0;drop--)
				{
					//document.getElementById('this').value=document.getElementById('dropsku'+drop).options[document.getElementById('dropsku'+drop).selectedIndex].value;
					/*** jat 10/6/07 - changed next 3 lines to use toLowerCase ***/
					var compare1 = (product_var[eachsku])["attr_value"+drop];
					var compare2 = document.getElementById('attr'+drop).options[document.getElementById('attr'+drop).selectedIndex].value;
					if (compare1.toLowerCase() != compare2.toLowerCase()){matching=false;}
				}
				if (matching==true){
				avail_message = product_var[eachsku].avail_msg;
				if (product_var[eachsku].price_sale!="" && product_var[eachsku].price_sale!="0" && product_var[eachsku].price_sale<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><br>"+avail_message;
				}
				
				/*** JAT 11/6/07 - added call to display_avail() which is defined in cavs_product_include.js. This function displays the 'in stock' message on page ***/
				display_avail(avail_message);
				
				return true;
		
				}
				eachsku++;
			}
		}
	}
}//end findprice