////
// TS4 AJAX support functions
//
// Can only make call to turboshop site this script is on - can no be used for cross-domain AJAX
//
//
// Added by Derrick
//
// Moved to core and renamed by Pete 07-10-2007
//
// modifed names and made it allow for multi AJAX elements on a page
// updated for use on all TS4 sites - now does not require XML thanks pages
// basic XML support added
// allows for over riding of XMLRequest objects onstateready method by redeclaring alertContentsOrProcessXML
//

//////////////////////////
// main methods to use from this lib are:
//
// tsPostForm - to post the data of a given form via a XMLHTTPRequest and display the returned contents in side
// an elements innerHTML or if XML is returned call the default call back methods:
// - tsXMLRequestCallBackStart
// - tsXMLRequestCallBackEnd
// - tsXMLRequestCallBackNoode
//   Handles basic XML single table type data set - no nested tables.
//   Can redeclare alertContentsOrProcessXML for more complex XML see below...
//
// tsPostFormXMLCallBack - same as above but allows prefix name of call back methods to be passed to
// allow a page to have mnay AJAX item on it if required.  methoids must be name, [prefix]Start, [prefix]End
// and [prefix]Node
//
// tsLoadObjectsInHeader - loads js or css file in to header of page - for use with forms
//   you must call this after a call to tsQuery for all froms and pass the name of the javascript
//   template - see sofa sofa custom-shop.js showFabricChooser method
//
// tsQuery - to display the output of a ts4 url (i.e just the query string) in side an elements innerHTML
//
// tsRequest - make a XMLHTTPRequest get, post etc and pass your own call back methods prefix
//
// alertContentsOrProcessXML - can redeclare to handle more complex XML
///

// globals
var bustcachevar=1;
var bustcacheparameter=""

// hack for browser without XMLHttpRequest
if( !window.XMLHttpRequest ) XMLHttpRequest = function(){
	try{ return new ActiveXObject("MSXML3.XMLHTTP") }catch(e){}
	try{ return new ActiveXObject("MSXML2.XMLHTTP.3.0") }catch(e){}
	try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
	try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
	throw new Error("Could not find an XMLHttpRequest alternative.")
};


///////
// Default event methods called by all requests unless you use a callbackFunctionsPreFix to specify a prefix
// for the event methods to call, default is tsXMLRequestCallBack.
//
//The event types are:
// Start - called just before XML is parsed
// End - called after XML is parsed
// Node - called for each node parsed
//

function tsXMLRequestCallBackStart(XMLDOMObj) {
}

function tsXMLRequestCallBackEnd() {
}

//callback method you can over ride
function tsXMLRequestCallBackNode(xmlNodeName, xmlNodeValue) {
}


//
// Make a XMLHttpRequest
//
function tsRequest(requestType, queryString, postData, containerid, callbackFunctionsPreFix) {

	var http_request = null;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		try {
			http_request = new XMLHttpRequest();
			if (http_request.overrideMimeType) {
				if (requestType=='POST')
				http_request.overrideMimeType('text/xml');
				else
				http_request.overrideMimeType('text/html');
			}
		}
		catch(e) {
			return false;
		}
	}
	else {
		return false;
	}


	// call back
	aCallbackFunk=function() {
		alertContentsOrProcessXML(http_request, containerid, callbackFunctionsPreFix);
	}
	http_request.onreadystatechange = aCallbackFunk;

	http_request.open(requestType, rootdir+'index.php?'+queryString, true);
	if (requestType=='POST') {
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	}
	else {
		http_request.setRequestHeader("Content-type", "text/xml");
	}
	http_request.setRequestHeader("Content-length", postData.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(postData);
}


// get all the text, hidden or select fields
//
function getFormValues(formId)
{
	var fobj = tsGetElementById(formId)
	var str = "";
	var valueArr = null;
	var val = "";
	var cmd = "";
	for(var i = 0;i < fobj.elements.length;i++) {
		
		switch(fobj.elements[i].type) {
			case "textarea":
			str += fobj.elements[i].name +"=" + escape(fobj.elements[i].value) + "&";
			case "text":
			case "hidden":
			case "checkbox":
			case "radio":
			str += fobj.elements[i].name +"=" + escape(fobj.elements[i].value) + "&";
			break;

			case "select-one":
			str += fobj.elements[i].name +
			"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
			break;
		}
	}
	str = str.substr(0,(str.length - 1));
	return str;
}

// display html page contents in div (containerid)
function renderContainer(http_request, containerid) {
	if (tsGetElementById(containerid)!=null)
		tsGetElementById(containerid).innerHTML=http_request.responseText;
}

// can use this as a callback in call to tsRequest
function alertContentsOrProcessXML(http_request, containerid, xmlCallBackFunctionPreFix) {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			if (http_request.responseText.substr(1, 5)=='?xml ') {
				var resp 	=	http_request.responseXML;
				if (resp!=null && xmlCallBackFunctionPreFix!='') {
					if (xmlCallBackFunctionPreFix!='')
						eval(xmlCallBackFunctionPreFix+'Start(resp);');

					var fields = resp.getElementsByTagName("field");

					for (var i = 0; i < fields.length; i++) {
						if(fields[i].childNodes.length > 0) {
							name = fields[i].getAttribute("name");
							data = fields[i].childNodes[0].data;
							eval(xmlCallBackFunctionPreFix+'Node(name, data);');
						}
					}
					if (xmlCallBackFunctionPreFix!='')
						eval(xmlCallBackFunctionPreFix+'End();');
				} else {
					renderContainer(http_request, containerid);
				}
			}
			else {
				renderContainer(http_request, containerid);
			}
		}
		else {
			alert('There was a problem with the request.');
		}
	}
}



//
// Post data to turboshop
//
function makePOSTRequest(queryString,parameters,containerDivId,callbackMethodsPreFix) {
	// make Request
	
	tsRequest('POST', queryString, parameters, containerDivId, callbackMethodsPreFix);
}

//
//POST a form and display result in container object - normally use a 'j' ts4 query sring i.e 'j=myaccount' or 'j=comms&t=callme'
//
function tsPostForm(formId, ts4Parameters, containerDivId) {
	var fields = getFormValues(formId);
	var xmlCallBackFunctionPreFix = 'tsXMLRequestCallBack';	
	makePOSTRequest(ts4Parameters, fields, containerDivId, xmlCallBackFunctionPreFix);
}

//
//POST a form abut with custom XML call back methods
//
function tsPostFormXMLCallBack(formId, ts4Parameters, containerDivId, callbackMethodsPreFix) {
	var fields = getFormValues(formId);
	//xmlCallBackFunctionPreFix = callbackMethodsPreFix;	
	makePOSTRequest(ts4Parameters, fields, containerDivId, callbackMethodsPreFix);
}

//
// load a page in to a container object using a 'j' ts4 query sring i.e 'j=myaccount' or 'j=comms&t=callme'
//
function tsQuery(queryString, containerDivId, xmlCallBackFunctionPreFix) {
	//containerid = containerDivId;
	tsRequest('GET', queryString, '', containerDivId, xmlCallBackFunctionPreFix);
}


var loadedobjects=""

function tsLoadObjectsInHeader(){
	if (!document.getElementById)
	return

	for (i=0; i<arguments.length; i++){
		var file=arguments[i]
		var fileref=""
		if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf("javascript")!=-1){ //If object is a js file
				//alert("javascript");
				fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			}
			else if (file.indexOf(".css")!=-1){ //If object is a css file
				fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!=""){
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			loadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}



//////////////////////////////////////////
// Examples

/*

Call a form:

	function showFabricChooser(itemprcd) {
		tsQuery('j=comms&t=fabricrequest&tsp_itemprcd='+itemprcd, 'contentarea', '');
		tsLoadObjectsInHeader('index.php?j=comms&t=fabricrequest_javascript');//template must be js file with template settings
		hide('rangeZoomPicDiv');
		hide('specificationDetails');
		show('contentarea');
	}

Submit the form and display results using custom call back methods with prefix of: fabricRequestFormXMLResult

	function submit_fabricRequestForm() {
		if( validate_fabricRequestForm()){
			tsPostFormXMLCallBack('fabricRequestForm', 'j=comms&t=fabricchooser', 'response',
				'fabricRequestFormXMLResult');
		}
	}

{forms_javascript}

*/