/**
 * Need to fix:
 *
 * Increasing textarea and input type="text" boxes fontsizes so that
 * user can post in readable Tibetan when editing.  This is already
 * partly handled well with the global variable
 * tp_bcorrectForTibetanFormInput, but the bigger size kinda makes
 * some sites, like Geeklog, look funny.  Use some onfocus measures?
 *
 * IE isn't Tibetan processing the comments.  Tests reveal that the
 * treewalker isn't really working, not catching all the elements I need.
 * Can't seem to find a better treewalker javascript implementation.
 * Maybe since only IE misses this DOM functionality, just use
 * document.all as a substition?  I think I have to look at Safari to
 * see if it really supports the filter argument of this DOM method.
 * (I seem to recall Safari had a problem with this single parameter)
 *
 * IE, Safari cookie is not persisting, the other browsers, yes?
 * 2. more basic problem, IE not making cookie on first font change?
 *
 * Opera is giving me some weird Javascript error that I can't figure out
 *
 * when using weft with Jomolhari, don't use sub-roots, use everything
 * but, and the stacks should come out okay anyway ACTUALLY THATS NOT RIGHT
 */


// Last modified May 2008
// chris AT tibetanportal DOT-HERE com (www.tibetanportal.com)
// Licence: GPLv2


	/*****************************************************************************
		Tibetan Aider functions
	*****************************************************************************/ 

	//*******************************************************
	//	Set up global variables
	
// Jomolhari, Tibetan Machine Uni not embedding right
// What's the license of TCRC Youtso Unicode?
var tp_FONTLIST = [
	// fontname               size lnheight valign priority userhas embeddable operatingsystem 
	// last option = looksGoodInXPwithUniscribe
	["Jomolhari"                , 160, 160, -15,  80, false, false, "PC" , false],
	["Microsoft Himalaya"       , 195, 140,  10,  60, false, true , "PC" , false],
	["TCRC Youtso Unicode"      , 160, 160, -15,  30, false, true , "PC" , true ],
	["Tibetan Machine Uni"      , 160, 160, -15,  50, false, false, "PC" , false],
	["Tib-US Unicode"           , 222, 107, -15,  85, false, true , "PC" , true ],
	["Uchen_05"                 , 280, 100, -25,  70, false, true , "PC" , false],
	["Wangdi29"                 , 360,  75, -40,  10, false, true , "PC" , false],
	["XTashi"                   , 220, 100, -20,  40, false, true , "PC" , false],
	["Kailasa"                  , 152, 150,  -7, 120, false, false, "Mac", false],
	["Kokonor"                  , 155, 160, -15, 110, false, false, "Mac", false],
	["XenoType Tibetan New"     , 171, 144, -19,  90, false, false, "Mac", false],
	["XenoType TB dBuMed"       , 220, 150, -18, 100, false, false, "Mac", false],
	["XenoType TB Woodblock"    , 222, 150, -20, 105, false, false, "Mac", false],
	["XenoType TB sPungsChen"   , 200, 130, -15, 105, false, false, "Mac", false],
	["XenoType TB Horyig Modern", 200, 166, -23, 120, false, false, "Mac", false]
];

var tp_FONTNAME      = 0;
var tp_FONTSIZE      = 1;
var tp_LINEHEIGHT    = 2;
var tp_VERTICALALIGN = 3;
var tp_PRIORITY      = 4;
var tp_USERHAS       = 5;
var tp_EMBEDDABLE    = 6;
var tp_OS            = 7;
var tp_NOUSPGOOD     = 8;

// ******************************************************************
var tp_knowIfXPorLower = false; // global variable
// REDO THIS BETTER (know only checks for XP, but not lower
if ( navigator.userAgent.indexOf( "Windows NT 5" ) > -1 ){
	tp_knowIfXPorLower = true;
}
// don't embed most opentype fonts in XP, only those ones that
// display correctly
if ( tp_knowIfXPorLower ) {
	for (var i = 0; i < tp_FONTLIST.length; i++) {
		if (!(tp_FONTLIST[i][tp_NOUSPGOOD])) {
			tp_FONTLIST[i][tp_EMBEDDABLE] = false;
		}
	}
}
// ******************************************************************

var tp_myCookie;
var tp_currentFont = null;
var tp_noBold =      true;
var tp_bcorrectForTibetanFormInput = true;
var tp_embedFonts =  false;
var tp_fontMultiplier = 1;
var tp_bReadjust =   true;
var tp_nReadjust =   0;
var tp_bFineTune =   false;
var tp_aFineTuneSpans = [];
// var tp_convertUCS2CNS = true;

var tp_cookieDomain = ""; // can be set by user
// I set above to "tibetanportal.com"

// Create the global symbol "com" if it doesn't exist
// Throw an error if it does exist but is not an object
var com;
if (!com) {com = {};}
else if (typeof com != "object") {
    throw new Error("com already exists and is not an object");
}
// Repeat the creation and type-checking code for the next level
if (!com.tp) {com.tp = {};}
else if (typeof com.tp != "object") {
    throw new Error("com.tp already exists and is not an object");
}
	
// **************************************************************************


// **************************************************************************
function tp_addFontSelectContainerForMediaWiki() {
	var d = document;
	var exist = d.getElementById('p-navigation');
	if (exist) {
		var o = d.createElement("div");
		o.className = "portlet";
		o.id = "com_tp_fontSelectContainer";
		var h5 = d.createElement("h5");
		h5.appendChild(d.createTextNode("Tibetan Font"));
		o.appendChild(h5);
		exist = d.getElementById('p-navigation');
		var par = exist.parentNode;
		par.insertBefore(o, exist);
	}
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
function tp_updateFONTLISTbyFontAvailability() {
	var g = com.tp.General;
	var fontName;
	for (var i=0; i<tp_FONTLIST.length; i++) {
		fontName = tp_FONTLIST[i][tp_FONTNAME];
		if (g.hasFont(fontName)) {
			tp_FONTLIST[i][tp_USERHAS] = true;
		} else {
			tp_FONTLIST[i][tp_USERHAS] = false;
		}
	}
}
///////////////////////////////////////////////////////
function tp_embedFont(fontName) {
	var d = document;
	var oLink = d.createElement('link');
	oLink.setAttribute("rel", "stylesheet");
	var rSpaceCharacter = /\s/g;
	var s = fontName.replace( rSpaceCharacter, "" );
	var u = navigator.userAgent;	
	if ((u.indexOf("compatible") > -1) && (u.indexOf("MSIE") > -1)) {
		s += "UCSandSpace";
	}
	s += ".css";
	oLink.setAttribute("href", "/embeddedFonts/" + s);
	var oHead = d.getElementsByTagName("head")[0];
	oHead.appendChild(oLink);
}
///////////////////////////////////////////////////////
// replace above \n to \n with Dreamweaver regexp replace within selected text
function tp_populateFontSelectContainer() {
	// will only populate if container node is found
	var u = com.tp.User;
	
	var d = document;
	var o = d.getElementById('com_tp_fontSelectContainer');
	if (o) { // create SELECT node
		var select = d.createElement("select");
		select.name = "com_tp_fontSelect";
		select.id   = "com_tp_fontSelect";
		
		// add OPTIONs to the SELECT
		var option, fontName;
		for (var i=0; i<tp_FONTLIST.length; i++) {
			option = d.createElement("option");
			fontName = tp_FONTLIST[i][tp_FONTNAME];
			
			// set the selected font in box before adding any special characters
			if (fontName == tp_currentFont) {
				option.defaultSelected = true; // Opera needs
				option.selected = true;
			}
			
			// add a "+" or "*" based on properties
			if (!tp_FONTLIST[i][tp_USERHAS]) {
				if (tp_embedFonts && u.getBrowserCanEmbedFonts() && tp_FONTLIST[i][tp_EMBEDDABLE]) {
					fontName = "+" + fontName;
				}
				else {
					fontName = "*" + fontName;
				}
			}
			
			fontName = fontName + " (" + tp_FONTLIST[i][tp_OS] + ")";

			// add to select tag
			var t = d.createTextNode(fontName);
			option.appendChild(t);
			select.appendChild(option);
		}
		// add Help option
		// option = d.createElement("option");
		// option.appendChild(d.createTextNode('[ font help... ]'));
		// select.appendChild(option);
		
		// give SELECT an onchange event
		select = o.appendChild(select);
		var a0 = "this.options[this.selectedIndex].text";
		select.onchange = tp_onchangeTibetanStyleByFont;
		
		// if I make the below value greater than 200,
		// it breaks my Wordpress blog
		select.style.width = "180px"; // this will vary as font names get longer
		
		// add boldness to avaiable fonts
		var op = select.options;
		for (i=0; i<op.length; i++) {
			if (op[i].text.indexOf("*") > -1) {
				op[i].style.color = "#C0C0C0";
			}
			if (op[i].text.indexOf("help") > -1) {
				op[i].style.fontWeight = "bold";
			}
		}
		// add more
		/*var br = d.createElement("br");
		o.appendChild(br);
		var a = d.createElement("a");
		a.href = "http://www.thdl.org/tools/fonts/tibfonts.php?l=uva200607171100";
		a.appendChild(d.createTextNode(" Download Jomolhari Font"));
		o.appendChild(a); */
		
		// return true if created
		return true;
	}
	// return false if container node not found
	return false;
}

	//***********************************************************
	// Return a Tibetan font that user has, first one found
	
function tp_checkUsersTibetanFonts() {
	// return highest prioritized font if user has,
	// otherwise return false
	var font, fontPriority;
	var currentPriority = -10;
	for (var i=0; i < tp_FONTLIST.length; i++) {
		if (tp_FONTLIST[i][tp_USERHAS]) {
			fontPriority = tp_FONTLIST[i][tp_PRIORITY];
			if (fontPriority > currentPriority) {
				font = tp_FONTLIST[i][tp_FONTNAME];
				currentPriority = fontPriority;
			}
		}
	}
	if (font) {return font;}
	return false;
}

function tp_indexOfTibetanFont(fontName) {
	for (var i=0; i < tp_FONTLIST.length; i++) {
		if (tp_FONTLIST[i][tp_FONTNAME] == fontName) {return i;}
	}
	return false;
}

function tp_createCSStextByFontName(fontName) {
	var index = tp_indexOfTibetanFont(fontName);
	var cssRule = "";
	if (index !== false) {
		cssRule =  'font-family: "'   + tp_FONTLIST[index][tp_FONTNAME] + '"; ';
		if (tp_bReadjust) {
			cssRule += 'font-size: '      + (tp_FONTLIST[index][tp_FONTSIZE] * tp_fontMultiplier) + '%; ';
			cssRule += 'line-height: '    + tp_FONTLIST[index][tp_LINEHEIGHT] + '%; ';
			cssRule += 'vertical-align: ' + tp_FONTLIST[index][tp_VERTICALALIGN] + '%; ';
		}
	}
	if (tp_noBold) {
		cssRule += 'font-weight: normal; ';
	}
	var u = com.tp.User;

	// firefox 3 won't justify, but won't break like firefox 2
	if (u.getBrowserBreaksUCStibetanJustification()) {
		cssRule += 'text-align: left; '; 
	}
	// cssRule += 'background-color: yellow;' ;
	// Firefox (and others?) can't have weird letter spacing in Tibetan
	cssRule += 'letter-spacing: normal; ';
	// Tibetan doesn't do 'small-caps', will screw up if in the cascade
	cssRule += 'font-variant: normal; ';
	return cssRule;
}

	// **********************************************************
	// Create a StyleSheet for com-tp-bo
function tp_createTibetanStyleSheet() {
	var General = com.tp.General;
	General.createStyleSheetByTitle('com_tp_bo_stylesheet');
}
	//***********************************************************
	// 	Remove and Udpate Tibetan style based on font name
function tp_appendTibetanStyleByFont(fontName) {
	var cssSelector = ".com-tp-bo";
	var cssRule = tp_createCSStextByFontName(fontName);
	var sStyleSheet = 'com_tp_bo_stylesheet';
	var g = com.tp.General;
	g.appendStyleSheetByTitle(cssSelector, cssRule, sStyleSheet);
}

function tp_replaceTibetanStyleByFont(fontName) {
	var cssSelector = ".com-tp-bo";
	var cssRule = tp_createCSStextByFontName(fontName);
	var sStyleSheet = 'com_tp_bo_stylesheet';
	var g = com.tp.General;
	g.replaceStyleSheetByTitle(cssSelector, cssRule, sStyleSheet);
}

function tp_correctForTibetanFormInput() {
	if (!tp_currentFont) { return; }
	// later make this only apply to nodes with a certain class name
	// like "com-tp-boFormElement"
	// ALSO, this should be made to work after the select Tibetan font box is updated
	
	// actually, I don't need to change all INPUT elements to BUTTON because this
	// routine takes care of it!
	var d = document;
	var aTags;
	var nIndex;
	var aElements = ["textarea", "input"];
	for (var i = 0; i < aElements.length; i++) {
		// this is not working in Opera, can't resize?
		aTags = d.getElementsByTagName(aElements[i]);
		for (var i2 = 0; i2 < aTags.length; i2++) {
			nIndex = tp_indexOfTibetanFont(tp_currentFont);
			//aTags[i2].style.fontFamily = tp_FONTLIST[nIndex][tp_FONTNAME];
			//aTags[i2].style.fontSize = (tp_FONTLIST[nIndex][tp_FONTSIZE] * 0.9) + "%";
			var font = tp_FONTLIST[nIndex][tp_FONTNAME];
			var size = (tp_FONTLIST[nIndex][tp_FONTSIZE] * 0.9) + "%";
			aTags[i2].onfocus = function() {
				this.style.fontFamily = font;
				this.style.fontSize = size;
			};
			aTags[i2].onblur = function() {
			//	this.style.fontFamily = "";
			//	this.style.fontSize = "";
			};
		}
	}
}
// Select Box Font Change
tp_onchangeTibetanStyleByFont = function(e) {
	var d = document;
	var g = com.tp.General;
	if (!e) {e = window.event;}
	var o = (e.srcElement)?(e.srcElement):(e.target);
	var fontName = o.options[o.selectedIndex].text;
	
	if (fontName.indexOf("(") > -1) {
		fontName = fontName.replace(/ \(.*\)/, "");	
	}
	if (fontName.indexOf("+") > -1) {
		fontName = fontName.replace(/\+/g, "");
		tp_embedFont(fontName);
	}	
	
	if (fontName.indexOf("*") > -1) {
		fontName = fontName.replace(/\*/g, "");
			// var s = "You don't appear to have %fn loaded.\n\nYour Tibetan font sizes and line adjustments may\nlook a little strange after applying the style\nrules for this font.\n\nIf you justed installed %fn,\nplease restart your browser to make it available.\n\nProceed with style changes anyway?\n\n(Press 'Cancel' to return without changing anything)";
			// s = s.replace(/\%fn/g, fontName); 
			// if (!confirm(s)) {return;}
		var s = "The %fn font is either not installed\non your system or is unavailable\nfor embedding in this browser.\n\nIf you just installed %fn,\nplease quit and restart your browser.\nYou can then try to select this font again.";
		s = s.replace(/\%fn/g, fontName);
		alert(s);
		// alert(tp_currentFont);

		// reselect the previous selection
		for (var i=0; i < tp_FONTLIST.length; i++) {
			s = tp_FONTLIST[i][tp_FONTNAME];
			if (s === tp_currentFont) {
				o.options[i].defaultSelected = true; // Opera needs
				o.options[i].selected = true;
			}
		}
		return;
	}
	/* if (fontName === "[ font help... ]") {
		s = '>> Help!... ';
		alert(s);
	} */
	else {
		if (!g.getStyleSheetByTitle('com_tp_bo_stylesheet')) {
			return false;
		}
		else {
			tp_replaceTibetanStyleByFont(fontName);
			tp_myCookie.font = fontName;
			tp_currentFont = fontName;
			tp_myCookie.store(365, "/", tp_cookieDomain);
		}

		// fine the spans
		var cf = "tpf-" + tp_currentFont.replace(/ /g, "");
		if (d.body.className.match(/tpf-/)) {
			d.body.className = d.body.className.replace(/tpf-.*/, cf);
		}
		else {
			d.body.className += " "+cf;
		}
		// correct font for forms and inputs
		tp_correctForTibetanFormInput();

		if (tp_bFineTune) {
			// get rid of spaces in fontname, single for cssclasname
			for (var i=0; i<tp_aFineTuneSpans.length; i++) {
				tp_aFineTuneSpans[i].className = cf;	
			}
		}
	}
};

	/************************************************************************************
		Tibetan SPAN and WBR function
	************************************************************************************/	
function tp_tibetanSpansAndLineBreaks(node) {
	var User = com.tp.User;
	var myNodes = [];
	var i, i2;
	if (!node) {node = document.body;} // default	
	var d = document;
	var clonedNode = node.cloneNode(true);	

	//*********************************
	// add filter to the TreeWalker
	var s = navigator.userAgent;
	if ((s.indexOf("compatible") > -1) && (s.indexOf("MSIE") > -1)) {
		// the IE way

		var aElements = clonedNode.all;
		var rSlash = /\//g;
		for (i = 0; i < aElements.length; i++) {
			if (aElements[i].nodeType == 1) {
				if (aElements[i].nodeName != "TEXTAREA" && aElements[i].nodeName != "INPUT" && aElements[i].nodeName != "EMBED" && aElements[i].nodeName != "OBJECT" && !rSlash.test( aElements[i].nodeName ) ) {
					myNodes.push(aElements[i]);
				}
			}
		}		
	}
	else {	
		var filter = {};
		// do not include TEXTAREA or INPUT nodes and her descendants
		filter.acceptNode = function (oNode) {
			if (oNode.nodeName == "TEXTAREA" || oNode.nodeName == "INPUT" ) {
				return NodeFilter.FILTER_REJECT;
			}
			// do not include elements with excluded classNames (and skip her children)
			var cn = oNode.className;
			if (cn && (cn.indexOf("com-tp-doNotProcess") > -1 )) {
				return NodeFilter.FILTER_REJECT;
			}
			// other than that, the element may be one we want to process
			return NodeFilter.FILTER_ACCEPT;
		};
			
		// only get the elements which are possible candidates
		//var walker = d.createTreeWalker2(clonedNode, NodeFilter.SHOW_ELEMENT, filter, false);
		var walker = new com.tp.General.TreeWalker(clonedNode, NodeFilter.SHOW_ELEMENT, filter, false);
		var fAddSpans, intoWBR, buggyBrowser;
		var oNode = walker.nextNode();	
		while(oNode) {
			if (oNode.nodeType != 1) {oNode = walker.nextNode(); continue;} // HACK HERE! TREEWALKER2 NOT WORKING FULLY
			myNodes.push(oNode);
			oNode = walker.nextNode();
		}
	}



	///////////////////////////////////////////////////
	// define function to bound Tibetan with SPANS

	try {
			// IE, MOZ, Safari, & Opera do fine with this, but Konqueror gives error when making the regular expression.
			// Konqueror (and Safari to some extent) have real problems with Tibetan codepoints in regular expressions
		
			// Safari can't handle simplified regex like: /((?:\s*[\u0f00-\u0fff]+\s*)+)/g
			var sRegExp = "((?: *(?:\u0f00";
			for (i=3841; i<4096; i++) {
				sRegExp += "|"+String.fromCharCode(i);
			}
			sRegExp += ")+ *)+)";
			var reSPAN = new RegExp(sRegExp, 'g');
			var withSPAN = '~@~span class="com-tp-bo" ';
			withSPAN += 'lang="bo" xml:lang="bo"~#~$1~@~\/span~#~';

			if (tp_bFineTune) {
				// get rid of spaces in fontname, single for cssclasname
				var cf = tp_currentFont.replace(/ /g, "");
				cf = "tpf-" + cf;
				withSPAN = '~@~span class="' + cf + '"~#~' + withSPAN;
				withSPAN += '~@~\/span~#~';
			}

			fAddSpans = function(sText) {
				return sText.replace(reSPAN, withSPAN);
			};
			buggyBrowser = false;
			intoWBR = "";
			
	}	catch (exception) {
			// set up browser to makes SPANs without using regular expressions.
			// Konqueror, ALSO since it doesn't break correctly on Tshegs, and only has buggy realization of the WBR tag,
			// needs to have the unicode character for breaking inserted into the WBR tag.
			// alert(exception.message); // Konqueror will say "Invalid regular expression"
			fAddSpans = tp_buggyBrowserReplace;
			intoWBR = '\u200b';
			buggyBrowser = true;
	}
	// find any tsheg, which is not followed by shad
	var reWBR = /(\u0f0b)(?=[^\u0f0d])/g; // Safari wants this as literal syntax, won't accept in constructor

	var withWBR = '\u0f0b~@~wbr~#~' + intoWBR + '~@~/wbr~#~';
	// do the replacing
	var sText = "";
	var child = {};
	for (i = 0; i < myNodes.length; i++) {
		if (myNodes[i].hasChildNodes()) {
			for (i2 = 0; i2 < myNodes[i].childNodes.length; i2++) {
				child = myNodes[i].childNodes[i2];
				var reNotWhiteSpace = /\S/g;
				if (child.nodeType == Node.TEXT_NODE && reNotWhiteSpace.test(child.nodeValue)) {
					sText = fAddSpans(child.nodeValue);
					if (!User.getBrowserKnowsToBreakAtTsheg()) {
						sText = sText.replace(reWBR, withWBR);
					}
					child.nodeValue = sText;
				}
			}
		}
	}
	var sINNER = "";	
	try {

		sINNER = clonedNode.innerHTML;

	} catch(err) {
		// IE error most likely caused by EMBED tags in HTML.
		// have to rewrite the embed tags manually to work
		// can't seem to read other attributes from EMBED object
		// beside height and width and src (no type, etc..)
		var o; // element in the loop
		for (i = 0; i < aElements.length; i++) {
			o = aElements[i];
			if (o.nodeType === 1) {
				if (o.nodeName === "EMBED") {
					s =  "~@~EMBED"; 
					s += " width="  + o.width;
					s += " height=" + o.height;
					s += " src="    + o.src;
					s += "/~#~";
					o.outerHTML = s;
				}
			}
		}
		sINNER = clonedNode.innerHTML; // try again with new nodes
	}

	var sLT = "~@~";
		var reLT = new RegExp(sLT, "g");
		sINNER = sINNER.replace(reLT, "<");
	var sGT = "~#~";
		var reGT = new RegExp(sGT, "g");
		sINNER = sINNER.replace(reGT, ">");
		
	node.innerHTML = sINNER;

	if (tp_bFineTune) {
		var cn; // classname
		var spans = node.getElementsByTagName( 'span' );
		for (i = 0; i < spans.length; i++) {
			cn = spans[i].className;
			if ( cn.indexOf( "tpf-" ) > -1 ) {
				// add to global container
				tp_aFineTuneSpans.push( spans[i] );
			}
		}
	}
}

	//*********************************
	// deal with buggy browser (Konqueror, but not Safari)
	// its inability handling Tibetan in Reg Expressions
	// and prioritizing regular space break over WBR
	
	/*
function tp_buggyBrowserReplace(sText) {
	var spanStatus = false;
	var rangeLower = 3840;
	var rangeUpper = 4095;
	var newStr = "";	
	for (i=0; i<sText.length; i++) {
		// if it's a Tibetan character:
		if ((sText.charCodeAt(i) >= rangeLower) && (sText.charCodeAt(i) <= rangeUpper)) {
			// if the SPAN tag is not open yet:
			if (!spanStatus) {
				newStr += '~@~span class="com-tp-bo" lang="bo" xml:lang="bo"~#~';
				spanStatus = true;
			}
			newStr += sText.charAt(i);
			// if we're at the last character:
			var checkAgainstMe = sText.length - 1;
			if (i == checkAgainstMe) {
				newStr += '~@~/span~#~';
				continue;
			}
		} else {
		// if it's a non-Tibetan character:
			// if the SPAN tag is open, close it:
			if (spanStatus) {
				newStr += '~@~/span~#~';
				spanStatus = false;
			}
			newStr += sText.charAt(i);
		}
	}
	// put outside white space inside the SPAN tag
	newStr = newStr.replace(/(\s+)(~@~span class\=\"com\-tp\-bo\" lang\=\"bo\" xml\:lang\=\"bo\"~#~)/g, '$2$1');
	newStr = newStr.replace(/(~@~\/span~#~)(\s+)/g, '$2$1');	
	return newStr;
} 
*/
// automatic load ***********************************************************


function tp_fullAutomatic(correctForms, embedFonts, sCookieDomain, bReadjust, nReadjust) {
	tp_currentHash = window.location.hash;
	var isOpera = false; // Opera seems to be bahving correctly is spans done at end

	tp_bReadjust = bReadjust;

	if (nReadjust) {
		for (var i=0; i<tp_FONTLIST.length; i++) {
			tp_FONTLIST[i][tp_FONTSIZE] = ( tp_FONTLIST[i][tp_FONTSIZE] ) * nReadjust;
       		 }
	}

	if (embedFonts) {
		tp_embedFonts = true;
	}
	if (correctForms) {
		tp_bcorrectForTibetanFormInput = true;
	}
	if (sCookieDomain) {
		tp_cookieDomain = sCookieDomain;
	}
	
	var d = document;
	var u = com.tp.User;
	var font;
	var Cookie = com.tp.Cookie;
	tp_myCookie = new Cookie("com_tp_cookie");
	tp_addFontSelectContainerForMediaWiki();
	tp_updateFONTLISTbyFontAvailability();

	// Safari needs to do this first, before stylesheet change.
	if ( isOpera ) {
 		tp_tibetanSpansAndLineBreaks(document.body); // OPERA NEEDS THIS FIRST-QUIRKS
	}
	// FIREFOX WOULD LIKE IT LATER
	
	tp_createTibetanStyleSheet(); 
	
	// What to do if a font cookie is set
	if (tp_myCookie.font !== undefined) {
		// there is a pre-set font defined in the cookie
		font = tp_myCookie.font;
		
		// embed if necessary
		var nIndex = tp_indexOfTibetanFont(font);
		if (nIndex) {
			// should we, can we, and is the font embeddable?
			if (tp_embedFonts && u.getBrowserCanEmbedFonts() && tp_FONTLIST[nIndex][tp_EMBEDDABLE]) {
				tp_embedFont(font);
			}
		}
	}
	
	// What to do if a font cookie is not set
	else {
		font = tp_checkUsersTibetanFonts();
		
		// if no font on user's computer, but we have IE
		// we should at least embed Tib-US Unicode
		if ( tp_embedFonts && !font && u.getBrowserCanEmbedFonts() ) {
			font = "Tib-US Unicode";
			tp_embedFont(font);
		}
	}

	if (font) {
		// store the font name if not already
		if (tp_myCookie.font !== font) {
			tp_myCookie.font = font;
			tp_myCookie.store(365, "/", tp_cookieDomain);
		}
		tp_currentFont = font;
		tp_appendTibetanStyleByFont(font);
	}
	
	// if firefox
	/* var nothing = d.createElement( 'div' );
	var text = d.createTextNode( 'hey' );
	nothing.appendChild( text );
	var tempobject = d.body.insertBefore( nothing, d.body.firstChild );
	tempobject.style.height = "200px";
	tempobject.innerHTML = "please kill me......";
	d.body.removeChild( tempobject ); */

	// doing later for other non-Opera browers
	if ( !isOpera ) {
 		tp_tibetanSpansAndLineBreaks(document.body); // OPERA NEEDS THIS FIRST-QUIRKS
	}

	tp_populateFontSelectContainer();
	// I depend on the above routine to draw the screen, which is vital to
	// Firefox 2 (scrunched text), so this means user of script *must* have
	// the com_tp_fontSelectContainer object for this to work in FF 2.
	// of course, then could always hide it with CSS.

	if (tp_bcorrectForTibetanFormInput) {
		tp_correctForTibetanFormInput();
	}
	// turn off Javascript needed message (Safari needs this to come at end of routine)
	var jsOn = d.getElementById("com_tp_usingJavascript");
	if (jsOn) {
		jsOn.style.display = "none";
	}

	var cf = "tpf-" + tp_currentFont.replace(/ /g, "");
	if (d.body.className.match(/tpf-/)) {
		d.body.className = d.body.className.replace(/tpf-.*/, cf);
	}
	else {
		d.body.className += " "+cf;
	}

	// after redraw, then go to the intended hash;
	if (tp_currentHash) {
		window.location.hash = tp_currentHash;
	}
	// is there a global function called tp_onComplete?
	if (window.tp_onComplete) {
		// if yes, call it
		tp_onComplete();
	}
}
function tp_fullChrisAutomatic() {
	// automatic domain cookie assertion
	var hn = window.location.hostname;
	// take out the beginning www if there
	hn = hn.replace(/(www\.)?(.*)/, "$2");	
	tp_fullAutomatic( false, true, hn , true, 0 );
}
function tp_fullSuperAutomatic() {
	var reAd;
	if (!window.tp_nReadjustME) {
		reAd = 0;
	}
	else {
		reAd = tp_nReadjustME;
	}
	// automatic domain cookie assertion
	var hn = window.location.hostname;
	// take out the beginning www if there
	hn = hn.replace(/(www\.)?(.*)/, "$2");	
	tp_fullAutomatic( false, true, hn , true, reAd );
}

/**
You don't appear to have %fn loaded.

Your Tibetan font sizes and line adjustments may
look a little strange after applying the style
rules for this font.

If you justed installed %fn,
please restart your browser to make it available.

Proceed with style changes anyway?
*/

/**
>> Help! The Tibetan on this page is malformed, or
you are getting boxes where Tibetan should be!"

First, you can download and install Unicode Tibetan
fonts from the Internet. For download information,
please go to http://thdl.org (Tools>Fonts>Tibetan
Fonts).

Among your choices, the free "Jomolhari" font is
especially well-suited for the Internet.

Windows Users! :
Regardless of the Unicode Tibetan Font installed,
you should be using Microsoft Vista to render it
correctly. XP users CAN get the same
functionality by upgrading their "Uniscribe"
system resource. See above URL.      

Mac OS X Users! :
The currently free "Opentype" Unicode Tibetan
fonts do not render quite right on Mac OS X,
even though you can install most of them on
your system. However, a commercial vendor,
XenoType Technologies, offers some nice "ATT"
Unicode Tibetan fonts which will work well
(both dbu-chen and dbu-med). Visit
http://xenotypetech.com

Linux Users!:
You can use the freely available "Opentype"
Unicode fonts, but you should be using a
suitable version of Pango (GNOME) or Qt (KDE),
and your application should be calling the
smart rendering abilities of those libraries.
*/

