/**requirements for this function to work
  * form name is guide
  
  * hidden variable for table name is TableName
  
  * Cascade called from
  		each element
		reset button
		
  * each criteria element must have a unique id
  
  * the text describing the element should have the same name as the element prefixed by txt_
  
  * need to add <p id='prodcount'></p>  to top of page for dynamic product count
  		


**/

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


var xmlFormMap
var OpSys=new Array(2); //get operating system OpSys(0) and version OpSys(1)

//the function is the dollar sign function which is a shortcut method of calling getElementbyID
function $() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    if (arguments.length == 1)
      return element;
    elements.push(element);
  }
  return elements;
}




function getPosition(element) {
    //This function finds the location of an html element
	//The counters for the total offset values.
	var left = 0;
	var top = 0;
	//Loop while this element has a parent.
	while (element.offsetParent) { 
	//Sum the current offsets with the total.

	left += element.offsetLeft; 
	top += element.offsetTop; 
	//Switch position to this element's parent.

	element = element.offsetParent;
	}
	//Do a final increment in case there was no parent or if //the last parent has an offset.
	left += element.offsetLeft;
	top += element.offsetTop;
	//Return the values as x,y.
	return {x:left, y:top};

}//function getPosition


function writeWin(s){
//this function writes a new window, used for debug purposes. 
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write(s);
newdocument.close();

}

function SaveSelected(){
//this function will save in a hidden variable the selected option
// this is needed because after submitting to the results page and pressing the back button, the selected option changes because they are dynamic. 
for(i=0; i<document.guide.elements.length; i++){
    sType = document.guide.elements[i].type;
	if(sType=="select-one"){
		sId = document.guide.elements[i].id ;
		document.guide[sId + "_noquery"].value=document.guide.elements[i].value;
	}//if(sType=="select-o
}//for(i=0; i<

}



//================================================
//			GetXmlHttpObject()
//  This function retrieves XmlHttpObject 
//================================================
function GetXmlHttpObject()
{
//this function retrieves an XmlHttpObject
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}
//======================================================
//			End GetXmlHttpObject()
//======================================================

//========================================================
//   ClearOptions
//		Clears a select option list
//========================================================
	function ClearOptions(id){
	  var oSel = document.getElementById(id);
	  while (oSel.length > 0)
	  {
	    oSel.remove(oSel.length - 1);
	  }//while (oSel.lengt
	}//function ClearOptions
	

//========================================================
//   AddOption
//		Adds an option to a Select list
//========================================================	
	function AddOption(id,t,v) {    
    
	   var option = document.createElement("option"); 
	   var oSelect = document.getElementById(id);  
	   option.text = t   
	   option.value = v;   
	   try {   
	       oSelect.add(option, null); //Standard   
	   }catch(error) {   
	       oSelect.add(option); // IE only   
	   }   

	} //function AddOptio

function GetMS(){
//returns milliseconds since 1970
 var t= new Date()
 return t.getTime()
}//function GetMs(){

function xCascadexx(obj){
document.body.style.cursor = "wait";

setTimeout ( "Cascade(this)", 20 );

}
//======================================================
//			ShowProgInd()
//			shows the progress indicator
//
//======================================================
function ShowProgInd(obj){
 var pos 
 if (obj==null){
	 $("progress").style.left = "40%";
  	 $("progress").style.top = "40%";
 }
 else{
 	 pos= getPosition($(obj))
	 $("progress").style.left = pos.x-50;
  	 $("progress").style.top = pos.y-50;
 }//if (obj=null)


  $("progress").style.visibility = "visible";
 }//function ShowProgInd(


//======================================================
//			RemoveProgInd()
//			removes the progress indicator
//
//======================================================
  function RemoveProgInd(){

      $("progress").style.visibility = "hidden";
  } //function RemoveProgInd

//======================================================
//			Load Function
//
//======================================================
window.onload=function(){
OpSys=getOS()
RemoveProgInd();
Cascade(null);

}

//================================================
//			Cascade()
//  This function builds the sql query and the xml map
//================================================
function Cascade(obj){
var s=""
var sField
var sFieldName
var sSQL = ""
var sSQL_template = ""
var value, params
var xmlFormMap = ""
var sType, sID
var sTableName = document.guide.TableName.value
var prodcount = ""
var j,k,t1
var sLastField = ""
var selCnt = 0 // count the number of selection boxes
var oSelect

//Exit if WinNT
if(OpSys[1] == 'nt4'){
	return;
}	

//t1=GetMS();
ShowProgInd(obj);

xmlFormMap = xmlFormMap + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n";
xmlFormMap = xmlFormMap + "<form>\r\n<prodcount></prodcount>\r\n";
xmlFormMap = xmlFormMap + "<tablename>" + sTableName + "</tablename>\r\n";
for(i=0; i<document.guide.elements.length; i++)
{
	sFieldName = document.guide.elements[i].name ;
	sId = document.guide.elements[i].id ;
	sField = sFieldName.toLowerCase();
	sField = sField.trim();
	sType = document.guide.elements[i].type;
	sType = sType.toLowerCase();
	
	if(sType=="select-one"){ //if the element is selection -option we need to get the value differently
	   //Because the options in the select boxes are dynamic there is a problem when the back button is pressed after submitting to the results page
	   // To work around this, on submit we store the slected value in a hidden variable.  If this value is present it means the back button was pressed
	    
		selCnt++; //keep track of the number of selection boxes
		s= document.guide[sId + "_noquery"].value;
	    if(s==""){
			sValue = document.guide.elements[i].options[document.guide.elements[i].selectedIndex].value;
			}
		else{// back button must have beeen pressed
			sValue = s;
			document.guide[sId + "_noquery"].value = ""; //clear it
		
			if(typeof sgReload =='function'){
				sgReload(); 
			}
		   
		}	//if(s==""){

		
	}
	else{
		sValue = document.guide.elements[i].value;
	}	
	sValue_L  =sValue.toLowerCase();

     
	 if ((sType == 'radio' || sType =='checkbox' || sType == 'select-one') && sValue_L.match("dc")== null  && sField.indexOf('_noquery')==-1 ){	
	    if (sField !=sLastField && sLastField !=""){
			xmlFormMap = xmlFormMap + "</queryitem>\r\n";
		}//if (sField !=sLastField && slastField !="
		
		if (sField !=sLastField){
			xmlFormMap = xmlFormMap + "<queryitem>\r\n";
			xmlFormMap = xmlFormMap + "\t<queryname>" + sFieldName + "</queryname>\r\n";
			xmlFormMap = xmlFormMap + "\t<querytype>" + sType + "</querytype>\r\n";
		}//if (sField !=sLastField){


		//xmlFormMap = xmlFormMap + "\t<type>" + sType + "</type>\r\n";
		if (sType=='select-one'){
			xmlFormMap = xmlFormMap + "\t<id>" + sId + "</id>\r\n";
			for(k=0;k<selValue[selCnt].length; k++){
				xmlFormMap = xmlFormMap + "\t<querychoice>\r\n";
				xmlFormMap = xmlFormMap + "\t\t<value>" + selValue[selCnt][k] + "</value>\r\n";
				xmlFormMap = xmlFormMap + "\t\t<text>" + selText[selCnt][k] + "</text>\r\n";
				if (sValue==selValue[selCnt][k]){
					xmlFormMap = xmlFormMap + "\t\t<selected>yes</selected>\r\n";	
				}
				else{
					xmlFormMap = xmlFormMap + "\t\t<selected>no</selected>\r\n";	
				}
				xmlFormMap = xmlFormMap + "\t\t<state>off</state>\r\n";  //default before passing to asp
				xmlFormMap = xmlFormMap + "\t</querychoice>\r\n";
			}//for(k=0;k<
		}//if (sType=='
		else{ //must be a check box or radio button
			xmlFormMap = xmlFormMap + "\t<querychoice>\r\n";
			xmlFormMap = xmlFormMap + "\t\t<id>" + sId + "</id>\r\n";
			xmlFormMap = xmlFormMap + "\t\t<value>" + sValue + "</value>\r\n";
		 	if (document.guide.elements[i].checked == true || sType == 'select-one' && sValue !='' ){
				xmlFormMap = xmlFormMap + "\t\t<selected>yes</selected>\r\n";	
				}
			else{
				xmlFormMap = xmlFormMap + "\t\t<selected>no</selected>\r\n";
		  	}//if (document.guides.elements[i].checked 
			xmlFormMap = xmlFormMap + "\t\t<state>off</state>\r\n";  //default before passing to asp
			xmlFormMap = xmlFormMap + "\t</querychoice>\r\n";
		}//	if (sType=='select-one'){

		sLastField = sField;
	}// if ((sType == 'radio' || sType =='checkbox' || sType == 'selec
}//for(i=0; i<docume

xmlFormMap = xmlFormMap + "</queryitem>\r\n";

xmlFormMap = xmlFormMap + "</form>";



//writeWin(xmlFormMap);  // before calling asp
//alert (xmlFormMap );
 params = "xmlFormMap=" + xmlFormMap;
 params = encodeURI(params)

 xmlHttp=GetXmlHttpObject();
 if (xmlHttp==null)
  {
  //alert ("could not get GetXmlHttpObject");
  return;
  } 

 xmlHttp.open("POST","sgDynamicCount.asp",true);
  //Send the proper header information along with the request
 
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

  xmlHttp.onreadystatechange=function()
    {
	//create a new XML document with returned data
    if(xmlHttp.readyState==4)
      {

	  try //Internet Explorer
		  {
		  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		  objLst = new ActiveXObject("Microsoft.XMLDOM");
		  xmlDoc.async=false;
		  xmlDoc.loadXML(xmlHttp.responseText); //load the document
		  //alert (xmlDoc.xml);
		  }
		catch(e)
		  {
		  try //Firefox, Mozilla, Opera, etc.
		    {
			var parser=new DOMParser();
			var xmlDoc=parser.parseFromString(xmlHttp.responseText,"text/xml"); 
			var objLst =document.implementation.createDocument("","",null);

		    }
		  catch(e)
		    {
		    return;// xml not supported by browserjust exit
		    }
		  }// try //Interne
		  //display the total product count
		   //alert(xmlDoc.xml); // only valide for IE
		  //writeWin(xmlDoc.xml);  //after return from asp
		  prodcount =xmlDoc.getElementsByTagName("prodcount")[0].childNodes[0].nodeValue;
		  if (document.getElementById("prodcountb")!=null){
		  	if(prodcount == 1){
		  	document.getElementById("prodcountb").innerHTML = "1 Product Found";  //singular
			}
			else{
				document.getElementById("prodcountb").innerHTML = prodcount + " Products Found";
			}
		  }	//if (document.getElementById
		  
		  if (document.getElementById("prodcountt")!=null){
		  	document.getElementById("prodcountt").innerHTML = prodcount;
		  	if(prodcount == 1){
		  	document.getElementById("prodcountt").innerHTML = "1 Product Found";  //singular
			}
			else{
				document.getElementById("prodcountt").innerHTML = prodcount + " Products Found";
			}			

		  }	//if (document.getElementById
 
		 oQueryItem = xmlDoc.getElementsByTagName("queryitem");
		 oID = xmlDoc.getElementsByTagName("id");
		  for(i=0;i < oQueryItem.length; i++){
				nodeFieldname = xmlDoc.getElementsByTagName("queryname")[i].childNodes[0].nodeValue;
				nodeType = xmlDoc.getElementsByTagName("querytype")[i].childNodes[0].nodeValue;
				oChoices = oQueryItem[i].getElementsByTagName("querychoice")
				QCcnt = 0 ;//'this keeps track of the query choice
				if (nodeType=='select-one'){
					sId=oQueryItem[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
					ClearOptions(sId); 
					optCnt=0;//counts the options that are active
					//optSelected = 0;// default to option 0 as selected
					oSelect =  document.getElementById(sId); 
					for (j=0; j < oChoices.length; j++){
					     sText =oChoices[j].getElementsByTagName("text")[0].childNodes[0].nodeValue;
					     sValue = oChoices[j].getElementsByTagName("value")[0].childNodes[0].nodeValue;
						 sSelected = oChoices[j].getElementsByTagName("selected")[0].childNodes[0].nodeValue;
						 sState = oChoices[j].getElementsByTagName("state")[0].childNodes[0].nodeValue;
						 if (sState=='on'){
						 	AddOption(sId,sText,sValue);
							if (sSelected=='yes'){
								optSelected=optCnt;
							}
							optCnt++;
						 }// if (sState=='on'){
						//alert("field name=" + nodeFieldname + "    id=" + sId+  "   nodeType=" +  nodeType + "   QCcnt=" + QCcnt);
						QCcnt++;
					}//for (j=0; j<oChoices.
					oSelect.options[optSelected].selected = true;
				}
				else{ //if (nodeType=='select-one') must be radio button or check box
					for (j=0; j < oChoices.length; j++){
						sId=oChoices[QCcnt].getElementsByTagName("id")[0].childNodes[0].nodeValue;
						sState=oChoices[QCcnt].getElementsByTagName("state")[0].childNodes[0].nodeValue;
						if(sState == "on"){ //turn on control
							document.getElementById(sId).disabled = false;
							if (document.getElementById('txt_' + sId) != null){   //if there is text for this element set to black
								document.getElementById('txt_' + sId).style.color = "#000000";
							}//if document.getElementById('txt_'
						}//if(xmlDoc.getElementsByTagName("state"
						else{// if(xmlDoc.getElementsByTagName("state")
							document.getElementById(sId).disabled = true;
							if (document.getElementById('txt_' + sId) != null){   //if there is text for this element set to gray
								document.getElementById('txt_' + sId).style.color = "#999999";
							}//if document.getElementById('txt_'	
						}//else{// if(xmlDoc.	
						QCcnt ++;
						//alert("field name=" + nodeFieldname + "    id=" + sId+  "   nodeType=" +  nodeType + "   QCcnt=" + QCcnt);
					}//for (j=0; j < oChoices.length; j++)
				}//if (nodeType=='select-o
		  }//for(i=0;i<obj
		 //alert(GetMS()-t1);
		 RemoveProgInd();
		 //setTimeout ( "document.body.style.cursor = 'default'", 200 );

      }// if(xmlHttp.readyS

    }//xmlHttp.onreadystatechange=function
	

xmlHttp.send(params); 

}//function Cascade

//======================================================
//			End Cascade()
//======================================================
