var callbackPIDs = new Array();
var callbackFunctions = new Array();

var sFieldsToCheck = "";

function addFieldToCheck(sField) {
    if (sFieldsToCheck=="") {
        sFieldsToCheck = sField;
    }
    else
    {
        sFieldsToCheck += "," + sField;
    }
}

var sNoAttributeProducts = "";

function addNoAttributeProducts(ProductID) {

    if((","+sNoAttributeProducts+",").indexOf(','+ProductID+',')==-1){
	    if(sNoAttributeProducts!="") {
		    sNoAttributeProducts += ",";	
	    }
	    sNoAttributeProducts += ProductID;
	}
}

function loadComboBox(nID, callbackFunction) {

    callbackPIDs[callbackPIDs.length] = nID;
    callbackFunctions[callbackFunctions.length] = callbackFunction;

	var objSelect = new Array();							// attribute combo-boxes
	var arrAttributes = eval("productAttributes" + nID);	// array of attributes from JSON

    // field to contain final selection
    objInput = document.createElement("INPUT");
    objInput.type = "hidden";
    objInput.id = nID;
    
    if (arrAttributes.length-1==1) {                             

        objInput.value = nID.substring(nID.indexOf("p")+1);
    }
    else {
    
        objInput.value = "0";

        // create combo box for items with more than 1 selection
    
        for(i=1;i<arrAttributes[0].length-1;i++) {

			var InsertedAttributes = new Array()				// keep track of inserted attributes to prevent same
																		        // value from populated twice.
	        // Create SELECT element
	        objSelect[i] = document.createElement("SELECT");	
	        objSelect[i].id = nID + "Level_" + i;
    		
	        // Create OPTION element for the attribute header "- COLOR -", ...
	        var opt = document.createElement("OPTION");
			var szAttributeKey = "";
			var optKeyParts = arrAttributes[0][i].split(":");

			if(ArrAttributeKeys.length>0 && ArrAttributeValues.length>0)
			{
				for(var k=0;k<ArrAttributeKeys.length;k++)
				{
					if(ArrAttributeKeys[k][0]==optKeyParts[1])
					{
						szAttributeKey = "- Select " + ArrAttributeKeys[k][1] + " - ";
					}
				}
			}
			else {
				szAttributeKey = optKeyParts[0];
			}

			opt.text = szAttributeKey;
	        opt.value = "0";
	        objSelect[i].options.add(opt);

	        // attach event handler to update subsequent combo-boxes when a combo-box value is changed
	        if (!document.addEventListener){
		        // for IE
		        objSelect[i].attachEvent('onchange', ChangedSelection); 
	        } else{
		        // for Mozilla
		        objSelect[i].addEventListener("change", ChangedSelection, false);
	        }

	        // disable combo-boxes for 2nd and subsequent combo boxes
	        if(i>1){
		        objSelect[i].disabled=true;
	        }
        }

	    // populate combo boxes
	    if (arrAttributes.length==2)
	    {
		    // no records
		    if (arrAttributes[1][1]==0)
		    {
			    document.getElementById("attributeSelectorSpan_" + nID).innerHTML = "<font color='#ff0000'>&nbsp;" + OutOfStock + "</span>";
		    }
		    else {
			    document.getElementById("attributeSelectorSpan_" + nID).innerHTML = "&nbsp;";
		    }
		    return false;
	    }

	    for(j=1;j<arrAttributes.length;j++) {
			
			var opt = arrAttributes[j][1].split(":");
			for (k=0;k<ArrAttributeValues.length;k++)
			{
				if(ArrAttributeValues[k][0]==opt[1]) {
						arrAttributes[j][1]=ArrAttributeValues[k][1];
				}
			}
		}

	    for(j=1;j<arrAttributes.length;j++) {

		    var bFound=false;

		    // check if attribute has been added before
		    for(k=0;k<InsertedAttributes.length;k++) {
			    if(InsertedAttributes[k]==arrAttributes[j][1]) {
				    bFound=true;
			    }
		    }

		    if(!bFound) {
			    // create OPTION element for the attribute value
			    var opt = document.createElement("OPTION");
			    opt.text = arrAttributes[j][1];
			    opt.value = arrAttributes[j][0];
			    objSelect[1].options.add(opt);

			    // add to list of added attributes to prevent duplicate values
			    InsertedAttributes[InsertedAttributes.length]=opt.text;
		    }
	    }

	    // render the SELECT element on the page

	    for(i=1;i<arrAttributes[0].length-1;i++) {
		    document.getElementById("attributeSelectorSpan_" + nID).appendChild(objSelect[i]);
	    }

	    var productMessage = document.createElement("SPAN");
	    productMessage.id = nID + "message";
	    document.getElementById("attributeSelectorSpan_" + nID).appendChild(productMessage);

	    // if the first combo box only have 1 value, select it and trigger its event.
	    if(objSelect[1]!=null) {
		    if (objSelect[1].options.length == 2)
		    {
			    objSelect[1].selectedIndex = 1;
			    activateNextComboBox(objSelect[1]);
		    }
	    }
	}
	
    document.getElementById("attributeSelectorSpan_" + nID).appendChild(objInput);
    addFieldToCheck(objInput.id);
}

function ChangedSelection(event) {

	var obj;

	if (!document.addEventListener){
		obj=event.srcElement;
	}
	else {
		obj=event.target;
	}

	activateNextComboBox (obj);
}

function activateNextComboBox (obj) {

	szControlID = obj.id.substring(0,obj.id.indexOf('_')+1);
	
	document.getElementById(szControlID.replace("Level_","")).value=0;
	document.getElementById(szControlID.replace("Level_","")+"message").innerHTML = "";

	nCurrentLevel=parseInt(obj.id.substring(obj.id.indexOf('_')+1),10);

	// disable subsequent combo boxes

	for(i=nCurrentLevel+1;document.getElementById(szControlID+i)!=null;i++){
		document.getElementById(szControlID+i).selectedIndex=0;
		document.getElementById(szControlID+i).disabled=true;
	}

	nNumComboBox = i-1;

	var arrAttributes = eval("productAttributes" + szControlID.substring(0,szControlID.indexOf("Level")));

	if (obj.selectedIndex>0){ 

		if (nCurrentLevel < nNumComboBox)
		{
			// populate next combo box
			objComboBox = document.getElementById(szControlID +(nCurrentLevel+1));

			// remove existing entries
			for (i=objComboBox.length;i>1;i--)
			{
				objComboBox.remove(1);
			}

			// insert related entries
			var InsertedAttributes = new Array();

			for (i=1;i<arrAttributes.length;i++)
			{
				bMatch=true;
				for(j=1;j<nCurrentLevel+1;j++) {					
					cmbNow = document.getElementById(szControlID+j);
					if (cmbNow[cmbNow.selectedIndex].text!=arrAttributes[i][j])
					{
						bMatch=false;
					}
				}

				if(bMatch) {

					// can insert
					var bFound=false;
					for(k=0;k<InsertedAttributes.length;k++) {
						if(InsertedAttributes[k]==arrAttributes[j][i]) {
							bFound=true;
						}
					}

					if(!bFound) {
						var opt = document.createElement("OPTION");
						opt.text = arrAttributes[i][nCurrentLevel+1];
						opt.value = arrAttributes[i][0];//arrAttributes[i][nCurrentLevel+1];
						objComboBox.options.add(opt);

						InsertedAttributes[InsertedAttributes.length]=opt.text;
					}
				}
			}

			// if only one value, auto select
			objComboBox.disabled=false;
			if (objComboBox.options.length==2)
			{
				objComboBox.selectedIndex=1;
				activateNextComboBox(objComboBox);
			}
		}
		else {
			// child product selected;
			checkSelectedProduct(szControlID);
		}
	}
}

function checkSelectedProduct(szControlID) {

    // arrAttributes = Color, Capacity, ...
    
	var arrAttributes = eval("productAttributes" + szControlID.substring(0,szControlID.indexOf("Level")));
//    alert (arrAttributes);
	for (i=1;i<arrAttributes.length;i++)
	{
		var bMatch = true;
		
		// loop through all the attributes of the current product to see if all of them matched.
				
		for(j=1;j<arrAttributes[i].length-1;j++) {
		    
            if (document.getElementById(szControlID+j)[document.getElementById(szControlID+j).selectedIndex].text
                != arrAttributes[i][j])
			{
				bMatch = false;
			}		
		}
				
	    if(bMatch) {

		    // check stock level 

		    nStockLevel = arrAttributes[i][arrAttributes[i].length-1];
		    var MessageSpan = document.getElementById(szControlID.replace("Level_","") + "message")

		    if (nStockLevel<=0)
		    {
			    // no more stocks
			    MessageSpan.innerHTML = "<font color='#ff0000'>&nbsp;This product is out of stock.</span>";
			    document.getElementById(szControlID.replace("Level_","")).value = 0;
		    }
		    else {	
			
			    // still got stocks
			    MessageSpan.innerHTML = "";
			    document.getElementById(szControlID.replace("Level_","")).value = arrAttributes[i][0];
				
			    // callback function
                for(j=0;j<callbackPIDs.length;j++){
                
                    if (callbackPIDs[j] == szControlID.substring(0,szControlID.indexOf("Level"))) {
						if(callbackFunctions[j]!="") {
							eval(callbackFunctions[j]+"("+arrAttributes[i][0]+")");
						}
						return
			        }
			    }
		    }
		}
	}
}
