// 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",qs['lang']);
	quoteHeading(qs['lang']);
    keyToSolutionsHeading(qs['lang']);
	//updateQuotes("quotes_"+lang+".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="es";
	if(typeof(start)=="undefined")
		start=0;

 	//ajax("studylist.xml","",getMessage);
	ajax("studylist_"+lang+".xml","",getMessage);
}

//updates the quotes section.
function updateQuotes(xml,lang){
     
	if(typeof(lang)=="undefined")
		lang="es";
	//ajax(xml,"",getQuotesMessage);
	ajax("quotes_"+lang+".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
	changeSubLogoLinks(lang); 
	changeSubLogo(lang);
	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";
<!--ras xxx	-->	
	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+="";
	}

   
 if (studies[x].getAttribute('language') == 'es')
 {
	 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>\
			<a href="'+elm.getAttribute('link')+'" style="font-size:12px; font-weight:bold;line-height:12px;" target="_blank">' + elm.getAttribute('name') + '</a><br />\
			<div style="padding-top:5px;height: 60px; ">' + elm.getAttribute('summary').substr(0,70) + '...</div>\
			'+servout+'<a href="'+elm.getAttribute('link')+'" target="_blank">Más...</a></div>\
		</div>\
	';

if(count%2) {
		document.getElementById("studylist").innerHTML+='<hr style="clear: both; width: 100%;  background-color:#dfdfdf; color:#dfdfdf"/>';
	}


 }
else if (studies[x].getAttribute('language') == 'pt')
{
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>\
			<a href="'+elm.getAttribute('link')+'" style="font-size:12px; font-weight:bold;line-height:12px;" target="_blank">' + elm.getAttribute('name') + '</a><br />\
			<div style="padding-top:5px;height: 60px; ">' + elm.getAttribute('summary').substr(0,70) + '...</div>\
			'+servout+'<a href="'+elm.getAttribute('link')+'" target="_blank">Mais...</a></div>\
		</div>\
	';

if(count%2) {
		document.getElementById("studylist").innerHTML+='<hr style="clear: both; width: 100%;  background-color:#dfdfdf; color:#dfdfdf"/>';
	}


}
else
{
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>\
			<a href="'+elm.getAttribute('link')+'" style="font-size:12px; font-weight:bold;line-height:12px;" target="_blank">' + elm.getAttribute('name') + '</a><br />\
			<div style="padding-top:5px;height: 60px; ">' + elm.getAttribute('summary').substr(0,70) + '...</div>\
			'+servout+'<a href="'+elm.getAttribute('link')+'" target="_blank">Mais/Más/More...</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;	

}




  function changeSubLogo(lang){
           
            var logoDiv = document.getElementById('subLogo');
                      
                  
            if(lang == 'es'){
            
                  
                  logoDiv.innerHTML = '<img src="images/img-cexito.jpg" alt="Asamblea Nacional de Pánama " title="Asamblea Nacional de Pánama " width="143" height="169"/>';
                  
            }else if (lang == 'en')
            {
                
                    
                  logoDiv.innerHTML = '<img src="images/MINISTERIO_DE_MINAS_LOGO_143x169.jpg" alt="Colombian Ministry of Mining and Energy " title="Colombian Ministry of Mining and Energy" width="143" height="169"/>';
            }else{
              
                  
                  logoDiv.innerHTML = '<img src="images/espmLarge.jpg" alt="ESPM" title="ESPM" width="143" height="169"/>';
            }
           
		
      }

     function changeSubLogoLinks(lang){
                       
                        var subLogoLinksDiv = document.getElementById('subLogoLinks');
                       
                   
                        if(lang == 'es'){
 
			                         subLogoLinksDiv.innerHTML='<p class="showcaseContentHeader" style="font-size:24px">Asamblea Nacional de Pánama  </p>';
							         subLogoLinksDiv.innerHTML+='<p>Uno de los tres órganos del Estado de Panameño, logro mejorar un 97% de efectividad el acceso a los servicios de la Red Corporativa...<a href="studies/casestudies/PANAMA.pdf" target="_blank">Más...</a><br/></p>';
							         subLogoLinksDiv.innerHTML+='<p> <a href="http://lat.3com.com/lat/casestudies/index.html" class="more">Ver más casos de estudio de LAT</a> &nbsp;<img src="assets/Arrow.gif" alt="Arrow" width="7" height="8" /></p>' ;
							         subLogoLinksDiv.innerHTML+='<p> <a href="http://www.3com.com/solutions/en_US/cgindex.html" class="more">Ver más casos de estudio en todo el mundo</a> &nbsp;<img src="assets/Arrow.gif" alt="Arrow" width="7" height="8" /></p>';
                        }
                        else if (lang == 'en')
                        {
                                     subLogoLinksDiv.innerHTML='<p class="showcaseContentHeader" style="font-size:22px">Colombian Ministry of Mining and Energy </p>';
                                     subLogoLinksDiv.innerHTML+='<p>As part of the quest for excellence of all government entities, the Colombian Ministry of Mining and Energy added new communications solutions...<a studies/casestudies/CASO_DE_EXITO_MINISTERIO_DE_MINAS_COLOMBIA_FS.pdf" target="_blank">More...</a><br/></p>';
                                     subLogoLinksDiv.innerHTML+='<p> <a href="http://www.3com.com/solutions/en_US/cgcase3.html?cat=all*la*all*all*all*all" class="more">View LAT Customer Success Showcase</a> &nbsp;<img src="assets/Arrow.gif" alt="Arrow" width="7" height="8" /></p>' ;
                                     subLogoLinksDiv.innerHTML+='<p> <a href="http://www.3com.com/solutions/en_US/cgindex.html" class="more">View Worldwide Case Studies</a> &nbsp;<img src="assets/Arrow.gif" alt="Arrow" width="7" height="8" /></p>';                     
                         }else{
                                    //Default portugese.
                                     subLogoLinksDiv.innerHTML='<p class="showcaseContentHeader" >ESPM</p>';
                                     subLogoLinksDiv.innerHTML+='<p>Recorremos à tecnologia de ponta para facilitar os procesos de ensino-aprendizagem dos nossos estudantes <a href="studies/casestudies/ESPM.pdf" target="_blank">Más/Mais...</a><br/></p>';
                                     subLogoLinksDiv.innerHTML+='<p> <a href="http://lat.3com.com/br/casestudies/index.html" class="more">Ver más casos de estudio de LAT </a> &nbsp;<img src="assets/Arrow.gif" alt="Arrow" width="7" height="8" /></p>' ;
                                     subLogoLinksDiv.innerHTML+='<p> <a href="http://www.3com.com/solutions/en_US/cgindex.html" class="more">Ver más casos de estudio en todo el mundo </a> &nbsp;<img src="assets/Arrow.gif" alt="Arrow" width="7" height="8" /></p>';                     
                        }
                        
            }


function quoteHeading(lang){
	var quoteHeaderDiv= new String();
	var quoteHeaderDiv = document.getElementById('quoteHeader');
	
if(lang=='en')
{     
	   quoteHeaderDiv.innerHTML='<Strong>Customer Quotes</Strong>';
	//quoteHeaderDiv.innerText='Customer Quotes';
}
else if(lang=='pt')
{ quoteHeaderDiv.innerHTML='<Strong>Testemunho</Strong>';
    // quoteHeaderDiv.innerHtml='Testemunho';
	//quoteHeaderDiv.innerText='Testemunho';
}
else{
	quoteHeaderDiv.innerHTML='<Strong>Testimonios</Strong>';
	 // quoteHeaderDiv.innerHtml='Testimonios';
  //  quoteHeaderDiv.innerText='Testimonios';
}
}

function keyToSolutionsHeading(lang){
	//var keyToSolutionsDiv= new String();
	var keyToSolutionsDiv = document.getElementById('keyToSolutionsHeader');
	
if(lang=='en')
{     
	   keyToSolutionsDiv.innerHTML='<Strong>KEY TO SOLUTIONS</Strong>';
}
else if(lang=='pt')
{  
	keyToSolutionsDiv.innerHTML='<Strong>SOLUÇÕES</Strong>';
}
else{
	keyToSolutionsDiv.innerHTML='<Strong>SOLUCIONES</Strong>';
}
}


