/* 
Copyright (c) 2006 David L Norris <dave@webaugur.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ 

/* loadDoc - handles onload event in document bodies 
 *
 * no parameters
 * returns nothing
 *
 * example: <body onload="loadDoc();">
 */
var loadDoc = function(){
    dhtmlHistory.initialize();
    dhtmlHistory.addListener(historySearch);
    
    if (dhtmlHistory.isFirstLoad()) {
        /* set the query text box value */
        var parms = parseUrl("#"+window.location.href.split("#")[1]);
        if( parms['w'] ) {
            document.getElementById("query").value = parms['w'];
            doSearch();
        }
        
        /* perform a history search */
        historySearch(window.location.search, null);
    }
    
	/* unhose PNG images in IE */
	transformPngs();
}


/* transformPngs -	alpha-blend PNG icons for the wonderfully 
 * 					borken Internet Explorer series of web browsers.
 *					This affords us 24-bit color icons that look nice.
 * 
 * Note:	I've read that DXImageTransform.Microsoft.AlphaImageLoader works 
 * 			differently between some revisions of IE 6. If the icons look 
 * 			wrong that specific IE 6 revision may need sizingMethod='scaling'
 *
 * no parameters
 * returns nothing
 *
 * example:  <body onload="transformPngs();"><img src="/foo/bar.png" />
 */
var transformPngs = function(){
	if( /MSIE (5\.5)|[6789]/.test(navigator.userAgent) && navigator.platform == "Win32"){
		as=document.getElementsByTagName('img');
		for(i=0;i<as.length;i++){
			if( /\.png$/.test(as[i].getAttribute('src'))){
				as[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" +
											as[i].src + "',sizingMethod='image')";
				as[i].src="/icons/blank.gif";
			}
		}
	}
}


function doSearch(){
	// Get query from text box
	var query = document.getElementById("query").value

	// Show busy cursor
	document.getElementById("thebod").style.cursor = "wait";

	var xmlHttp = new XMLHttpRequest();
	// specify HTTP method, file URL and 
	// whether to use asynchronous loading
	xmlHttp.open("GET", "/dave/blogger/swish-e.php?w="+query, true);
	xmlHttp.onreadystatechange = function()
	{
		if(xmlHttp.readyState == 4){
            /* add this query to the history */
		    oldloc = unescape(window.location.href).split("#")[0];
            window.location.href =  oldloc+'#w='+escape(query);
//            dhtmlHistory.add("w", query);
			var xmlDoc = xmlHttp.responseXML;
			var results = xmlDoc.documentElement.getElementsByTagName("result");
			html='<strong>Posts about &quot;'+query+'&quot;</strong><br /><ul id="SearchPostList">'+"\n";
			for (var i = 0; i < results.length; i++){
				var rank = results[i].getAttribute("rank");
				var title = results[i].getAttribute("title");
				var href = results[i].getAttribute("href");
				if(title.substring(0,4) == "err:"){
				    var error = true;
				}
				// format this result
				html += '<li><a href="'+href+'#w='+escape(query)+'">'+title+'</a></li>'+"\n";
			}
			html += '</ul>';
			if(error || (query == "") ){
                document.getElementById("PostSearchResults").innerHTML = "";
            }
            else {
                document.getElementById("PostSearchResults").innerHTML = html;
            }
			// Show normal cursor
			document.getElementById("thebod").style.cursor = "default";
		}
	}
	
	// perform the actual request
	xmlHttp.send(null);
}

var historySearch = function(loc, data){
    var parms = parseUrl("#"+loc);
    if( parms['w'] ) {
        document.getElementById("query").value = parms['w'];
        doSearch();
    }
}

/* parseUrl - parse the HTTP GET query portion 
 *	of an URL into an Array object.
 * urlText - Complete URL as a string.
 * 
 * example: var myArray = parseUrl( "http://foo/bar?baz=foo" );
 *          print( "baz=" + myArray['baz'] );
 * example: var myArray = parseUrl( "http://foo/bar#baz=foo" );
*          print( "baz=" + myArray['baz'] );
 */
var parseUrl = function(urlText) {
	var results = new Object();
	var input = unescape(urlText.substr(1));
	if (input) {
		// input.replace("&amp;", "&");
		// input.replace(";", "&");
		var srchArray = input.split("&");
		var tempArray = new Array();
		for (var i = 0; i < srchArray.length; i++) {
			var tempArray = srchArray[i].split("=");
			results[tempArray[0]] = tempArray[1];
		}
	}
	return results;
}
