// JScript source code


/*
 * This class allow an easy management of a dropdownlist
 */
function DropDownList(ddlPointer)
{    
    //PUBLIC VARIABLES 
    this.DataTextField  = null;
    this.DataValueField = null;
    this.DataSource     = null;
    
    
    //PUBLIC - bind data into the ddlist
    this.DataBind = function()
    {

		if(this.DataSource instanceof Recordset)
	    {
			if(this.DataValueField == null)
	            this.DataValueField = this.DataTextField;

	        while ( !this.DataSource.EOF() )
	        {
	            ddlPointer.options[ddlPointer.options.length] = 
	                new Option(
	                        this.DataSource.Field(this.DataTextField), 
	                        this.DataSource.Field(this.DataValueField));
	            
	            this.DataSource.MoveNext();
	        }
		}
		else if (this.DataSource instanceof Array)
		{
			var dTyp = (this.DataSource[0] instanceof Array);
			
			if (this.DataTextField == null)
				this.DataTextField = 1;

			if (this.DataValueField == null)
				this.DataValueField = 0;
				
			for (var i=0, dLen = this.DataSource.length; i<dLen; i++)
			{
	            ddlPointer.options[ddlPointer.options.length] = 
					(dTyp) 	? 
							new Option(this.DataSource[i][this.DataTextField],this.DataSource[i][this.DataValueField]) 
							:
							new Option(this.DataSource[i],this.DataSource[i]);
			}
		}
    };
    
    
    //PUBLIC - Remove the specified element from the ddlist
    this.Remove = function(index)
    {
        ddlPointer.options[index] = null;
    };
    
    
    //PUBLIC - Add a new element to the ddlist
    this.Add = function(strText, strValue)
    {
        ddlPointer.options[ddlPointer.options.length] = new Option(strText, strValue);    
    };
    
    
    //PUBLIC - delete all the options of the ddlist
    this.Reset = function()
    {
        ddlPointer.options.length = 0;
    };
}


/*
 * Allow you to query a database by the way of an asp page.
 * The object created returns an array of associative arrays that 
 * can be handled "like" a vb recordset.
 */
function Recordset(path)
{
    //PUBLIC VARIABLES
    //Error handling
    this.err = new Array();
    
    //paging variables
	var recordsPerPage = -1;
	var page = 1;
	var totalPages = 1;
	var totalRecords = -1;
		
	//PRIVATE VARIABLES
	//Path to the working page
    var strPath = path;
 
    //Error handling
    var errNumber = 0
    var errDescription = "";
    var errSource = "";
	
    //recordset management
    var sql = "";
    var recPosition = 0;
    var recordNumber = 0;
    var recs = new Array();
    
	//PUBLIC - execute the query
    this.ExecuteQuery = function(strSql, par1, par2, par3, par4, par5, par6, par7, par8, par9, par10)
    {
        sql = escape(strSql);
		
		var arg = null;
    
        for (var i=0; i<arguments.length; i++)
        {
            arg = arguments[i+1];
            
            if(typeof(arg) == 'string')
                arg = "'" + arg.replace(/'/gi, "''") + "'";
            
            sql = sql.replace("\{"+i+"\}", arg);
        }
		
		var result = SendRequest();

        FetchRecordset(result);
		
		this.err["number"] = errNumber;
		this.err["description"] = errDescription;
		this.err["source"] = errSource;
	};
    
	
	//PRIVATE - fetch the recordset with the xml tree
    function FetchRecordset(strXml)
    {
        var x = LoadXml(strXml);
        
        //check for query errors
        if (x.getElementsByTagName("error").length)
        {
            errNumber      = x.childNodes[0].childNodes[0].firstChild.nodeValue;
            errDescription = unescape(x.childNodes[0].childNodes[1].firstChild.nodeValue);
			errSource      = unescape(x.childNodes[0].childNodes[2].firstChild.nodeValue);
        }
        else //fetch the recordset
        {
            var pageNav = x.getElementsByTagName("pageNavigator");
            
            if(pageNav != null)
            {
                page = parseInt(pageNav[0].childNodes[0].firstChild.nodeValue);
                totalPages = parseInt(pageNav[0].childNodes[1].firstChild.nodeValue);
                totalRecords = parseInt(pageNav[0].childNodes[2].firstChild.nodeValue);
            }
            else
            {
                page = 1;
                totalPages = 1;
                totalRecords = 0;            
            }
            
            var recNodes = x.getElementsByTagName("recordset");
        
            if (recNodes != null)
            {
                recordNumber = recNodes.length;
			    var tmpNode = null;
    			
                for(var i=0; i<recordNumber; i++)
                {
                    recs[i] = new Array();
                    tmpNode = recNodes[i];
    				
                    for(var j=0, len=tmpNode.childNodes.length; j<len; j++)
                    {
                        recs[i][tmpNode.childNodes[j].nodeName] = 
                            CheckNodeValue(tmpNode.childNodes[j].firstChild);
                    }
                }
            }
                        
            recPosition = 0;
        }
    }
    

	//PUBLIC - return the BOF status
    this.BOF = function()
    {
        return (recPosition<0) ? true : false;
    };
    
	
	//PUBLIC - return the EOF status
    this.EOF = function()
    {
        return (recPosition<recordNumber) ? false : true;
    };
    
	
	//PUBLIC - return the number of records
    this.RecordCount = function()
    {
        return recordNumber;
    };
    
	
	//PUBLIC - return the field value
    this.Field = function(fieldName)
    {
        return unescape(recs[recPosition][fieldName]);
    };
    
	
	//PUBLIC - move to the next record
    this.MoveNext = function()
    {
        recPosition++;
    };

	
	//PUBLIC - move to the previous record
    this.MovePrevious = function()
    {
        recPosition--;
    };
    
	
	//PUBLIC - move to the "i" record
    this.Move = function(i)
    {
        recPosition = i;
    };
 
    
	//PUBLIC - move to the first record
	this.MoveFirst = function()
    {
        recPosition = 0;
    };
    
	
	//PUBLIC - move to the last record
    this.MoveLast = function()
    {
        recPosition = recordNumber -1;
    };
    
    //get or set the current page
    this.Page = function(actPage)
    {
        if(!isNaN(actPage))
            page = actPage;
            
        return page;
    }

    //set the total records per page
    this.RecordsPerPage = function(rpp)
    {
        recordsPerPage = rpp;
    }
    
    //return the total number of records
    this.TotalRecords = function()
    {
        return totalRecords;
    }
    
    //return the total number of pages
    this.TotalPages = function()
    {
        return totalPages;
    }
	
    
    //Verify the value of a node, return null if no value is present
    function CheckNodeValue(node)
    {
        if(node != null)
            return node.nodeValue;
        else
            return null;
    }
    
    
    //Load the xml structure from the variable testxml
    function LoadXml(strXml)
    {
        // code for IE
        if (window.ActiveXObject)
        {
            var doc=new ActiveXObject("Microsoft.XMLDOM");
            doc.async="false";
            doc.loadXML(strXml);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else
        {
            var parser=new DOMParser();
            var doc=parser.parseFromString(strXml,"text/xml");
        }

        // documentElement always represents the root node        
        return doc.documentElement;
    }

    
    //get a valid xmlhttp object or a null value if it's not possible
    function getXMLHttp() 
    {
        var xmlhttp = null;
        
        if (window.ActiveXObject) 
        {
            if (navigator.userAgent.toLowerCase().indexOf("msie 5") != -1) 
            {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            else 
            {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
        }
        if (!xmlhttp && typeof(XMLHttpRequest) != 'undefined') 
        {
            xmlhttp = new XMLHttpRequest()
        }
        
        return xmlhttp;
    }

	
	//PRIVATE - send a request to the server and return the result
    function SendRequest() 
    {
        var xmlhttp = getXMLHttp();
		var result = null;
		var myPath = strPath+"?paginaAttuale__="+page;

		/*
		we make an asyncronous request in order to be able to return the result of the request from the function
		(in fact a syncronous request obliges you to implement the function onreadystatechange that is executed
		after the end of the current function, making impossible to return a value from it)
		*/
        xmlhttp.open("POST", myPath, false);        
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send("sql="+sql+"&recsPerPage__="+recordsPerPage);

		if(xmlhttp.status==200)
		{
			result = xmlhttp.responseText;
		}
		else
		{
			result = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"+
				"<root><error><number>"+xmlhttp.status+"</number>"+
				"<description>"+escape(xmlhttp.statusText)+"</description>"+
				"<source>xmlhttp%20request</source></error></root>";
		}
		
		return result;
    }
}

