// JavaScript Document

var lang="";
var cats="";
var start=0;
var xmlDoc;
var id = new Array("bucketLeft", "bucketMiddle");
var fl = new Array("left", "right");
//var colors = new Array('Convergence', 'Switch', 'Routers', 'Wireless', 'Security', 'Voice Over IP (VoIP)');
var colors = new Array('Switching', 'Routing', 'Wireless', 'Security', 'Voice Over IP (VoIP)', 'Network Management', 'Services', 'Enterprise', 'SMB');
pagesize=8;


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

	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']);
	updateQuotes("quotes.xml");
	
}


/* 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.xml","",getMessage);

}

//updates the quotes section.
function updateQuotes(xml){
 	ajax(xml,"",getQuotesMessage);
}

// gets the XML document from an XML text input or XML DOM object and returns it //
// don't ask me how it works, I just downloaded 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;
        }

}


// recieves the XML for the study list and processes it //
function getMessage(rxml){
	
	//parse document
	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;
	}

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

	// create list of pages
	pagelist="<div style='font-size: inherit; margin-top: 1em; margin-bottom: 1em; margin-left: 14px;'><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>";
	// end list of pages
	
	// run through case studies
	for(x=start;x<end;x++)
	{
/*		if(lang==null && cats==null)
		{
			if(studies[x].getAttribute('language')=='en')
			{
				outputElement(studies[x],count);
				count++;
			}
		}
		else if(lang!=null && cats==null)
		{
			if(studies[x].getAttribute('language')==lang)
			{
				outputElement(studies[x],count);
				count++;
			}
		}
		
		else if(lang==null && cats!=null)
		{
			
			if(studies[x].getAttribute('language')=='en' && studies[x].getAttribute('cats').indexOf(cats)>-1 )
			{
				outputElement(studies[x],count);
				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);
				count++;
			/*}
		}*/
		
	}
	// end processing
	
	//output page list to browser
	outputHTML(pagelist);
	
	//output if there's nothing in the XML.
	if(count==0)
		document.getElementById("studylist").innerHTML = "No case studies found";

}

//recieves the XML for the Quotes section and processes it.
function getQuotesMessage(rxml){
	
	xmlDoc=getXMLDocument(rxml);
	document.getElementById("quoteArea").innerHTML="";
	quotes=xmlDoc.getElementsByTagName("quote");
	
	for(x=0;x<quotes.length;x++)
	{
		outputQuoteElement(quotes[x]);
	}

}


// 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,cnt){
	
	img=elm.getAttribute('image');
	if(img==null)
		img="noimage.jpg";
		
	serv=elm.getAttribute('services');
	if(serv==null)
		serv="000000";
	
	servout="";
	for(j=0;j<9;j++){
		if(serv.charAt(j)==1)
			servout+="<img style='margin-right: 3px;' src='assets/Color"+j+".gif' title='"+colors[j]+"'/>";
		else
			//servout+="<img style='margin-right: 3px;' src='assets/ColorN.gif'  title='"+colors[j]+"' />";
			servout+="";
	}
	
	document.getElementById("studylist").innerHTML+='\
		<div style="width: 260px; float:' + fl[cnt%2] + '; padding:5px 0px 8px 8px;" class=' + id[count%2] + '>\
			<img src="assets/'+img+'" title="' + elm.getAttribute('name').substr(0,21) + '" style="float:left; padding:0px 10px 0px 0px;"/>\
			<a href="'+elm.getAttribute('link')+'" target="_blank" style="font-size:13px; font-weight:bold"">' + elm.getAttribute('name') + '</a><br />\
			<div style="height: 50px; padding-top:10px;">' + elm.getAttribute('summary').substr(0,70) + '...<br/></div>\
			'+servout+'\
			<a href="'+elm.getAttribute('link')+'" target="_blank">View More</a> ['+elm.getAttribute('language')+']\
		</div>\
	';
	if(cnt%2)
		document.getElementById("studylist").innerHTML+='<hr style="clear: both; width: 570px;  background-color:#dfdfdf; color:#dfdfdf"/>';

	studies=xmlDoc.getElementsByTagName("study");
	totalStudies=Number(studies.length);
	endStudy=Number(end);
	startStudy=Number(start);
	
	if (endStudy == totalStudies) 	{
		final=(totalStudies - startStudy);
	} else {
		final=Number(end);
	}
	
	if ((cnt + 1 == final) && (startStudy + final == totalStudies) && ((cnt%2) == false))  {
		//Add <HR> to final 
		document.getElementById("studylist").innerHTML+='<hr style="clear: both; width: 570px;  background-color:#dfdfdf; color:#dfdfdf"/>';
	}
}

// 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 outputQuoteElement(elm){
	
	document.getElementById("quoteArea").innerHTML+='<div style="border: 1px solid #999999; padding:5px; margin:3px 0px 12px 0px"><div style="color:#3e3b3b; margin-bottom:5px">' + elm.getAttribute('text') + '</div><div style="color:#404040;font-weight:bold">' + elm.getAttribute('name') + '</div> <div style="color:#000000; font-weight:bold">' + elm.getAttribute('company') + '</div></div>';

}

// outputs some HTML to the Case Study area.
function outputHTML(html){
	document.getElementById("studylist").innerHTML+=html;	
}
