var js_debug = 0;

var FontClass;
var Font;
function init_font_class() {
	if (!window.FontClass) {
		FontClass = new Class({ 
			initialize: function() { 
				this.container = new Element('div');
				this.container.setStyles({ 
					fontFamily: 'serif',
					visibility: 'hidden',
					position: 'absolute', 
					left: '-1000px',
					top: '-1000px' 
				}); 
				this.detector = new Element('span');
				this.detector.setStyles({ 
					fontFamily: 'serif',
					fontSize: '72px'
				});
				this.detector.set('text', 'mmmmmmmmmml');
				this.container.appendChild(this.detector);	
				document.body.appendChild(this.container); 
				$extend(this, this.detector.getSize());
			}, 
			detect: function(font) { 
				var a = new Object;
				a.font = font;
				 var dimensions = this.detector.setStyles({ 
					fontFamily: '"$font"'.interpolate(a)
				 }).getSize(); 
				var targetClass = $(document.body).getElements('font');
				if (font == 'serif' || /^Times/i.test(font)) return true; 
				return (dimensions.x != this.x || dimensions.y != this.y); 
			} 
		});
	}
	if (!window.Font) {
		Font = new FontClass();
	}
	return Font;
}
window.addEvent('domready', init_font_class);

function display_system_conf_instr() {
	var platformName = 'other';
	if (Browser.Platform.win) platformName = 'win';
	if (Browser.Platform.mac) platformName = 'mac';
	if ($('system-conf-' + platformName)) {
		$('system-conf-' + platformName).setStyle('display', 'block');
	}
	$$('.instructions-' + platformName).each(function(el, i, array) {
		el.setStyle('display', 'block');
	})
}

var load_lang_css = function(lang_code) {
	var head = document.getElementsByTagName('head')[0];
	var cssNode = document.createElement('link');
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	var href = (isStatic) ? '' : '/';
	href += 'css/input.'+lang_code+'.css';
	cssNode.href = href;
	cssNode.media = 'screen';
	head.appendChild(cssNode);
}

var FontDetector = new Class({
	Implements: [Options, Events],
	options: {
		required_fonts: [],
		test_string: ''
	},
	testFonts: {
		arabic:     ['KacstBook NFLC', 'Geeza Pro', 'targetFontArabic'],
		bengali:    ['Rupali', 'SolaimanLipi', 'targetFontBengali'],
		burmese:    ['PadaukOT', 'Padauk', 'targetFontBurmese'],
		devanagari: ['Akshar Unicode', 'Jaipur Unicode NFLC', 'Devanagari MT', 'targetFontDevanagari', 'Jaipur'],
		ethiopic:   ['Ethiopia Jiret', 'targetFontEthiopic', 'targetFontEthiopicTTF'],
		gujarati:   ['Gujarati MT', 'Shruti'],
		thai:       ['Thonburi', 'Ayuthaya', 'Krungthep', 'Sathu', 'Silom', 'Garuda'],
		latin:		['Arial Unicode MS', 'Lucida Sans Unicode', 'Microsoft Sans Serif'],
		nastaliq:	['Nastaliq Unicode NFLC', 'Nastaliq Unicode NFLC TTF', 'Nastaliq Unicode NFLC EOT', 'Nafees', 'Nafees TTF'],
		generic:	['NonexistentFont']
	},
	initialize: function(options) {
		if (!window.FontClass) {
			init_font_class();
		}
		this.setOptions(options);
		if (!this.options.required_fonts || this.options.required_fonts.length == 0) {
			this.options.required_fonts = this.testFonts[this.options.script];
		}
	},
	hasFonts: function() {
		var required_fonts_available = [];
		for (i = 0; i < this.options.required_fonts.length; i++) {
			if (window.Font.detect(this.options.required_fonts[i])) {
				var index = required_fonts_available.length;
				required_fonts_available[index] = this.options.required_fonts[i];
			}
		}
		return (required_fonts_available.length > 0);
	}
});

var ScriptDetector = new Class({
	Implements: [Options, Events],
	options: {
		chars: ['&nbsp;', '&nbsp;'],
		required_fonts: [],
		script: 'generic'
	},
	testChars: {
		arabic:     ['&#x64A;',  '&#x629;'],
		bengali:    ['&#x995;',  '&#x9BF;'],
		burmese:    ['&#x1010;', '&#x102E;'],
		devanagari: ['&#x915;',  '&#x93F;'],
		gujarati:   ['&#xAAF;',  '&#xABF;'],
		nastaliq:   ['&#x644;',  '&#x6CC;'],
		thai:       ['&#xE17;',  '&#xE34;']
	},
	testFonts: {
		arabic:     ['KacstBook NFLC', 'Geeza Pro', 'targetFontArabic'],
		bengali:    ['Rupali', 'SolaimanLipi', 'targetFontBengali'],
		burmese:    ['PadaukOT', 'Padauk', 'targetFontBurmese'],
		devanagari: ['Akshar Unicode', 'Jaipur Unicode NFLC', 'Devanagari MT', 'targetFontDevanagari', 'Jaipur'],
		ethiopic:   ['Ethiopia Jiret', 'targetFontEthiopic', 'targetFontEthiopicTTF'],
		gujarati:   ['Gujarati MT', 'Shruti'],
		thai:       ['Thonburi', 'Ayuthaya', 'Krungthep', 'Sathu', 'Silom', 'Garuda'],
		latin:		['Arial Unicode MS', 'Lucida Sans Unicode', 'Microsoft Sans Serif'],
		nastaliq:	['Nastaliq Unicode NFLC', 'targetFontNastaliq', 'Geeza Pro'],
		generic:	['NonexistentFont']
	},
	initialize: function(options) {
		if (!window.FontClass) {
			init_font_class();
		}
		this.setOptions(options);
		if (this.options.required_fonts.length == 0) {
			this.options.required_fonts = this.testFonts[this.options.script];
		}
		this.chars = this.options.chars;	
		this.initializeElements();
		this.char1 = $('script-test-char1');
		this.char2 = $('script-test-char2');
		this.combo = $('script-test-char-both');
		this.charSpans = $('script-test-span-both').getElementsByTagName('SPAN');
	},
	destroy: function() {
		$('script-test').dispose();
	},
	initializeElements: function() {
		var div = new Element('div', {
			'id':     'script-test',
			'class':  'target',
			'styles': {
				'background-color': '#ddd',
				'position': 'absolute',
				'left':     '-1000px',
				'top':      '100px'
			}
		}).adopt(
			new Element('span', {
				'id':   'script-test-width',
				'styles': {'display': 'inline-block'}
			}).adopt(
				new Element('div', {
					'id': 'script-test-char1',
					'html': this.chars[0],
					'styles': {'float': 'left'}
				}),
				new Element('div', {
					'id': 'script-test-char2',
					'html': this.chars[1],
					'styles': {'float': 'left'}
				}),
				new Element('span', {
					'id': 'script-test-char-both',
					'styles': {'display': 'inline-block'},
					'html': this.chars[0] + this.chars[1]
				}),
				new Element('span', {'id': 'script-test-span-both'}).adopt(
					new Element('span', {'html':this.chars[0]}),
					new Element('span', {'html':this.chars[1]})
				)
			)
		);
		if (window.font_direction && window.font_direction == 'rtl') {
			div.setStyles({
				'direction': 'rtl',
				'text-align': 'right'
			});
		}
		document.getElementsByTagName('body')[0].appendChild(div);
		return div;
	},
	hasSupport: function() {
		var widths = {
			char1: (this.char1.offsetWidth) ? this.char1.offsetWidth : this.char1.getCoordinates().width,
			char2: (this.char2.offsetWidth) ? this.char2.offsetWidth : this.char2.getCoordinates().width,
			span1: (this.charSpans[0].offsetWidth) ? this.charSpans[0].offsetWidth : this.charSpans[0].getCoordinates().width,
			span2: (this.charSpans[1].offsetWidth) ? this.charSpans[1].offsetWidth : this.charSpans[1].getCoordinates().width,
			combo: (this.combo.offsetWidth) ? this.combo.offsetWidth : this.combo.getCoordinates().width
		};
		// Nastaliq is a special case, because it falls back to Arabic if it's not supported, and
		// if Arabic is supported then the test will come back as a false positive. With a Nastaliq font
		// (tested with 'Pak Nastaleeq', 'Nafees Nastaleeq', and 'Nastaliq Unicode NFLC'), the rendered 
		// combination of a and b is smaller width than either characters individually, so we test for this
		// condition.
		if (this.options.script == 'nastaliq') {
			return (widths.char1 > widths.combo && widths.char2 > widths.combo);
		}
		// Burmese currently won't work on the mac
		if (Browser.Platform.mac && this.options.script == 'burmese') return false;
		// If the proper fonts aren't installed, sometimes all characters can have zero width
		if (widths.char1 == 0 && widths.char2 == 0 && widths.combo == 0) return false;
		// Modifier characters in Thai (all browsers), Devanagari (FF), and Gujarati (FF) have zero-width
		if (widths.char1 == 0 || widths.char2 == 0) return true;
		// If the two characters combined are not equal to the sum of their parts, then the
		// fonts are being rendered properly
		if (widths.char1 + widths.char2 != widths.combo) return true;
		// For Firefox and IE. Unlike Safari, Firefox and IE will merge glyphs even if they're not in the same text node,
		// but are next to each other in elements with display:inline. Sometimes the widths of glyphA and glyphB rendered
		// independently will be the same as the combined glyph, but when looking at their individual spans in the combined
		// glyph one of them will have zero width.
		if (widths.span1 == 0 || widths.span2 == 0) return true;
		// If it hasn't passed any of the tests, the script isn't working
		return false;
	},
	hasFonts: function() {
		var required_fonts_available = [];
		for (i = 0; i < this.options.required_fonts.length; i++) {
			if (window.Font.detect(this.options.required_fonts[i])) {
				var index = required_fonts_available.length;
				required_fonts_available[index] = this.options.required_fonts[i];
			}
		}
		return (required_fonts_available.length > 0);
	}
});

function test_two_char_script_class(testChars) {
	if (!window.test_chars && !testChars) return false;
	var chars = (testChars) ? testChars : window.test_chars;
	if (chars.length == 3) return test_three_char_script_class();
	var required_fonts = (window.lang_fonts) ? lang_fonts : [];
	try {
		var scriptTest = new ScriptDetector({
			chars: chars,
			required_fonts: required_fonts,
			script: window.script_name
		});
		var fontsAvailable = scriptTest.hasFonts();
		var scriptSupported = scriptTest.hasSupport();
		scriptTest.destroy();
		// Kashmiri hack to see whether the Nastaliq font needs to be updated
		if (window.test_chars_lang_specific) {
			if (test_chars_lang_specific == chars) return scriptSupported;
			var langSupported = test_two_char_script_class(test_chars_lang_specific);
			show_hide_script_msgs(scriptSupported, fontsAvailable, langSupported);
		} else {
			show_hide_script_msgs(scriptSupported, fontsAvailable);
		}
	} catch(e) {
		if (window.js_debug && window.console && window.console.log) {
			console.log(e);
		}
		if ($('script-test-results')) {
			$('script-test-results').setStyles({'display': 'none'});
		}
		return false;
	}
}

function test_script_fonts() {
	if (!window.test_chars) return false;
	var required_fonts = (window.lang_fonts) ? lang_fonts : [];
	try {
		var scriptTest = new ScriptDetector({
			required_fonts: required_fonts,
			script: window.script_name
		});
		var fontsAvailable = scriptTest.hasFonts();
		scriptTest.destroy();
		// Ignore the results of script detection when just testing fonts
		var scriptSupported = true;
		show_hide_script_msgs(scriptSupported, fontsAvailable);
	} catch(e) {
		if (window.js_debug && window.console && window.console.log) {
			console.log(e);
		}
		if ($('script-test-results')) {
			$('script-test-results').setStyles({'display': 'none'});
		}
	}	
}


function test_three_char_script_class() {
	if (!window.test_chars) return false;
	var required_fonts = (window.lang_fonts) ? lang_fonts : [];
	if (test_chars.length < 2) {
		if (window.js_debug && window.console && window.console.warn) {
			console.warn("Insufficient length of test_chars for test_three_char_script_class()", test_chars);
		}
	}
	var c = test_chars;
	var char_pairs = [
		[c[0],      c[1]],
		[c[1],      c[2]],
		[c[0]+c[1], c[2]],
		[c[0],      c[1]+c[2]]
	];
	var scriptSupported = false;
	try {
		var fontTest = new FontDetector({ script: window.script_name });
		var fontsAvailable = fontTest.hasFonts();
		for (var i = 0; i < char_pairs.length; i++) {
			var scriptTest = new ScriptDetector({
				chars: char_pairs[i],
				required_fonts: required_fonts,
				script: window.script_name
			});
			var scriptSupported = scriptTest.hasSupport() || scriptSupported;
			scriptTest.destroy();	
		}
		show_hide_script_msgs(scriptSupported, fontsAvailable);
	} catch(e) {
		if (window.js_debug && window.console && window.console.log) {
			console.log(e);
		}
		if ($('script-test-results')) {
			$('script-test-results').setStyles({'display': 'none'});
		}
	}
}

function show_hide_script_msgs(scriptSupported, fontsAvailable, langSupported) {
	var scriptSupportId = (scriptSupported) ? 'script-supported' : 'script-not-supported';
	// Kashmiri hack to see whether the Nastaliq font needs to be updated
	if (typeof(langSupported) == 'boolean') {
		if (scriptSupported && !langSupported) {
			scriptSupportId = 'lang-not-supported';
			scriptSupported = false;
		}
	}
	var scriptImgPath = (window.scriptImgPath) ? window.scriptImgPath : 'img/font_instr';
	if (scriptSupported) {
		if ($('script-test-loading-img')) {
			$('script-test-loading-img').set('src', scriptImgPath+'/success.png');
		}
	} else {
		if ($('script-test-loading-img')) {
			// Some of the tests are not able to successfully detect font support on Safari
			if (Browser.Engine.webkit && Browser.Platform.mac && window.script_name!='burmese' && window.script_name!='nastaliq') {
				var img = 'unknown.png';
				scriptSupportId = 'script-support-unknown';
			} else {
				var img = 'failure.png';
			}
			$('script-test-loading-img').set('src', scriptImgPath+'/'+img);
		}
		if ($('script-instructions')) {
			$('script-instructions-link').setStyle('display', 'inline');
			$('script-instructions').setStyle('display', 'block');
		}
		scriptSupportId = (fontsAvailable) ? scriptSupportId : 'insufficient-fonts';
	}
	if ($(scriptSupportId)) {
		$(scriptSupportId).setStyle('display', 'block');
	}
	if ($('script-test-loading')) {
		$('script-test-loading').setStyles({'display': 'none'});
	}
}