/* 
GDHoodSearch.js: by randy bacon 06/24/09
	hood search classes and methods
*/

/* HoodBrowserSearchParams
		class to wrap our search params for searching
*/

function HoodBrowserSearchParams(ingdmls, ingroup, ingroupKey, insearchFilter, instartRow, insearchItem)
{
	//class members
	this.gdMLS = escape(ingdmls);
	this.Group = escape(ingroup);
	this.GroupKey = escape(ingroupKey);
	this.SearchFilter = escape(insearchFilter);
	this.StartRow = escape(instartRow);
	this.SearchItem = escape(insearchItem);
}

//to post string - make me a post string
HoodBrowserSearchParams.prototype.ToPostString = function()
{
	var rtnStr = "gdMLS=" + this.gdMLS;
	if( this.Group != "" )
		rtnStr += "&sg=" + this.Group;
	if(this.GroupKey != "")
		rtnStr += "&sk=" + this.GroupKey;
	if(this.SearchFilter != "")
		rtnStr += "&sf=" + this.SearchFilter;
	if(this.StartRow != "")
		rtnStr += "&sr=" + this.StartRow.toString();
	if(this.SearchItem != "")
		rtnStr += "&si=" + this.SearchItem;
	
	return rtnStr;
};


/* end HoodBrowserSearchParams */ 

/* HoodBrowserItem
 * 		wrapper for a hood search result item
 */

function HoodBrowserItem(name, code)
{
	this.Name = name;
	this.Code = code;
}

/* end HoodBrowserItem */ 

/* HoodBrowserSearchResults
		wrapper class for the results of an item or group search
*/

function HoodBrowserSearchResults(searchParamsObj)
{
	//class members (consider _ private)
	this.ResultCount = 0;
	this.StartRow = 0;
	this.PageCount = 0;
	this.ResultsFound = false;
	
	this.IsGroup = false;
	
	this.FilterOptions = "";
	
	this.ResultItems = null;
	
	this.SearchParams = null;
	this.SetParams(searchParamsObj);
}

//method to set the search params (if we aren't creating from scratch)
HoodBrowserSearchResults.prototype.SetParams = function(searchParamsObj)
{
	this.SearchParams = searchParamsObj;
	//set the search type
	if( this.SearchParams.Group != "" && this.SearchParams.GroupKey != "" )
		this.IsGroup = false;
	else
		this.IsGroup = true;
};

/* end HoodBrowserSearchResults */ 

/* HoodBrowserSearch
 * 	actual obj to do our searches and wrap up some results!
 */
function HoodBrowserSearch(wsLocation, debug)
{
	this.Busy = false;
	this.CanSearch = false;
	this.Results = null; //should be of type HoodBrowserSearchResults
	this._WSLocation = wsLocation;
	this.oXmlReq = null;
	this._DebugIt = debug;
}

//call when you are ready for interaction
HoodBrowserSearch.prototype.Launch = function()
{
	this.CanSearch = true;
	this.Busy = false;
};

//meat of the search here
HoodBrowserSearch.prototype.Search = function(searchParams)
{
	//make sure we can even search
	if(!this.CanSearch || this.Busy)
	{
		if(this._DebugIt)
			alert('cannot search');
		return;
	}
	
	//fire events and start search
	if(this.OnSearchStart != null)
		this.OnSearchStart();
	this.Busy = true;
	this.Results = null;
	this.ResultsFound = false;
	
	// branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        this.oXmlReq = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) 
    {
        // branch for IE/Windows ActiveX version
        try {
            this.oXmlReq = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e) 
        {
            try 
            {
                this.oXmlReq = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (E) 
            {
                this.oXmlReq = false;
            }
        }
    }
    
    if( this.oXmlReq )
    {
    	/*if(this._DebugIt)
    		alert('searching ' + this._WSLocation + ' with params ' + searchParams.ToPostString());*/
        var oThis = this; //reference to this obj to use in function
        this.oXmlReq.onreadystatechange = function(){ oThis.WSRequestDone(); };
        this.oXmlReq.open("POST", this._WSLocation, true);
        this.oXmlReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        this.oXmlReq.send(searchParams.ToPostString());
    }   
};

//handle our XML response
HoodBrowserSearch.prototype.WSRequestDone = function()
{
	 //process our request
    if (this.XmlResponseValid()) 
    {
    	/*if(this._DebugIt)
    		alert(this.oXmlReq.responseText);*/ //debug here
    	    	
    	//parse
        var xmlResponse = this.oXmlReq.responseXML.documentElement;
        if( HoodBrowserSearch.FindXMLNodes(xmlResponse, "NR") != null)
        {
        	this.ResultsFound = false;
        }
        else
        {    
        	this.ResultsFound = true;
        	
	    	//get search params and create results first
	    	var tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "GM");
	    	var tmpGdmls = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "GP");
	    	var tmpGroup = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "GPI");
	    	var tmpGroupKey = (tmpNode != null && tmpNode.length == 1) ? tmpNode[0].firstChild.nodeValue : "";
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "SF");
	    	var tmpSearchFilter = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "SR");
	    	var tmpStartRow = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "SI");
	    	var tmpSearchItem = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	
	    	var searchParams = new HoodBrowserSearchParams(tmpGdmls, tmpGroup, tmpGroupKey, tmpSearchFilter, tmpStartRow, tmpSearchItem); 
	    	
	    	//alert('reparse ' + searchParams.ToPostString());
	    	
	    	this.Results = new HoodBrowserSearchResults(searchParams);
	    	this.Results.ResultItems = new Array();
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "PC");
	    	this.Results.PageCount = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "SR");
	    	this.Results.StartRow = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "RC");
	    	this.Results.ResultCount = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    	
	    	//then parse unique items
	    	if( this.Results.IsGroup )
	    	{
	    		tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "GPI");
	    		if( tmpNode != null )
	    		{
		    		for(var i=0;i<tmpNode.length;i++)
		    		{
		    			this.Results.ResultItems.push(new HoodBrowserItem(new String(tmpNode[i].firstChild.nodeValue), null));
		    		}
	    		}
	    	}
	    	else
	    	{
	    		tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "FO");
	    		this.Results.FilterOptions = tmpNode != null ? tmpNode[0].firstChild.nodeValue : "";
	    		//get the HD items
	    		tmpNode = HoodBrowserSearch.FindXMLNodes(xmlResponse, "HD");
	    		if(tmpNode != null)
	    		{
	    			for(var i=0;i<tmpNode.length;i++)
		    		{
	    				var tmpName = tmpNode[i].childNodes[0].firstChild.nodeValue;
	    				var tmpCode = tmpNode[i].childNodes[1].firstChild.nodeValue;
	    				this.Results.ResultItems.push(new HoodBrowserItem(tmpName, tmpCode));
		    		}
	    		}
	    	}
	    	
        }
        
        //done loading stuff up change our flags and fire the event
    	this.Busy = false;
    	if(this.OnSearchEnd != null )
    		this.OnSearchEnd();
    }
};

//static helper to get an XML node value
HoodBrowserSearch.FindXMLNodes = function(xmlDoc, node)
{
	if( xmlDoc.getElementsByTagName(node) != null && xmlDoc.getElementsByTagName(node).length > 0 && xmlDoc.getElementsByTagName(node)[0].firstChild != null )
		return xmlDoc.getElementsByTagName(node);
	return null;
};

//see if our XML response is valid
HoodBrowserSearch.prototype.XmlResponseValid = function()
{
	if(this.oXmlReq)
    {
        if (this.oXmlReq.readyState == 4) 
        {
            if (this.oXmlReq.status == 200) 
            {
            	/*if(this._DebugIt)
            		alert("Request return text status was:\n" + this.oXmlReq.responseText);*/
                return true;
            } 
            else 
            {
                 //unexpected response handle it here
                if(this._DebugIt)
                    alert("Request return text status was:\n" + this.oXmlReq.statusText + "\nText:" + this.oXmlReq.responseText);
            }
        }
    }
    return false;
};

//events
HoodBrowserSearch.prototype.OnSearchStart = null;
HoodBrowserSearch.prototype.OnSearchEnd = null;
HoodBrowserSearch.prototype.OnSearchTimeout = null;

/* end HoodBrowserSearch */ 


