

var newobject1;
addEvent(window, "load", td_loader);

/**
 * sets up td elements with proper height and width
 */
function td_loader() {
	
	var hdr_height = 0;
	var cols = document.getElementsByClassName('filter_outer');
	
	for( var i = 0; i < cols.length; i++ ) {
		try {
			cols[i].style.width = ((700 )/ cols.length ) -10 + "px";
		} catch(e) {
			cols[i].style.setAttribute('width',((700 )/ cols.length ) -10 + "px");			
		}	
	}
	try {
		$('ProdCat-td').style.width=((700 )/ cols.length ) -10 + "px";
	} catch(e) {
		$('ProdCat-td').style.setAttribute('width',((700 )/ cols.length ) -10 + "px");	
	}
	// first loop resets heights and gets tallest header div 
	for( var i = 0; i < document.getElementsByClassName('techdocs-nodeHdr').length; i++ ) {
		document.getElementsByClassName('techdocs-nodeHdr')[i].style.height =  "" ;
		hdr_height = Math.max(hdr_height,parseInt(document.getElementsByClassName('techdocs-nodeHdr')[i].clientHeight));
	}
	
	//second loop sets other header divs to match tallest header div
	for( var i = 0; i < document.getElementsByClassName('techdocs-nodeHdr').length; i++ ) {
		document.getElementsByClassName('techdocs-nodeHdr')[i].style.height =  parseInt(hdr_height - 9 )+"px" ;
		if(i < document.getElementsByClassName('filter').length) {
			document.getElementsByClassName('filter')[i].style.height = parseInt(146) - (parseInt(hdr_height - 26 )) + "px"
		}
	}

	$('ProdCat-div').style.height = parseInt(146) - (parseInt(hdr_height - 28 )) + "px";

	if ($('techdocs-td') && cols.length == 1 && $('filter_outer_1')) {
		try {
		$('ProdCat-td').style.width="346px;"
		$('filter_outer_1').style.width="346px;"
		} catch(e) {
			$('filter_outer_1').style.setAttribute('width',"346px");
			$('ProdCat-td').style.setAttribute('width',"346px");
		}
		$('techdocs-td').style.display="none"; 
		$('techdocs-default').style.display="none";				
	}else if($('techdocs-td') && cols.length > 0) {
		$('techdocs-td').style.display="none"; 
		$('techdocs-default').style.display="none";
		$('ProdCat-td').style.width="170px";
	}else if ($('techdocs-td')) {
		$('ProdCat-td').style.width="170px";
	}
	
	if($('filter_outer_prod')) {
		try {			
			$('techdocs-default').style.display="none";	
		}catch(e){}
		try {			
			$('techdocs-td').style.display="none";	
		}catch(e){}
		try {
			$('ProdCat-td').style.width="346px;"
			$('filter_outer_prod').style.width="346px;"
		} catch(e) {			
			$('filter_outer_prod').style.setAttribute('width',"346px");
			$('ProdCat-td').style.setAttribute('width',"346px");
		}	
	}
}

/**
 * Make the passed object active, calls removeActive to make sibling objects inactive.
 * @param {Object} el New active object
 * @see removeActive
 */
function changeActive(el) {
	var actives;
	actives = document.getElementsByClassName('techdocs-node-act', el.parentNode);
	removeActive(actives);
	el.className = 'techdocs-node-act';
}

/**
 * Make the passed Array inactive, called by changeActive.
 * @param {Array} actives Old active objects
 * @see changeActive
 */
function removeActive(actives) {
	var active;
	for (var i=0;i<actives.length;i++){
		active = 	actives[i].className = 'techdocs-node';
	}		
}

/**
 * Make the passed object active. Sets the hidden form value for the categoryNumber.
 * Uses changeActive to make object active. Needs Prototypes Ajax.Request object
 * @param {Object} el New active object
 * @param {String} categoryNumber ID for new active Element
 * @see changeActive
 * @see	addFilterInput
 * @see	addFilterColumn
 * @see Ajax.Request
 */
function makeActiveCategory(el, categoryNumber) {

    var hdr_height = 0;
	changeActive(el);
	$('categoryNumber_td').value = categoryNumber;
	$('techdocs-go').style.display= "";
	url = "/" + directory + "/technicaldocumentsvalues.htm?sectionNumber="+$F('sectionNumber_td')+"&categoryNumber="+categoryNumber;
	url2 = "/"+ directory +"/technicaldocumentsresults.htm?sectionNumber="+$F('sectionNumber_td')+"&categoryNumber="+categoryNumber+"&contentNumber=301&nodeNumber=3";
	
    new Ajax.Request(
		url, 
		{ method:'get',
			onSuccess: function(transport){
				try {
				resp =  transport.responseText.replace(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/, " ");
				eval(" newobject1 = {" +resp + "}"); //put it in object
				} catch(e) {}			
				//remove prodlist column, if there
				if ($('filter_outer_prod')) {
					while ($('filter_outer_prod').childNodes[0]) {
						while ($('filter_outer_prod').childNodes[0].childNodes[0]) { 
							$('filter_outer_prod').childNodes[0].removeChild($('filter_outer_prod').childNodes[0].childNodes[0]);
						}
						$('filter_outer_prod').removeChild($('filter_outer_prod').childNodes[0]);
					}
					$('filter_outer_prod').parentNode.removeChild($('filter_outer_prod'));
					$('prodNum').value = "";
				}
				NumberOfFilters = document.getElementsByClassName('filter').length;
				for(var i = 1; i< NumberOfFilters; i++) {
					removeActive(document.getElementsByClassName('techdocs-node-act',$('filter_td_'+i)));
				}
				try{
					filters = newobject1.technicalDocuments.attributes.length ; // set number of filters
				}catch(e) {
					filters = 0;
					makeProdList();
				}
				for(var i = 1; i <= NumberOfFilters; i++) {
					removeNode($('filter_outer_'+i));
				}
				for(var iter = 1; iter < filters;iter++) { //add in the new filters
					addFilterInput(iter,"ALL");						
					addFilterColumn(iter,'ALL', ( (532 )/ (parseInt(filters) -1)) -10,newobject1.technicalDocuments.headers[iter].header );		
				}
			
				td_loader();
				if(newobject1.technicalDocuments.productcount != 0) {
					$('techdocs-count').innerHTML = newobject1.technicalDocuments.productcount+ " products products match your selected attributes";
				} else {
					$('techdocs-count').innerHTML = "";
				}
				$('techdocs-go').href= url2;
			}
		}
	)
}

/**
 * Make the passed object active. Sets the hidden form value for the filter.
 * Uses changeActive to make object active. Needs Prototypes Ajax.Request object
 * @param {Object} el New active object
 * @param {String} filterID ID for new active Element
 * @see changeActive
 * @see	addFilterInput
 * @see	addFilterColumn
 * @see Ajax.Request
 */
function makeActiveFilter(el, filterID) {
	var hdr_height = 0;
	var filterNo;
	var NumberOfFilters;
	var activeFilters = new Array(); // array to hold selected values
	filterNo = el.parentNode.getAttribute('id').substring(10); //current filter
	NumberOfFilters = document.getElementsByClassName('filter').length; //total number of filters
	$('filter_value_'+filterNo).value = filterID;
	urlExt = "sectionNumber="+$F('sectionNumber_td')+"&categoryNumber="+$F('categoryNumber_td');
	url = "/"+directory+"/technicaldocumentsvalues.htm?";
	url2 = "/"+directory+"/technicaldocumentsresults.htm?";
	for(var i = 1 ; i<= filterNo; i++) { // add selected values to URL
		urlExt+="&filter_"+i+"="+$F('filter_value_'+i);
	}
	for(var j = parseInt(filterNo)+1 ; j <= NumberOfFilters;j++) { //set the rest of the filters to ALL
		urlExt+="&filter_"+j+"=ALL";
		$('filter_value_'+j).value = "ALL";
	}
	url += urlExt; //url to AJAX request
	url2 += urlExt+"&contentNumber=301&nodeNumber=3"; //url to next page
		
	new Ajax.Request(
	url, 
	{ method:'get',
		onSuccess: function(transport){
			resp =  transport.responseText.replace(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/, " ");
			eval(" newobject1 = {" +resp + "}"); //put it in object
			$('techdocs-go').href= url2;
			if(newobject1.technicalDocuments.productcount != 0) {
				$('techdocs-count').innerHTML = newobject1.technicalDocuments.productcount+ " products products match your selected attributes";
			} else {
				$('techdocs-count').innerHTML = "";
			}
			for(var i = 1; i<= NumberOfFilters ; i++) {
				removeActive(document.getElementsByClassName('techdocs-node-act',$('filter_td_'+i)));
				activeFilters[i] = $('filter_value_'+i).value;
			}
			try{
				filters = newobject1.technicalDocuments.attributes.length ; // set number of filters
			}catch(e) {
				filters = 0;
				makeProdList();
			}
			for(var iter = 1; iter <= NumberOfFilters; iter++) {	
				removeNode($('filter_outer_'+iter));		
			}
			
			for(var iter = 1 ; iter < filters;iter++) {
				addFilterInput(iter,activeFilters[iter]);
				addFilterColumn(iter,activeFilters[iter], ((532 )/ (parseInt(filters) -1)) -10 ,newobject1.technicalDocuments.headers[iter].header);
			}
			td_loader();			
		}
	}
	);
	changeActive(el);
		
}

/**
 * Creates the hidden form input for new filter
 * @param {Number} i index of filter being added
 * @param {String} val Value of selected active object
 */
function addFilterInput(i,val){	
	if (val == null ){val = 'ALL';}
	var addAnother;
	addAnother = createNewElement('<input id="filter_value_'+i+'" name="filter_value_'+i+'" value="'+val+'" type="hidden" />');	
	$('techdocs_inputs').appendChild(addAnother);
}


/**
 * Creates column of values for new filter.  Uses addFilterDiv to create options
 * @param {Number} i index of filter being added
 * @param {String} val Value of selected active object
 * @param {Number} w width of the column
 * @param {String} headName name of column
 * @see	addFilterDiv
 */
function addFilterColumn(i,val, w, headName) {
	if (val == null ){val = 'ALL';}
	var addAnother;
	var addSpace;
	var addimg;
	addOuterDiv = createNewElement('<td  style="border-left:10px solid #FFF;height:172px;width:'+w+'px;" id="filter_outer_'+i+'" class="filter_outer" ></td>');
	addAnother = createNewElement('<div class="techdocs-nodeHdr" ></div>');
	addAnother.innerHTML = headName;
	addOuterDiv.appendChild(addAnother);
	addSpace = createNewElement('<div style="background-color:#FFF;"></div>');
	addimg = createNewElement('<img src="/common/images/spacer.gif" width="1" height="2" alt="" border="0" />'); 
	addSpace.appendChild(addimg);
	addOuterDiv.appendChild(addSpace);
	addAnother = createNewElement('<div class="scroll" id="scroll_'+i+'" ></div>');
	addOuterDiv.appendChild(addAnother);
	addAnother = createNewElement('<div id="filter_td_'+i+'" class="filter" ></div>');
	for(var iter = 0; iter < newobject1.technicalDocuments.attributes[i-1].attributeList.length ; iter++){
		newDiv = addFilterDiv(newobject1.technicalDocuments.attributes[i-1].attributeList[iter],val, w)		
		addAnother.appendChild(newDiv);		
	}
	addOuterDiv.appendChild(addAnother);
	$('techdocs-tr').insertBefore(addOuterDiv,$('clearDiv'));
}

/**
 * Creates new div object with class and onclick.  If val == i.value, div is active
 * @param {Object} i filter value object from JSON that is being added
 * @param {String} val Value of selected active object
 * @return {Object} New div object
 */
function addFilterDiv(i,val,w) {
	var addAnother1;
	if (val == null ){val = 'ALL';}
	if(i.value == val) {
		addAnother1 = createNewElement('<div class="techdocs-node-act" style="width:100%;" onclick="makeActiveFilter(this, '+"'"+i.value+"'"+')"></div>')
	}else {
		addAnother1 = createNewElement('<div class="techdocs-node" style="width:100%;" onclick="makeActiveFilter(this, '+"'"+i.value+"'"+')"></div>')		
	}
	addAnother1.innerHTML = i.name;
	return addAnother1;		
}

/**
 * Sets up and makes the product lists
 */
function makeProdList() {
	var prods = newobject1.technicalDocuments.prodList;
	addProdColumn(prods);
}


/**
 * Creates new div object with class and onclick. 
 * @param {String} val value of new element
 * @param {String} desc description of new element
 * @return {Object} New div object
 */
function addProdDiv(val,desc) {
	var addAnother1;
	addAnother1 = createNewElement('<div class="techdocs-node" style="width:100%;" onclick="makeActiveProd(this, '+"'"+val+"'"+')"></div>');
	addAnother1.innerHTML = desc;
	return addAnother1;	
}

/**
 * Creates the columns to hold product divs
 * @param {Object} prods object containing product names and values
 */
function addProdColumn(prods) {
	var addAnother;
	var addSpace;
	var addimg;
	var w = 346;

	addOuterDiv = createNewElement('<td  style="border-left:10px solid #FFF;height:172px;width:'+w+'px;" id="filter_outer_prod"></td>');
	addAnother = createNewElement('<div class="techdocs-nodeHdr" ></div>')
	addAnother.appendChild(document.createTextNode("Models"));
	addOuterDiv.appendChild(addAnother);	
	addSpace = createNewElement('<div style="background-color:#FFF;"></div>');	
	addimg = createNewElement('<img src="/common/images/spacer.gif" width="1" height="2" alt="" border="0" />');
	addSpace.appendChild(addimg);
	addOuterDiv.appendChild(addSpace);
	addAnother = createNewElement('<div class="scroll" id="scroll_prod" ></div>');	
	addOuterDiv.appendChild(addAnother);
	addAnother = createNewElement('<div id="filter_td_prod" class="filter" ></div>');
	for(var iter = 0; iter < prods.length-1 ; iter++){
		newDiv = addProdDiv(prods[iter].prodNum,prods[iter].prodName)
		addAnother.appendChild(newDiv);
	}
	addOuterDiv.appendChild(addAnother);
	$('techdocs-tr').insertBefore(addOuterDiv,$('clearDiv'));
	var hdr_height = parseInt(document.getElementsByClassName('techdocs-nodeHdr')[document.getElementsByClassName('techdocs-nodeHdr').length-1].clientHeight);
	document.getElementsByClassName('techdocs-nodeHdr')[0].style.height =  parseInt(hdr_height - 8 )+"px" ;
	document.getElementsByClassName('techdocs-nodeHdr')[1].style.height =  parseInt(hdr_height - 8 )+"px" ;
	
	
	document.getElementById('ProdCat-div').style.height =  parseInt(146) - (parseInt(hdr_height - 24 )) + "px"
	
}

/**
 * Called when product is selected.  Makes selected product active
 * @param {Object} el new active object
 * @param {String} prodNum number of new active product
 */
function makeActiveProd(el, prodNum) {
	changeActive(el);
	$('prodNum').value = prodNum;
	
	urlExt = "sectionNumber="+$F('sectionNumber_td')+"&categoryNumber="+$F('categoryNumber_td')+'&productNumber='+$F('prodNum');
	url2 = "/"+directory+"/technicaldocumentsresults.htm?";
	$('techdocs-go').href= url2+urlExt+"&contentNumber=301&nodeNumber=3";
}

/**
 * Recursively deletes node and it's children
 * @param {Object} el_node node to be deleted
 */
function removeNode(el_node) {
	if(el_node.childNodes[0]) {
		while(el_node.childNodes[0])removeNode(el_node.childNodes[0])
	}
	el_node.parentNode.removeChild(el_node); 
}

/**
 * Creates a new element.  Tries IE method, then tries other method.
 * Node must be properly XML formatted with closing /
 * Javascript 1.2+ needed for regex
 * @param {String} elstring HTML of new node
 */
function createNewElement(elString) {
	var opentag, createdElement, el_attributes, tag_name, el_tag;
	try {
		createdElement = document.createElement(elString);
	}
	catch(e) {
		//match open tag, close tag
		if(el_tag = elString.match(/<([a-zA-Z]*)([^>]*)(>[^<]*<\/\1*>|\/>)/)) { 			
			tag_name = el_tag[1];
			el_attributes = el_tag[2].match(/[a-zA-Z]*=(\"[^\"]*\")|(\'[^\']*\')/g);
			createdElement = document.createElement(tag_name);			
			if(el_attributes) { 
				// loop through attributes
				for(var i = 0; i < el_attributes.length; i++) {
					try { 
						// attribute name is the part before the =
						// attribute properties come from the part after the =, strip out quotes
						createdElement.setAttribute(el_attributes[i].split("=")[0], el_attributes[i].split("=")[1].match(/(\'|\")(.*)\1/)[2] )
					}catch(e) {}
				}
			}
		}
		else {createdElement = null; }
	}
	return createdElement;
}

function debugOut(i) {	
	try{console.log(i);} catch(e){alert(i)}
}
