/**
 * @author Daniel Schwerdtner
 * @copyright Fahrenheit e-solutions GmbH & Co. KG, 2007
 * @since 21/01/2008
 * 
 * JavaScript support functions for tx_welkeselector
 */

var http;
var optionCount;
var sortArray;
var optName;

//create xmlhttprequest for ajax
if (window.XMLHttpRequest) 
{
   http = new XMLHttpRequest();
} 
else if (window.ActiveXObject) 
{
   http = new ActiveXObject("Microsoft.XMLHTTP");
}

/**
 * Function queries database for product IDs that equals user's selection
 * @param {Object} paramId
 */
function getProduct(paramId)
{
	var values;
	var optValues = getOptionValues();
	var optValuesNew;
	
	try
	{
		optValuesNew = optValues.replace(/undefiened/gi,"");
	}
	catch (e)
	{
		optValuesNew = '';
	}
	
	values = optValuesNew;
	
	if (values)
	{
		if (http != null) 
		{
			http.open('GET', 'index.php?eID=welke_productfinder&optionValues='+values, true);
			http.onreadystatechange = productToDisplay;
			http.send(null);
		}
	}	
	/*else
	{
		showAll();
	}*/
}

/**
 * Function returns values of all <option>-Tags
 * @return <option> values as comma-seperated string
 */
function getOptionValues()
{
	var optionValues = '';
	optionCount=0;
	for (var j=1; j<4; j++)
	{
		var options;
		options = document.getElementById('select-'+j).getElementsByTagName('option')
		
		for (var i=0; i<options.length; i++)
		{
			if (options[i].selected == true && options[i].value != '0')
			{
				optionValues += j+':'+options[i].value+',';
				optionCount++;
			}
		}
	}
	return optionValues;
}

/**
 * Function evaluates json-array returned by server and displays corresponding products
 * @return nothing
 */
function productToDisplay()
{
	var json_productIds;
	var productIds;
	
	if (http.readyState == 4)
	{
		json_productIds = http.responseText;
		productIds = eval('(' + json_productIds + ')');
		hideProducts();
		showProducts(productIds[0].produid.split(","),'result-');
		optName = 'Grundwerkstoffe';
		
		switch (optionCount) 
		{
			case 1:	
				showProducts(productIds[2].cat1.split(","),'select-2');
				enableSelect(2);
				disableSelect(3);
				optName = 'Anspruch an neue Oberfläche';
			break;
			case 2:	
				showProducts(productIds[3].cat2.split(","),'select-3');
				//disableSelect(2);
				enableSelect(3);
				optName = 'Anspruch an neue Oberfläche';
			break;
			case 3:	
				//disableSelect(3);
			break;						
		}
	}
}

/**
 * Functions hides all products that do not fit user's selection
 */
function hideProducts()
{
	var resultLi = document.getElementById('tx-welkeproductfinder-pi1-result-list').getElementsByTagName('li');
	for (var l=0; l<resultLi.length; l++)
	{
		resultLi[l].style.display = 'none';
	}

	document.getElementById('tx-welkeproductfinder-pi1-result').style.display = 'none';

}

function removeOptions(type)
{
	//remove options from selectors
	var opt = document.getElementById(type).getElementsByTagName('option');
	
	if (type != 'result-')
	{
		document.getElementById(type).options[0].selected = true;
		for (var z=1; z<document.getElementById(type).options.length; z++)
		{
			//alert('removing: '+document.getElementById(type).options[z].value);
			document.getElementById(type).options[z] = null;
		}
	}
}

/**
 * Function sows all products that fit user's selection
 * @param {Object} pId IDs of products
 */
function showProducts(pId,type)
{
	sortArray = new Array();
    
    //throw emos for user's selection
    if (type == 'result-') 
    {
        var variable = new Array();
        for (var t = 1; t < 4; t++) 
        {
            variable[t] = 'n.a.';
            for (var s = 1; s < document.getElementById('select-'+t).options.length; s++) 
            {
                if (document.getElementById('select-'+t).options[s].selected == true) 
                {
                    variable[t] = document.getElementById('select-'+t).options[s].text;
                }
            }
        }
        
        emosLeadEvent('OK_Suche', variable['1'], variable['2'], variable['3'], 'n.a.', pId.length, '0');
    }
    
	//show result an corr. options
	if (pId.length >= 1)
	{
/*		pId.sort();*/
		for (var j=0; j<pId.length; j++) 
		{
			if(type=='result-')
			{
				/*var tagArray = getElementsByClassName(type+pId[j]);
				for (var k=0; k<tagArray.length; k++)
				{
					if(type=='result-')
					{
						tagArray[k].style.display = 'block';
					}
				}*/
                
              /*  if (document.getElementById('tx-welkeproductfinder-pi1-result-list').childNodes.length > 0) 
                {
                    for (var o = 0; o < document.getElementById('tx-welkeproductfinder-pi1-result-list').childNodes.length; o++) 
                    {
                        document.getElementById('tx-welkeproductfinder-pi1-result-list').removeChild(o);
                    }
                }*/
                
                var tagArray = pId[j].split(":");
                var newLi = document.createElement("li");
                var newA = document.createElement("a");
                var newAEmos = document.createAttribute("onclick");
                newAEmos.nodeValue = 'emosLeadEvent("OK_Ergebnis", "'+variable['1']+'", "'+variable['2']+'", "'+variable['3']+'", "'+tagArray[1]+'","0", "1");';
                newA.setAttributeNode(newAEmos);
                /* href creation for der-oberflaechenspezialist.de
                 */
                var newAHref = document.createAttribute("href");
                newAHref.nodeValue = 'index.php?id='+tagArray[2];//+':'+tagArray[3]; for der-oberflaechenspezialist.de
                newA.setAttributeNode(newAHref);
                var newAText = document.createTextNode(tagArray[1]);
                newA.appendChild(newAText);
                newLi.appendChild(newA);
                document.getElementById('tx-welkeproductfinder-pi1-result-list').appendChild(newLi);
			}
			else
			{
				var optArray = pId[j].split(":");
				sortArray.push(optArray.reverse().join(":"));
			}	
		}
		
		if (type!='result-')
		{
			sortArray.sort();
			sortArray.shift();
			
			switch (type)
			{
				case 'select-2': optName = 'Grundwerkstoff';
				break;
				
				case 'select-3': optName = 'Anspruch an neue Oberflaeche';
				break;
			}
			
			if (document.getElementById(type).options.length > 1)
			{
				for (x=1;x<document.getElementById(type).options.length;x++)
				{
					document.getElementById(type).options[x] = null;
				}
			}
			
			for (y=0; y<sortArray.length; y++)
			{
				
				var optArray = sortArray[y].split(":");
				var newOption = new Option(optArray[0], optArray[1], false, false);
//				var newOption = '<option value="'+optArray[1]+'" onclick="emosTargetEvent("'+optName+'", "'+optArray[0]+'", "0")">'+optArray[0]+'</option>';
				var newOption = document.createElement("option");
				var optAttribute = document.createAttribute("value");
				optAttribute.nodeValue = optArray[1];
				/*var emos = document.createAttribute("onclick")
				emos.nodeValue = 'emosTargetEvent("'+optName+'", "'+optArray[0]+'", "0");'*/
				newOption.setAttributeNode(optAttribute);
				//newOption.setAttributeNode(emos);
				optText = document.createTextNode(optArray[0]);
				newOption.appendChild(optText);
//				new Option(optArray[0], optArray[1], false, false);				
				document.getElementById(type).options[y + 1] = null;
//				document.getElementById(type).options[y + 1] = newOption;
				document.getElementById(type).appendChild(newOption);
//				document.getElementById(type).write = newOption;
			}
		}
	}
	
	document.getElementById('tx-welkeproductfinder-pi1-result').style.display = 'block';
}

function disableSelect(selNo)
{
	document.getElementById('select-'+selNo).disabled=true;
}

function enableSelect(selNo)
{
	document.getElementById('select-'+selNo).disabled=false;
}

/**
 * Functioon displays whole coTab, in case values is empty
 */
function showAll(idName,elementName)
{
	var showAllOption = document.getElementById(idName).getElementsByTagName(elementName);
	for (var l=0; l<showAllOption.length; l++)
	{
		showAllOption[l].style.visibility = 'visible';
		showAllOption[l].style.position = 'static';		
	}
}

/**
 * Function gets all <tags> with a given className
 * @param {Object} clsName the className
 * @return the <tags> as array
 */
function getElementsByClassName(clsName)
{
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++)
	{
        if(elements[i].className.indexOf(" ") >= 0)
		{
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++)
			{
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

function setForm()
{
	document.getElementById('tx-welkeproductfinder-pi1-result').style.display = 'none';
	var tempSelect = document.getElementById('tx-welkeproductfinder-pi1-form').getElementsByTagName('select');
	for (var y=1;y<tempSelect.length;y++)
	{
		var tdis = y + 1;
		disableSelect(tdis);
	}
}

window.onload = function() 
{
	(document.all && !window.print) ? null : setForm();
};