// JavaScript Document
// JavaScript Document    

var lang="";
var cats="";
var start=0;
var xmlDoc;
var id = new Array("bucketLeft", "bucketMiddle");
var fl = new Array("left", "right");
pagesize=8;


/** 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']);
	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="pt";
	if(typeof(start)=="undefined")
		start=0;


// Use the lat studylists, so that we don't have to keep two up to date.  
 	//ajax("studylist.xml","",getMessage);
ajax("../../lat/showcase/studylist_"+lang+".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
	/*if(pages > 1)
	{
		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
	*/
	
	// create list of pages
	pagelist="<div style='font-size: inherit; margin-top: 1em; margin-bottom: 1em; margin-left: 14px;clear:both;'><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++)
	{
		//alert ("study #: "+x+", lang: "+lang+", cats: "+cats);
		if(lang==null && cats==null)
		{
			if(studies[x].getAttribute('language')=='es')
			{
				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')=='es' && 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++;
			}
		}
		
	}
	// end processing
	
	//output page list to browser
	outputHTML(pagelist);
	
	if(lang==null)
		lang="es";

	setCheckedValue(document.forms['form1'].elements['lang'],lang);

	if(cats==null)
		cats="";

	setCheckedValue(document.forms['form1'].elements['category'],cats);


	//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");
	
	// output 4 rand quotes
	var numQuotesForDisplay = 4;
	if(quotes.length > numQuotesForDisplay)
	{
		var found=false;
		var current = new Array();
		var maxValue=quotes.length;
		var count=0;
		for (i=0;count<numQuotesForDisplay;count++)
    	{
      		found=false;
      		var rndValue = rand(maxValue);
      		for (j=0;j<current.length;j++)
      		{
        		if (current[j] == rndValue)
        		{
          			found=true;
          			break;
		        }
      		}
		    if (found)
			{
				count--;
			} 
			else 
			{
				current[count]=rndValue;
			}
    	}
		for(i=0; i<current.length; i++)
			outputQuoteElement(quotes[current[i]]);
	}
	else
	{
		for(x=0;x<quotes.length;x++)
		{
			outputQuoteElement(quotes[x]);
		}
	}
}

// helper for rand
function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n ) );
}


// 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)
{		
	img=elm.getAttribute('image');
	if(img==null)
		img="noimage.jpg";
		
	serv=elm.getAttribute('services');
	if(serv==null)
		serv="000000";
	servout="";
	
	//alert ("Num colors: "+colors.length);
	for(j=0;j<colors.length;j++){
		if(serv.charAt(j)==1)
			servout+="<img style='margin-right: 3px;' src='assets/Color"+j+".gif' title='"+colors[j]+"'/>";
		else
			//THIS DISPLAYS THE GRAY NOTHING BOX
			//servout+="<img style='margin-right: 3px;' src='assets/ColorN.gif' />";
			servout+="";
	}
    var moreString= 'Mais/Más/More...';
    if (studies[x].getAttribute('language') == 'pt') {
        moreString= 'Mais...';
    }
    else if (studies[x].getAttribute('language') == 'es') {
	    moreString= 'Más...';
    }
	
    document.getElementById("studylist").innerHTML+='\
		<div style="background-color:#fff; width:255px; float:' + fl[count%2] + '; padding:5px 0px 10px 10px;" id=' + id[count%2] + '>\
			<img src="'+img+'" title="' + elm.getAttribute('name') +'" alt="' + elm.getAttribute('name') + '" style="float:left; padding:0px 10px 0px 0px;"/>\
			<div><strong><a href="'+elm.getAttribute('link')+'" style="font-size:12px;line-height:12px;" target="_blank">' + elm.getAttribute('name') + '</a></strong>\
			    <div style="padding:7px 0;line-height:14px; font-weight:normal;">' + elm.getAttribute('summary').substr(0,60) + '...</div>\
			    '+servout+'&nbsp<a href="'+elm.getAttribute('link')+'" target="_blank">'+moreString+'</a>\
			</div>\
		</div>';
	
	if(count%2) {
		document.getElementById("studylist").innerHTML+='<hr style="clear: both; width: 100%;  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;	
}

