// (C) 2006 williamz.net - all rights reserved.  You may not copy or adapt this code without permission in writing
// and payment of any appropriate licensing fees.

// Initialises a variable to hold expected values for browser stack
var expectedHash = "";

var nextImg ="";

// Variable to hols the source of a post request - this allows differentiated behaviour 
// after a post request - such as setting a time out to refresh a page etc.
var postSource ="";

// Object detection to return the correct object for an ajax browser refresh - the way of doing
// an XML browser refresh depends upon broswer type. Used by the getAXHA() function
function getNewHttpObject() 
{
    var objType = false;
    try 
	{	
		// See if IE 6 ActiveX component available 
        objType = new ActiveXObject('Msxml2.XMLHTTP');
    }catch(e){
		try 
		{
			// See if IE 5.5 ActiveX component available - if it isn't, then ajax is not
			// going to work on the IE client...
            objType = new ActiveXObject('Microsoft.XMLHTTP');
        }catch(e)
		{
			try
			{
				// Try Mozilla/Opera way 
    	        objType = new XMLHttpRequest();
				if (http_request.overrideMimeType) 
				{
					// set type accordingly to anticipated content type
					//http_request.overrideMimeType('text/xml');
					http_request.overrideMimeType('text/html');
				}
			}catch(e){
				alert("Sorry, but this website will not work properly with your browser.  To view this web site, please upgrade to a browser that supports XML HTTP refresh requests, such as IE6+, FireFox 1.5+, etc.");
			}
		}
    }
	// Return the object that works, which will then be used to do the request
    return objType;
}


// Function used to update page content with new content by using a javascript object, the dom, and a http
// request.  The element container is the id of the DIV tag to be updated 
function getAXAH(url,elementContainer)
{
	// Set the document area to a loading message
	document.getElementById(elementContainer).innerHTML = 'Loading...';
	
	// Get the appropriate xml HTTP request type
	var theHttpRequest = getNewHttpObject();
	
	// Set the behaviour on receipt of reply
	theHttpRequest.onreadystatechange = function() {processAXAH(elementContainer);};

	// Open the request object
	theHttpRequest.open("GET", url);

	// Avoid IE caching; this pig took me several hours to figure out (Firefox acted on new calls to
	// to the function, while IE kept on displaying the same fragment).  This is only necessay with
	// GET requests - POSTS are not cached as they deal with form data
	// MUST be done after open call
	theHttpRequest.setRequestHeader("If-Modified-Since", "Thu, 13 Oct 2005 19:00:00 GMT");

	// Send the request, without a postable string
	theHttpRequest.send(false);

	function processAXAH(elementContainer)
	{
		// Check to see that response has been received and all data has come in
		// see http://www.w3schools.com/ajax/ajax_xmlhttprequest.asp for more detials
		if (theHttpRequest.readyState == 4) 
		{
			// Check that the server returns OK (there are other codes that could be
			// trapped for, such as the 404 response (page not found).
			if (theHttpRequest.status == 200) 
			{
				// Output the response to the page element
				document.getElementById(elementContainer).innerHTML = theHttpRequest.responseText;
			}else{
				// In the case of the error, output the error message.
				document.getElementById(elementContainer).innerHTML="Error! HTTP request return the following status message:&nbsp;" + theHttpRequest.statusText + "<br />URI: " + expectedHash;
			}
		}
	}

}

// This function puts a new hash value to the browser's location stack so that the back button
// works after an ajax refresh
function makeHistory(newHash)
{
	window.location.hash = newHash;
	expectedHash = window.location.hash;
	return true;
}


function handleHistory()
{
  if ( window.location.hash != "#" + expectedHash )
  {
	nHash = window.location.hash;
    expectedHash = nHash.substr(1);
	
	getAXAH(expectedHash,'mainPageStuff');
  }
  return true;
}

function pollHash() 
{
  handleHistory();
  window.setInterval("handleHistory()", 1000);
  return true;
}

// Functions that allow a POST request to be made (so a form can be posted without using submit
// via ajax)
var http_request = false;
   
function makePOSTRequest(url, parameters) 
{
	// Warning, this loading message will knock out any other elements placed on the page
	// it would be better to do this another way...
/*	if (postSource != "APR_CAT" && postSource != "SUB_WP_SEARCH" && postSource != "CHAT_POLL" && postSource != "CHAT_POLL_X" && postSource != "CHAT_POST")
	{
		disp('mainPageStuff', 'Loading...');
	}
	
	if(postSource == "SUB_WP_SEARCH")
	{
		disp('mainPageStuff', 'Searching...');
	}
	
*/
	http_request = false;

	http_request = getNewHttpObject();

   	http_request.onreadystatechange = alertContents;
   	http_request.open('POST', url, true);
   	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   	http_request.setRequestHeader("Content-length", parameters.length);
   	http_request.setRequestHeader("Connection", "close");
   	http_request.send(parameters);
}


// Function to control what is done once the data is received - this will change from 
// site to site
function alertContents() 
{
  	if (http_request.readyState == 4) 
	{
    	if (http_request.status == 200) 
		{
           	result = http_request.responseText;
			
			if (postSource == "NEW_IMG")
			{
				disp ('mainImage', result);

			}else if (postSource == "NEW_BRO"){
				disp ('bcInnerEl', result);
				dispImage(nextImg);
			
			}else if (postSource == "GET_QUOTE"){
				retQuote = result;
				changeQuote();

			}else if (postSource == "ADD_TO_CART"){

				if (result != "")
				{					
					disp ('cartBody', result);
					document.getElementById('cart').style.display= 'block';
				}
				
			}else{
				alert('Unkown source of request.');
			}
		}else{
            alert('There was a problem with the request.');
			alert (http_request.responseText);
         }
	  }
   }
   
   
   function doNewImage(fName, altText)
   {
   		var strToPost;
		
		postSource = "NEW_IMG";
	
		strToPost = "fName=" + encodeURI(fName);
		strToPost = strToPost + "&aText=" + encodeURI(altText);
   
   		makePOSTRequest('/scripts/ajax/newPic.php', strToPost);
   }
   

   function doNewBrowser(iNames, imgGo)
   {
   		var strToPost;
	
		nextImg = imgGo;
	
		postSource = "NEW_BRO";
	
		strToPost = "iNames=" + encodeURI(iNames);
//		strToPost = strToPost + "&imgGo=" + encodeURI(imgGo);
   
   		makePOSTRequest('/scripts/ajax/newBrowser.php', strToPost);
   }
