// JavaScript Document

var lang="";
var cats="";
var start=0;
var xmlDoc;
pagesize=10;


/** loadStudies **/
/** imports the query string and gets the parameters, then imports the correct XML file **/
function loadStudies(lang,cats){

	var qs=new Object();
	if(document.location.search.length>1)
	{
		tmp=document.location.search.split("?");
		tmp=tmp[1].split("&");
		for(x in tmp)
		{
			tmp2=tmp[x].split("=");
			qs[tmp2[0]] = unescape(tmp2[1]).replace("+"," ");
		}
	}
	//alert("cat:"+qs['category']);
	
	updateList("studylist.xml",qs['lang'],qs['category'],qs['start'])
}


/* loads the XML document from the server and runs it into the callback function */
function ajax(url, vars, callbackFunction)
{
  var request = window.XMLHttpRequest ?
      new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
  request.open("GET", url);
  //request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
 
  request.onreadystatechange = function()
  {
    if (request.readyState == 4 && request.status == 200)
    {
      if (request.responseText)
      {
          callbackFunction(request);
      }
    }
  };
  request.send(vars);
}

// updates the list on page reload //
function updateList(xml,lang_,cats_,start_){
	lang=lang_;
	cats=cats_;
	start=start_;
	
	if(typeof(lang)=="undefined")
		lang="en";
	if(typeof(start)=="undefined")
		start=0;

 	ajax("studylist_"+lang+".xml","",getMessage);

}

// gets the XML document from an XML text input or XML DOM object and returns it //
function getXMLDocument( ajax )
{
        if (typeof DOMParser == "undefined") {
                DOMParser = function()
                {};

                DOMParser.prototype.parseFromString = function(str, contentType)
                {
                        if (typeof ActiveXObject != "undefined") {
                                var doc = new ActiveXObject("MSXML.DomDocument");
                                doc.loadXML(str);
                                return doc;
                        } else if ( typeof XMLHttpRequest != "undefined" ) {
                                var req = new XMLHttpRequest();
                                req.open("GET", "data:" + (contentType || "application/xml") +";charset=utf-8," + encodeURIComponent(str), false);
                                if ( req.overrideMimeType )
                                        req.overrideMimeType(contentType);
                                req.send(null);
                                return req.responseXML;
                        } else
                                throw new FatalException( "Can't find a valid xml parser","AJAX::getXMLDocument()" );
                }
        }
        var strDocument = ajax.responseText;
        var xmlDocument = ajax.responseXML;
        try {
                if( ! xmlDocument || xmlDocument.childNodes.length === 0 )
                        xmlDocument = (new DOMParser()).parseFromString( strDocument,"application/xml" );
                return xmlDocument;
        } catch( e ) {
                return null;
        }

}


// callback from ajax function //
function getMessage(rxml){
	
	xmlDoc=getXMLDocument(rxml);
	document.getElementById("studylist").innerHTML="";
	studies=xmlDoc.getElementsByTagName("study");
	
	cats2=cats;
	if(lang=="")
		lang=null;
	if(cats=="")
	{
		cats=null;
	}
	
	if(typeof(cats)=="undefined" || cats==null)
		cats2="";
	else
		cats2=cats;

	

	// list case studies
	count=0;
	end=Number(pagesize)+Number(start);
	if(end>studies.length)
	{
		end=studies.length;
		//start=studies.length-pagesize;
	}

	pages=Math.ceil(studies.length/pagesize);
//	alert(pages);

	//alert(cats);
	pagelist="<div style='font-size: 14px; margin-top: 1em; margin-bottom: 1em;'><b>Page: ";
	for(i=0;i<pages;i++)
	{
		if(Math.round(start/pagesize)!=i)
			pagelist+="<a href='index.html?start="+(i*pagesize)+"&lang="+lang+"&category="+cats2+"'>"+(i+1)+"</a> ";
		else
			pagelist+=(i+1)+" ";
	}
	pagelist+="</b></div>";
	
	outputHTML(pagelist);

	for(x=start;x<end;x++)
	{
		if(lang==null && cats==null)
		{
			if(studies[x].getAttribute('language')=='en')
			{
				outputElement(studies[x]);
				count++;
			}
		}
		else if(lang!=null && cats==null)
		{
			if(studies[x].getAttribute('language')==lang)
			{
				outputElement(studies[x]);
				count++;
			}
		}
		
		else if(lang==null && cats!=null)
		{
			
			if(studies[x].getAttribute('language')=='en' && studies[x].getAttribute('cats').indexOf(cats)>-1 )
			{
				outputElement(studies[x]);
				count++;
			}
		}
		else
		{
			//alert(studies[x].getAttribute('language')+"="+lang+"-"+studies[x].getAttribute('cats').indexOf(cats));
			if(studies[x].getAttribute('language')==lang && studies[x].getAttribute('cats').indexOf(cats)>-1 )
			{
				outputElement(studies[x]);
				count++;
			}
		}
		
	}
	outputHTML(pagelist);
	
	if(lang==null)
		lang="en";

	setCheckedValue(document.forms['form1'].elements['lang'],lang);

	if(cats==null)
		cats="";

	setCheckedValue(document.forms['form1'].elements['category'],cats);

	if(count==0)
		document.getElementById("studylist").innerHTML = "No case studies found";

}


// sets the value selected on reloading the page //
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.selected = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].selected = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].selected = true;
		}
	}
}

// outputs an element of the XML document to screen converting to HTML //
// We don't use XSL due to browser limitations and no server side XSL processing bah! //
function outputElement(elm){
	document.getElementById("studylist").innerHTML+="<div><a class='case_link' href='studies/"+elm.getAttribute('link')+"'>"+elm.getAttribute('name')+"</a></div>";
	document.getElementById("studylist").innerHTML+="<div class='case_cats'>"+elm.getAttribute('cats')+"</div>";
	document.getElementById("studylist").innerHTML+="<div class='case_summary'>"+elm.getAttribute('summary').substr(0,250)+"... <a class='case_readmore' href='studies/"+elm.getAttribute('link')+"'>Read more...</a></div>";
}

function outputHTML(html){
	document.getElementById("studylist").innerHTML+=html;	
}
