// Configuration
var _wrs_conf_editorEnabled = true;		// Specifies if fomula editor is enabled
var _wrs_conf_CASEnabled = true;		// Specifies if WIRIS cas is enabled

var _wrs_conf_imageMathmlAttribute = 'alt';	// Specifies the image tag where we should save the formula editor mathml code. In this integration, we use _wrs_temporalImage to comunicate the mathml to the formula editor window.
var _wrs_conf_CASMathmlAttribute = 'alt';	// Specifies the image tag where we should save the WIRIS cas mathml code. In this integration, we use _wrs_temporalImage to comunicate the mathml to the formula editor window.

var _wrs_conf_editorPath = _wrs_currentPath + '/pluginwiris/integration/editor.php';	// Specifies where is the editor HTML code (for popup window)
var _wrs_conf_editorAttributes = 'width=500, height=400, scroll=no, resizable=yes';							// Specifies formula editor window options.
var _wrs_conf_CASPath = _wrs_currentPath + '/pluginwiris/integration/cas.php';			// Specifies where is the WIRIS cas HTML code (for popup window)
var _wrs_conf_CASAttributes = 'width=640, height=480, scroll=no, resizable=yes';		// Specifies WIRIS cas window options

var _wrs_conf_createimagePath = _wrs_currentPath + '/pluginwiris/integration/createimage.php';			// Specifies where is createimage script
var _wrs_conf_createcasimagePath = _wrs_currentPath + '/pluginwiris/integration/createcasimage.php';	// Specifies where is createcasimage script

var _wrs_conf_getmathmlPath = _wrs_currentPath + '/pluginwiris/integration/getmathml.php';				// Specifies where is getmathml script
var _wrs_conf_getlatexPath = _wrs_currentPath + '/pluginwiris/integration/getlatex.php';			// Specifies where is the getlatex script.

var _wrs_conf_saveMode = 'tags';					// this value can be 'tags', 'xml' or 'safeXml'.
//var _wrs_conf_parseModes = ['latex'];				// This value can contain 'latex'.

// Vars
var _wrs_int_editorIcon = _wrs_currentPath + '/pluginwiris/core/wiris-formula.gif';
var _wrs_int_CASIcon = _wrs_currentPath + '/pluginwiris/core/wiris-cas.gif';
var _wrs_int_temporalTextarea;
var _wrs_int_window;
var _wrs_int_window_opened = false;
var _wrs_int_temporalFile;
var _wrs_int_language;

if (navigator.userLanguage) {
	_wrs_int_language = navigator.userLanguage;
}
else if (navigator.language) {
	_wrs_int_language = navigator.language.substring(0, 2);
}
else {
	_wrs_int_language = 'en';
}

_wrs_temporalImage = document.createElement('img');

var _wrs_int_editBox = document.createElement('div');
_wrs_int_editBox.style.textAlign = 'center';
_wrs_int_editBox.style.borderWidth = '2px';
_wrs_int_editBox.style.borderStyle = 'solid';
_wrs_int_editBox.style.padding = '4px';
_wrs_int_editBox.style.backgroundColor = '#ffe2ab';
_wrs_int_editBox.style.position = 'absolute';
_wrs_int_editBox.style.opacity = 0.75;
_wrs_int_editBox.style.filter = 'alpha(opacity=75)';
_wrs_int_editBox.style.display = 'none';


var _wrs_int_editBox_img = document.createElement('img');
_wrs_int_editBox_img.style.margin = 'auto';
_wrs_int_editBox_img.style.display = 'block';
_wrs_int_editBox.appendChild(_wrs_int_editBox_img);

var _wrs_int_editBox_link = document.createElement('a');
_wrs_int_editBox_link.style.margin = '25px';
_wrs_int_editBox_link.href = 'javascript:;';
_wrs_int_editBox_link.innerHTML = 'Edit';
_wrs_int_editBox.appendChild(_wrs_int_editBox_link);

wrs_addEvent(window, 'load', function () {
	document.body.appendChild(_wrs_int_editBox);
});

// Plugin integration

/**
 * Inits the WIRIS plugin for this demo.
 * @param string target Textarea target ID.
 */
function wrs_int_init(target) {
	/* Creating textarea events */
	var textarea = document.getElementById(target);
	wrs_addTextareaEvents(textarea, wrs_int_clickHandler);
	
	/* Creating toolbar buttons */
	var toolbar = document.createElement('div');
	
	if (_wrs_conf_editorEnabled) {
		var formulaButton = document.createElement('img');
		formulaButton.src = _wrs_int_editorIcon;
		formulaButton.style.cursor = 'pointer';
		
		wrs_addEvent(formulaButton, 'click', function () {
			wrs_int_openNewFormulaEditor(textarea);
		});
		
		toolbar.appendChild(formulaButton);
	}
	
	if (_wrs_conf_CASEnabled) {
		var CASButton = document.createElement('img');
		CASButton.src = _wrs_int_CASIcon;
		CASButton.style.cursor = 'pointer';
		
		wrs_addEvent(CASButton, 'click', function () {
			wrs_int_openNewCAS(textarea);
		});
		
		toolbar.appendChild(CASButton);
	}
	
	textarea.parentNode.insertBefore(toolbar, textarea);
}

/**
 * Opens formula editor.
 * @param object textarea Target
 */
function wrs_int_openNewFormulaEditor(textarea) {
	if (_wrs_int_window_opened) {
		_wrs_int_window.focus();
	}
	else {
		_wrs_int_window_opened = true;
		_wrs_isNewElement = true;
		_wrs_int_temporalTextarea = textarea;
		_wrs_int_window = window.open(_wrs_conf_editorPath, 'WIRISFormulaEditor', _wrs_conf_editorAttributes);
	}
}

/**
 * Opens CAS.
 * @param object textarea Target
 */
function wrs_int_openNewCAS(textarea) {
	if (_wrs_int_window_opened) {
		_wrs_int_window.focus();
	}
	else {
		_wrs_int_window_opened = true;
		_wrs_isNewElement = true;
		_wrs_int_temporalTextarea = textarea;
		_wrs_int_window = window.open(_wrs_conf_CASPath, 'WIRISCAS', _wrs_conf_CASAttributes);
	}
}

/**
 * Checks if the input string is a space.
 * @param string input
 * @return bool
 */
function wrs_int_isSpace(input) {
	var spaceCharacters = new Array(' ', "\r", "\n", "\t", ',', '\'', '"', '(', ')', '<', '>', '[', ']');
	
	for (var i = 0; i < spaceCharacters.length; ++i) {
		if (input == spaceCharacters[i]) {
			return true;
		}
	}
	
	return false;
}

/**
 * Returns the current word on the specified position of a text.
 * @param string text
 * @param int position
 * @return hash A has with these values:
 *	int beginPosition: the position of the first character of the current word
 *	int endPosition: the position of the last character of the current word
 *	string value: the current word
 */
function wrs_int_getCurrentWord(text, position) {
	if (position == 0 || wrs_int_isSpace(text.charAt(position - 1)) || wrs_int_isSpace(text.charAt(position)) || position == text.length) {
		return {
			'beginPosition': position,
			'endPosition': position,
			'value': ''
		};
	}

	var beginPosition = position;
	var found = false;
	
	while (beginPosition > 0 && !found) {
		if (wrs_int_isSpace(text.charAt(beginPosition - 1))) {
			found = true;
		}
		else {
			--beginPosition;
		}
	}
	
	var endPosition = position;
	found = false;
	
	while (endPosition < text.length && !found) {
		if (wrs_int_isSpace(text.charAt(endPosition))) {
			found = true;
		}
		else {
			++endPosition;
		}
	}
	
	var word = text.substring(beginPosition, endPosition);

	return {
		'beginPosition': beginPosition,
		'endPosition': endPosition,
		'value': word
	};
}

function wrs_int_onEditBoxLinkClick() {
	if (_wrs_int_window_opened) {
		_wrs_int_window.focus();
	}
	else {
		var httpRequest = wrs_createHttpRequest();
		
		if (httpRequest) {
			var position = _wrs_int_temporalFile.indexOf('?');
			var fileName = _wrs_int_temporalFile.substr(0, position);
			var query_length = position + '?formula='.length;
			var isCAS;
			var md5;
			
			if (fileName == 'showimage.php') {
				md5 = _wrs_int_temporalFile.substr(query_length, 32);		// Getting formula md5
				isCAS = false;
			}
			else {
				md5 = _wrs_int_temporalFile.substr(query_length, 32);		// Getting CAS md5
				isCAS = true;
			}
			
			var code = wrs_getCode('md5', md5);
			_wrs_temporalImage.setAttribute(_wrs_conf_imageMathmlAttribute, code);		// Setting image attribute with formula mathml
			
			if (isCAS) {
				wrs_int_openExistingCAS(_wrs_int_temporalTextarea);
			}
			else {
				wrs_int_openExistingFormulaEditor(_wrs_int_temporalTextarea);
			}
		}
		else {
			alert('Your browser is not compatible with AJAX technology. Please, use the latest version of Mozilla Firefox.');
		}
	}
	
	wrs_removeEvent(_wrs_int_editBox_link, 'click', wrs_int_onEditBoxLinkClick);
}

/**
 * Handles a click on the textarea
 * @param object textarea Target
 * @param object event Event triggered
 */
function wrs_int_clickHandler(textarea, event) {
	var selectionStart, selectionEnd, mouseX, mouseY;
	
	if (textarea.selectionStart != null) {
		selectionStart = textarea.selectionStart;
		selectionEnd = textarea.selectionEnd;
		mouseX = event.pageX;
		mouseY = event.pageY;
	}
	else {
		/* Get caret position, IE way */
		var range = document.selection.createRange();
		var duplication = range.duplicate();
		duplication.moveToElementText(textarea);
		duplication.setEndPoint('EndToEnd', range);
		
		selectionStart = duplication.text.length - range.text.length;
		selectionEnd = selectionStart + range.text.length;
		mouseX = event.clientX + document.body.scrollLeft;
		mouseY = event.clientY + document.body.scrollTop;
	}
	
	if (selectionStart == selectionEnd) {
		// Getting the word where the caret is over
		var currentWord = wrs_int_getCurrentWord(textarea.value, selectionStart);
		
		// Checking if is a WIRIS formula
		var paths = currentWord['value'].split('/');
		var protocol = paths[0];
		_wrs_int_temporalFile = paths[paths.length - 1];
		
		if ((protocol == 'http:' || protocol == 'https:')) {
			var position = _wrs_int_temporalFile.indexOf('?');
			var fileName = _wrs_int_temporalFile.substr(0, position);
			
			if (fileName == 'showimage.php' || fileName == 'showcasimage.php') {		// checks if is a WIRIS image
				// Displaying the editBox
				_wrs_int_editBox_img.src = currentWord['value'];
				_wrs_int_editBox.style.left = mouseX + 10 + 'px';
				_wrs_int_editBox.style.top = mouseY + 10 + 'px';
				_wrs_int_editBox.style.display = 'block';
				
				// Selecting textarea current word
				if (textarea.selectionStart != null) {
					textarea.selectionStart = currentWord['beginPosition'];
					textarea.selectionEnd = currentWord['endPosition'];
					event.stopPropagation();
				}
				else {
					var temporalText = textarea.value.substring(0, currentWord['beginPosition']);
					var difference = temporalText.split("\r").length - 1;
					currentWord['endPosition'] -= difference;
					currentWord['beginPosition'] -= difference;
					
					var range = textarea.createTextRange();
					range.collapse(true);
					range.moveStart('character', currentWord['beginPosition']);
					range.moveEnd('character', currentWord['endPosition'] - currentWord['beginPosition']);
					range.select();
					
					event.cancelBubble = true;
				}
				
				// Assinging events to the edit link
				_wrs_int_temporalTextarea = textarea;
				wrs_addEvent(_wrs_int_editBox_link, 'click', wrs_int_onEditBoxLinkClick);
				
				// Assinging document events for hide editBox when the user clicks the next time
				wrs_addEvent(document, 'click', wrs_int_documentActionHandler);
				wrs_addEvent(document, 'keydown', wrs_int_documentActionHandler);
			}
		}
	}
}

/**
 * Hiddes the editBox and removes itself from the document events.
 */
function wrs_int_documentActionHandler() {
	_wrs_int_editBox.style.display = 'none';
	
	wrs_removeEvent(_wrs_int_editBox_link, 'click', wrs_int_onEditBoxLinkClick);
	wrs_removeEvent(document, 'click', wrs_int_documentActionHandler);
	wrs_removeEvent(document, 'keypress', wrs_int_documentActionHandler);
}

/**
 * Opens formula editor to edit an existing formula.
 * @param object textarea Target
 */
function wrs_int_openExistingFormulaEditor(textarea) {
	_wrs_int_window_opened = true;
	_wrs_isNewElement = false;
	_wrs_int_temporalTextarea = textarea;
	_wrs_int_window = window.open(_wrs_conf_editorPath, 'WIRISFormulaEditor', _wrs_conf_editorAttributes);
}

/**
 * Opens CAS to edit an existing formula.
 * @param object textarea Target
 */
function wrs_int_openExistingCAS(textarea) {
	_wrs_int_window_opened = true;
	_wrs_isNewElement = false;
	_wrs_int_temporalTextarea = textarea;
	_wrs_int_window = window.open(_wrs_conf_CASPath, 'WIRISCAS', _wrs_conf_CASAttributes);
}

/**
 * Calls wrs_updateFormula with well params.
 * @param string mathml
 */
function wrs_int_updateFormula(mathml) {
	var text = window.location.protocol + '//' + window.location.host + wrs_createImageSrc(mathml);
	wrs_updateTextarea(_wrs_int_temporalTextarea, text);
}

/**
 * Calls wrs_updateFormula with well params.
 * @param string mathml
 */
function wrs_int_updateCAS(appletCode, image, width, height) {
	var text = window.location.protocol + '//' + window.location.host + wrs_createImageCASSrc(image, appletCode);
	wrs_updateTextarea(_wrs_int_temporalTextarea, text);
}

/**
 * Handles window closing.
 */
function wrs_int_notifyWindowClosed() {
	_wrs_int_window_opened = false;
}

