var xsl = null;
var xslProcess = true;
var dataInit = false;
var canProcess = true;
var xmlhttp, xslhttp;

function setXSL()
{
	xsl = null;
	if (xslhttp.readyState == 4) {
		// if "OK"
		if (xslhttp.status == 200) {
			xsl = xslhttp.responseXML.documentElement;
			xslProcess = true;
			// If the data has not yet been inited, it may have been waiting for me, so call it
			if(!dataInit) displayInitContent();
		}
	}
}

function loadXSL(url)
{
	if(!xslProcess) return; // Can only load one at a time
	var functionCall = function() {setXSL();};
	
	xslProcess = false;
	// AJAX code for Mozilla, Safari, Opera etc.
	if (window.XMLHttpRequest) {
		xslhttp = new XMLHttpRequest();
		xslhttp.onreadystatechange = functionCall;
		xslhttp.open("GET", url, true);
		xslhttp.send(null);
	}
	// AJAX code for IE
	else if (window.ActiveXObject) {
		xslhttp=new ActiveXObject("Microsoft.XMLHTTP");
		if (xslhttp)
		{
			xslhttp.onreadystatechange = functionCall;
			xslhttp.open("GET", url, true);
			xslhttp.send();
		}
	}
}

function loadXML(url, mode, div, headerBlock, loadingLength, type, id)
{
	if(!canProcess) return;
	var functionCall = function() {displayInitContent();};
	if(mode == 2) functionCall = function() {displayData(div, headerBlock, loadingLength, type, id);};
	
	canProcess = false;
	// AJAX code for Mozilla, Safari, Opera etc.
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = functionCall;
		xmlhttp.open("GET", url, true);
		xmlhttp.send(null);
	}
	// AJAX code for IE
	else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		if (xmlhttp)
		{
			xmlhttp.onreadystatechange = functionCall;
			xmlhttp.open("GET", url, true);
			xmlhttp.send();
		}
	}
}

function initContent()
{
	$(rootDiv).html(' <p> <img src="assets/mack/TalkingSCR/loading.gif" alt="" /></p>');
	loadXSL(dataPage+"&ret=XSL&"+random());
	loadXML(dataPage+"&ret=XML"+"&search="+filter+"&"+random());
}

// Modified method initContent() to accomodate Mack Australia SCR categories and future new SCR categories. 2011.07.26 LV.
function initContent2(categoryNodeId, questionNodeId) 
{
    $(rootDiv).html(' <p> <img src="assets/mack/TalkingSCR/loading.gif" alt="" /></p>');
    loadXSL(dataPage + "&catNode=" + categoryNodeId + "&quesNode=" + questionNodeId + "&ret=XSL&" + random());
    loadXML(dataPage + "&catNode=" + categoryNodeId + "&quesNode=" + questionNodeId + "&ret=XML" + "&search=" + filter + "&" + random());
}

function displayInitContent()
{
	// Make sure the XSL doc has been loaded first
	if(xsl == null) return;
	var xml = null;
	if (xmlhttp.readyState == 4) {
		// if "OK"
		if (xmlhttp.status == 200) {
			xml = xmlhttp.responseXML;
		}
	}
	else return;
	if(xml == null) return;
	// code for IE
	if (window.ActiveXObject)
	{
		ex=xml.transformNode(xsl);
		//ex = ex.replace(/&lt;\s*(\w+)\b(.*?)&gt;(.*?)&lt;\/\1&gt;/g,'<$1$2>$3</$1>');
		//alert("'"+trim(ex)+"'");
		if(trim(ex) == '<?xml version="1.0" encoding="UTF-16"?>')
			$(rootDiv).html('<p> There were no results found for your search.</p>');
		else
			$(rootDiv).html(restoreContent(ex));
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		xsltProcessor=new XSLTProcessor();
		xsltProcessor.importStylesheet(xsl);
		var tDiv = document.createElement('div');
		//resultDocument = xsltProcessor.transformToFragment(xml,document);
		tDiv.appendChild(xsltProcessor.transformToFragment(xml,document));
		//alert("'"+trim(restoreContent(tDiv.innerHTML))+"'");
		if(trim(restoreContent(tDiv.innerHTML)) == '')
			$(rootDiv).html('<p> There were no results found for your search.</p>');
		else
			$(rootDiv).html(restoreContent(tDiv.innerHTML));
	}
	setTimeout(function() {$('#category-header-0').addClass('expanded');$('#category-content-0').slideDown(300);}, 1000);
	dataInit = true;
	canProcess = true;
}

function requestContent(id, div, headerBlock, loadingLength, type, id)
{
	loadXML((dataPage+"&ret=XML&root="+id+"&search="+filter+"&"+random()), 2, div, headerBlock, loadingLength, type, id);
}

function displayData(div, headerBlock, loadingLength, type, id)
{
	var xml = null;
	if (xmlhttp.readyState == 4) {
		// if "OK"
		if (xmlhttp.status == 200) {
			xml = xmlhttp.responseXML;
		}
	}
	else return;
	if(xml == null) return;
	
	// code for IE
	if (window.ActiveXObject)
	{
		ex=xml.transformNode(xsl);
		//ex = ex.replace(/&lt;\s*(\w+)\b(.*?)&gt;(.*?)&lt;\/\1&gt;/g,'<$1$2>$3</$1>');
		$(div).html(restoreContent(ex));
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		xsltProcessor=new XSLTProcessor();
		xsltProcessor.importStylesheet(xsl);
		var tDiv = document.createElement('div');
		//resultDocument = xsltProcessor.transformToFragment(xml,document);
		tDiv.appendChild(xsltProcessor.transformToFragment(xml,document));
		$(div).html(restoreContent(tDiv.innerHTML));
	}
	$(headerBlock).html($(headerBlock).html().substring(0, $(headerBlock).html().length - loadingLength));
	$(headerBlock).addClass('expanded');
	$(div).slideDown(300);
	//setTimeout(function() {if(type == 'category' || type == 'subcategory') window.location.hash = ('#c'+id);}, 400);
	setTimeout(function() {if(type == 'category' || type == 'subcategory') scrollToElement(headerBlock.substring(1));}, 400);

	canProcess = true;
}

function scrollToElement(eleId)
{
	var y = 0;
	var ele = document.getElementById(eleId);
	while(ele != null)
	{
		y += ele.offsetTop;
		ele = ele.offsetParent;
	}
	window.scrollTo(0, y);
}

function loadData(type, id)
{
	var contentBlock = '#' + type + '-content-' + id;
	var headerBlock = '#' + type + '-header-' + id;
	var loadingGif = '<img src="assets/mack/TalkingSCR/loading.gif" alt="" />';
	var loadingLength = loadingGif.length - 4;
	
	// Fixes some odd thing that I didn't bother to investigate
	//if(type == 'subcategory') loadingLength -= 4;

	if(!$(headerBlock).hasClass('expanded'))
	{
		if($(contentBlock).html() == '')
		{	
			var headerHTML = $(headerBlock).html() + ' ' + loadingGif;
			$(headerBlock).html(headerHTML);
			setTimeout(function() {requestContent(id, contentBlock, headerBlock, loadingLength, type, id)}, 0);
		}
		else
		{
			$(headerBlock).addClass('expanded');
			$(contentBlock).slideDown(300);
			if(type == 'response') $('#response-link-' + id).html('<a href="javascript:void(0);" class="fakelink">Hide Response</a>');
			//setTimeout(function() {if(type == 'category' || type == 'subcategory') window.location.hash = ('#c'+id);}, 400);
			setTimeout(function() {if(type == 'category' || type == 'subcategory') scrollToElement(headerBlock.substring(1));}, 400);
		}
	}
	else
	{
		$(contentBlock).slideUp(300);
		$(headerBlock).removeClass('expanded');
		if(type == 'response') $('#response-link-' + id).html('<a href="javascript:void(0);" class="fakelink">Show Response</a>');
	}
}

function restoreContent(str)
{
	str = str.replace(/&amp;/g, '&');
	str = str.replace(/&lt;/g,'<');
	str = str.replace(/&gt;/g,'>');
	return str;
}

function filterResults()
{
	filter = escape($('#scrfilter').val());
	initContent();
}

function enterPressed(e)
{
	var charCode;
    if(e && e.which) charCode = e.which;
    else if(window.event) charCode = window.event.keyCode;
    if(charCode == 13) return true;
	return false;
}

function filterFocus(defaultValue)
{
	if($('#scrfilter').val() == defaultValue)
	{
		$('#scrfilter').val('')
	}
	else 
	{
		$('#scrfilter').select()		
	}
}

function resetSearch(defaultValue) 
{
	$('#scrfilter').val(defaultValue);
	filter = '';
	initContent();
}

function random()
{
	return Math.floor(Math.random()*100000000000);
}

function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}


