
function Dictionary(locale, contextArray, url){
	
	this.objContextDom = new ActiveXObject("Microsoft.XMLDOM");
	this.objContextDom.async = false;		
	
	this._locale = locale;
	this._context = contextArray.join();
	//this.svcURL = "http://devapp1/Services/Globalization/Language.asmx/GetDictionary";
	//this.svcURL = "http://localhost/Services/Globalization/Language.asmx/GetDictionary";
	this.svcURL = url;
	this._errorMsg = "";
	
	try { // Added on 10.16.2006 ~Olga (issue #7637)
		var xmlhttp_ctx = new ActiveXObject ("Microsoft.XMLHTTP");
		//	Join takes the contents of the array and makes it
		// a string of CSV's
		var oParam = "Locale=" + this._locale + "&Context=" + this._context  //ContextArray.join();
	
		//Post the data using the supplied url
		xmlhttp_ctx.Open("POST", this.svcURL, false);
		// Set the RequestHeader object
		xmlhttp_ctx.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		// Send the request with parameters
		xmlhttp_ctx.Send(oParam);
	
		// Check the status of the request
		if(xmlhttp_ctx.status != 200){
			// There was an error
			this.errorMsg = "Unable to obtain context at this time."
			alert(this.errorMsg);
			xmlhttp_ctx.abort();
		}else{
			// Return is good, no errors
			var svXML = xmlhttp_ctx.responseXML.xml;
			
			/////////////////////////////////
			// added for diagnostic purposes
			this._dom=svXML;
			//////////////////////////////////
			
			//alert(svXML);
			xmlhttp_ctx.abort();
			// Load the xml into the dom objContextDom DOM
			this.objContextDom.loadXML(svXML);
		}
	}catch(ex){
		alert("Dictionary Error: "+ ex.description);
		return;
	}
	
	this.lookUpToken = function(){
		var args = arguments;
		var result = null;
		switch(args.length) {
			case 0:
				result = null;
				break;
				
			case 1: 
				result = this.lookUpDomToken(this.objContextDom, args[0]);
				break;
				
			default:
				result = this.lookUpDomToken(this.objContextDom, args[0]);
				if (result == null) { return null;}
				
				var fmtargs = new Array(args.length - 1);
				for (var i = 1; i < args.length; i++) {
					fmtargs[i-1] = args[i];
				}
				
				for (var i = 0; i < fmtargs.length; i++) {
					var regex = new RegExp("\\{" + i + "\\}", "g");
					result= result.replace(regex, fmtargs[i]);
				}
				break;
		}
	
		return result;
	}
	

	
	
	this.lookUpDomToken = function(objDom, tokenName){
		
		if(objDom == null){
			return "Unable to connect to DOM";
		}
		
		//First, let's make sure there are items to check
		var oNodeList = objDom.selectSingleNode("//Items");
		var itemCount = oNodeList.selectNodes("Item").length;
		if(itemCount < 1){
			return "There are no tokens to return";
		}
		try{
		var oNode = objDom.selectSingleNode("//Items/Item[@Name='" + tokenName + "']");
			return oNode.text.toString();
		}catch (err){
			return null;
		}
	}

	
	this.populateForm = function(){
		this.iterateForm();
	}

	this.iterateForm = function(){
		
		var allElements = window.document.all;
		for (var i = 0; i < allElements.length; i++) {
			var thisElement = allElements[i];			
			
			//If there is a titletoken attribute transform the title
			if(thisElement.titletoken != null){
				thisElement.title = this.lookUpToken(thisElement.titletoken.toString());
			}
			
			if(thisElement.token !=null){
			
				var tokenName = thisElement.token.toString();
				var tokenValue = this.lookUpToken(tokenName);
				if(tokenValue != null){
					if(thisElement.type != null){ // form element										
					
						switch(thisElement.type){
							case "button":
								SetButtonWidth(thisElement,tokenValue);
								//thisElement.value = tokenValue;
								break;
							case "submit":
								thisElement.value = tokenValue;
								break;
							case "option":
								thisElement.value = tokenValue;
								break;
							default:
								thisElement.innerHTML = tokenValue;
								break;
						}
					}else { // not a form element
						switch(thisElement.tagName.toUpperCase()){
							case "IMG":
								thisElement.alt = tokenValue.stripBreaks();
								break;
							default:
								thisElement.innerHTML = tokenValue;
								break;
						}
					}
				}
			}
		}
	}
	
	String.prototype.stripBreaks = function(){
		return (this.replace(/<br>/gi,"\n").replace(/<br\/>/gi,"\n"));
	}
	
	//////////////////////////////////
	// diagnostics
	this.dumpAll=function()
	{
		var oNodeList = this.objContextDom.selectSingleNode("//Items");
		var itemCount = oNodeList.selectNodes("Item").length;
		
		var out="Locale: " + this._locale + "\r\n";
		out+="Context: " + this._context + "\r\n";
		out+="Node list count: " + itemCount + "\r\n";
		out+="\r\n";
		out+=this._dom + "\r\n";
		window.open("","","").document.write("<textarea cols=120 rows=40>" + out + "</textarea>")
	}
	
	this.dumpVal=function(out)
	{
		window.open("","","").document.write("<textarea cols=120 rows=40>" + out + "</textarea>")
	}
}




var Globalization = {
	Context: new Array(),
	Locale: "en-US",
	CreateDictionary: function(url){
		return new Dictionary(this.Locale, this.Context, url);
	}
}


function SetButtonWidth(element, tokenVal){
		
	var _cookie = getCookie("LocaleName");
		
	if(_cookie == "en-CA" || _cookie == "en-US"){
		element.value = tokenVal;
		return;
	}
	
	//Create a span dynamicaly to hold the token text
	//This is needed to get the width in pixels of the
	//text. It is destroyed later in the function
	var x = null;
	x = window.document.body.appendChild(document.createElement("SPAN"));
	x.id = "transformButtonSpan";
	x.style.width="";
	x.innerText = tokenVal;
		
	//Get the offset width of the text in the span
	var i_offset = window.document.getElementById("transformButtonSpan").offsetWidth;
		
	//Pad the offset with a little  more space
	i_offset = i_offset + 35;
		
	//Let's destroy the element so it can be used again and not 
	//interfear with anything on the page
	var oNodeToRemove = window.document.getElementById("transformButtonSpan");
	var oParentNode = oNodeToRemove.parentNode;
	oParentNode.removeChild(oNodeToRemove);
	
	//Get the width of the button, it returns the value + "px"
	//We need to strip off the px
	var _curLen = element.currentStyle.width;
	_curLen = _curLen.substring(0,_curLen.length-2);
	
	//If the offset is larger than the width of the button
	// Resize the button to fit the text	
	if( i_offset >= _curLen)
		element.style.width = i_offset;
		
	//Set the token value
	element.value = tokenVal;
}

// This function tries to get the content of globalization.xml:
// This function returns that xml string or null if the string couldn't be loaded.
// Takes 1 parameter which is the relative path to the globalization.xml file.
// Returns a string containing 
function GetGlobalizationXMLText(relPath)
{
  var oXMLDom = new ActiveXObject("Microsoft.XMLDOM");
  oXMLDom.async = false;

  var blvXMLStat = oXMLDom.load(relPath);

  // the xml wasn't loaded successfully
  if(blvXMLStat == false)
  {
		return null;
  }
  else
  {
		return oXMLDom.text;
  }
}

////////////////////////////////// COOKIES ///////////////////////////
//alert("Go away, I am testing here =D \n\t\t~Olga")
//debugger;
var cookieJar = window.document.cookie; // for cookies
var LocaleMap = {
	"en-US" : 1,
	"es-US" : 2,
	"en-CA" : 3,
	"fr-CA" : 4,
	"es-MX" : 5
};


function getCookie(name)
{
	//var cookieJar = window.document.cookie;
	var index = cookieJar.indexOf(name + "=");
	if (index == -1) return null;
	index = cookieJar.indexOf("=", index) + 1; // first character
	var endstr = cookieJar.indexOf(";", index);
	if (endstr == -1) endstr = cookieJar.length; // last character
	return unescape(cookieJar.substring(index, endstr));
}

function getBrowserLocaleName() {
	// TODO: use server variable "BrowserLang" to accurately detect browser language, 
	// and not operating system language
	var defValue = "en-CA";
	var retValue;
	try {
		retValue = (window.document.getElementById('BrowserLocaleName').innerText).split(',')[0];
	}catch(ex) {
		retValue = defValue;
	}
	finally {
		return retValue;
	}
}

function getSystemLocaleName() {
	var retValue = "en-US";
	if (window.navigator.userLanguage && window.navigator.userLanguage!="") {
		var sln = window.navigator.userLanguage;
		var test = sln.split("-")[0].toLowerCase()+"-"+sln.split("-")[1].toUpperCase();
		// check if this is supported OEC language
		if (typeof(LocaleMap[test])!='undefined')
			return test;
	}
	return retValue;
}


// replace xml reserved chars with entitites				
function cleanXMLString(s)
{
	if (typeof(s) != "string")
		return s;
	var arrRe = new Array();
	arrRe[0] = new Array(/&/g,"&amp;");	
	arrRe[1] = new Array(/'/g,"&apos;");
	arrRe[2] = new Array(/"/g,"&quot;");
	arrRe[3] = new Array(/</g,"&lt;");
	arrRe[4] = new Array(/>/g,"&gt;");
	var rtn=s;
	for (var i=0;i<arrRe.length;i++)
	{
		var tmp = rtn.replace(arrRe[i][0],arrRe[i][1]);
		rtn = tmp;
	}
	return rtn;
}
