﻿var activeEditor = null;
function textEditor() {
	this.htmlSource = null;
	this.sourceDiv = null;
	this.edittopDiv = null;
	this.editbottomDiv = null;
	this.iframe = null;
	this.iframeContainer = null;
	this.textarea = null;
	this.articleId = null;
	this.textdivId = null;
	this.textdivName = null;
	this.saveButtonId = null;
	this.textmodeButtonId = null;
	this.htmlmodeButtonId = null;
	this.boldButtonId = null;
	this.italicButtonId = null;
	this.underlineButtonId = null;
	this.linkButtonId = null;
	this.controlId = null;
	this.editMode = null;
	this.textSaved = false;
	this.styles = null;
	this.toolbarId = null;
	this.activeTextrange = null;
	this.requiresReload = false;
	this.dataInput = null;
	this.create = function(article_id, textdiv_id, caller, control_id, data_id) {
		if (document.designMode) {
			if (caller != null)
				caller.style.display = 'none';
			this.articleId = article_id;
			this.textdivId = textdiv_id;
			var textdiv_segments = textdiv_id.split("_");
			this.textdivName = textdiv_segments[textdiv_segments.length - 1];
			this.sourceDiv = document.getElementById(textdiv_id);
			this.edittopDiv = document.getElementById(textdiv_id + '_top');
			this.editbottomDiv = document.getElementById(textdiv_id + '_bottom');
			//this.saveButtonId = textdiv_id + '_top_save';
			this.textmodeButtonId = textdiv_id + "_bottom_textmode";
			this.htmlmodeButtonId = textdiv_id + "_bottom_htmlmode";
			this.boldButtonId = textdiv_id + "_top_bold";
			this.italicButtonId = textdiv_id + "_top_italic";
			this.underlineButtonId = textdiv_id + "_top_underline";
			this.linkButtonId = textdiv_id + "_top_link";
			this.controlId = control_id;
			this.styles = document.getElementById(textdiv_id + '_top_styles');
			this.toolbarId = control_id + '$top$toolbar';
			this.textarea = document.getElementById(textdiv_id + '_textarea');
			iframeObject = document.getElementById(textdiv_id + '_iframe');
			this.iframeContainer = iframeObject;
			if (iframeObject.contentWindow)
				this.iframe = iframeObject.contentWindow;
			else
				this.iframe = iframeObject;
			this.iframeContainer.style.display = "block";
			this.htmlSource = this.sourceDiv.innerHTML;
			this.sourceDiv.style.display = 'none';
			this.edittopDiv.style.display = 'block';
			this.editbottomDiv.style.display = 'block';
			this.iframe.document.designMode = 'on';
			this.editMode = "text";
			this.dataInput = document.getElementById(data_id);
			this.updateIframe();
		}
	}
	this.updateIframe = function() {
		this.iframe.document.open();
		this.iframe.document.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n' +
			'<html xmlns="http://www.w3.org/1999/xhtml">\r\n' +
			'<head>\r\n' +
			'<title>Editor</title>\r\n' +
			'<link rel="stylesheet" type="text/css" href="' + editorStylesheet + '" />\r\n' +
			'</head>\r\n' +
			'<body class="' + this.sourceDiv.className + '">\r\n');
		this.iframe.document.writeln(this.htmlSource);
		this.iframe.document.writeln('</body>\r\n'+
			'</html>');
		this.iframe.document.close();
        if (this.iframe.document.addEventListener) {
            this.iframe.document.addEventListener('mouseup', updateState, false);
            this.iframe.document.addEventListener('keyup', updateState, false);
        }
        else if (this.iframe.document.attachEvent) {
            this.iframe.document.attachEvent('onmouseup', updateState);
            this.iframe.document.attachEvent('onkeyup', updateState);
        }
	}
	this.execCmd = function(command, option) {
		try {
			this.iframe.document.execCommand(command, false, option);
		}
		catch(error) {
			alert('execCommand: ' + command + ' is not supported.');
		}
		this.updateState();
	}
	this.updateState = function() {
	    this.contentSaved = false;
	    if (this.iframe.document.queryCommandState) {
	        if (this.iframe.document.queryCommandState('Bold'))
	            AdminButton_changeFace(this.boldButtonId, 'down');
	        else
	            AdminButton_changeFace(this.boldButtonId, 'up');
	        if (this.iframe.document.queryCommandState('Italic'))
	            AdminButton_changeFace(this.italicButtonId, 'down');
	        else
	            AdminButton_changeFace(this.italicButtonId, 'up');
	        if (this.iframe.document.queryCommandState('Underline'))
	            AdminButton_changeFace(this.underlineButtonId, 'down');
	        else
	            AdminButton_changeFace(this.underlineButtonId, 'up');
	    }
	    this.styles.selectedIndex = 0;
	    var selected_class = null;
        if (this.iframe.document.selection) {
            if (this.iframe.document.selection.type == 'Text') {
                var textrange = this.iframe.document.selection.createRange();
                if (textrange.parentElement() != null) {
                    selected_class = textrange.parentElement().className;
                }
            }
        }
        else if (this.iframe.getSelection) {
        /*
            var textrange = this.iframe.getSelection().getRangeAt(0);
            if (textrange.commonAncestorContainer != null) {
                selected_class = textrange.commonAncestorContainer.className;
            }
        */
        }
        if (selected_class != null) {
            for (i=0; i<this.styles.options.length; i++) {
                if (this.styles.options.item(i).value == selected_class)
                    this.styles.selectedIndex = i;
            }
        }
	}
	this.save = function() {
        //AdminButton_changeFace(this.saveButtonId, "down");
		if (this.editMode == "text")
		    this.dataInput.value = trimText(this.iframe.document.body.innerHTML);
		else if (this.editMode == "html")
		    this.dataInput.value = trimText(this.textarea.value);
		//AjaxService.ArticleSaveText(this.articleId, this.htmlSource, saveCallback);
	}
	this.saveCallback = function(result) {
	    this.contentSaved = true;
        //AdminButton_changeFace(this.saveButtonId, "up");
		if(result == "ok") {
		    if(this.requiresReload == true)
		        document.location.replace(document.location.href);
		}
		else {
			alert(result);
	    }
	}
	this.confirmSaveChanges = function() {
	    var savechanges = confirm('Spara ändringar?');
		if (savechanges) {
			this.save();
		}
		return savechanges;
	}
	this.close = function() {
		alert('close');
	    if (this.requiresReload == true)
	        return;
	    if (!this.contentSaved) {
	        if (this.confirmSaveChanges())
	            this.requiresReload = true;
		}
		if(this.requiresReload == false) {
		    activeEditor = null;
		    __doPostBack(this.controlId, 'refresh');
		}
	}
	this.switchMode = function(new_mode) {
	    if (new_mode == "html") {
	        this.htmlSource = trimText(this.iframe.document.body.innerHTML);
	        this.textarea.value = this.htmlSource;
	        AdminButton_changeFace(this.htmlmodeButtonId, "down");
	        AdminButton_changeFace(this.textmodeButtonId, "up");
	        this.iframeContainer.style.display = "none";
	        this.textarea.style.display = "block";
	        this.editMode = new_mode;
	    }
	    else if (new_mode == "text") {
	        this.htmlSource = trimText(this.textarea.value);
	        AdminButton_changeFace(this.htmlmodeButtonId, "up");
	        AdminButton_changeFace(this.textmodeButtonId, "down");
	        this.iframeContainer.style.display = "block";
	        this.textarea.style.display = "none";
	        this.updateIframe();
	        this.editMode = new_mode;
	    }
	}
	this.clearFormatting = function() {
		if (this.editMode == "text")
		    this.htmlSource = this.iframe.document.body.innerHTML;
		else if (this.editMode == "html")
		    this.htmlSource = this.textarea.value;
	    AjaxService.HtmlToText(this.htmlSource, clearFormattingCallback);
	}
	this.clearFormattingCallback = function(result) {
	    if(result.indexOf("<error>") != -1) {
	        alert(result)
	    }
	    else {
	        this.htmlSource = trimText(result);
		    if (this.editMode == "text")
		        this.updateIframe();
		    else if (this.editMode == "html")
		        this.textarea.value = this.htmlSource;
	    }
	        
	}
	this.changeClass = function(new_class) {
	    if (new_class != "") {
	        var newNode = this.iframe.document.createElement("span");
	        newNode.className = new_class;
	        if (this.iframe.document.selection) {
	            if (this.iframe.document.selection.type == 'Text') {
	                var textrange = this.iframe.document.selection.createRange();
        		    var cntnts = textrange.htmlText;
        		    if (textrange.parentElement() != null) {
        		        if (textrange.parentElement().outerHTML == cntnts) {
        		            textrange.moveToElementText(textrange.parentElement());
        		            cntnts = textrange.htmlText;
        		        }
        		    }
		            var startTag = /<span\s[^>]*>/ig;
		            var endTag = /<\/span>/ig;
		            cntnts = cntnts.replace(startTag, "");
		            cntnts = cntnts.replace(endTag, "");
    		        newNode.innerHTML = cntnts;
		            textrange.pasteHTML(newNode.outerHTML);
	            }
	        }
	        else if (this.iframe.getSelection) {
	            var textrange = this.iframe.getSelection().getRangeAt(0);
	            if (!textrange.collapsed) {
	                textrange.surroundContents(newNode);
	            }
	        }
	    }
	}
	this.getTextrange = function() {
	    var textrange = null;
	    if (this.iframe.document.selection) {
	        if (this.iframe.document.selection.type == 'Text') {
	            textrange = this.iframe.document.selection.createRange();
	            var cntnts = textrange.htmlText;
	            if (textrange.parentElement() != null) {
	                if (textrange.parentElement().outerHTML == cntnts) {
	                    textrange.moveToElementText(textrange.parentElement());
	                }
	            }
	        }
	        else {
	            textrange = this.iframe.document.selection.createRange();	            
	        }
	    }
	    else if (this.iframe.getSelection) {
	        textrange = this.iframe.getSelection().getRangeAt(0);
	    }
	    return textrange;
	}
	this.getSelectedText = function() {
        if (this.iframe.document.selection) {
            if (this.iframe.document.selection.type == 'Text') {
                var textrange = this.iframe.document.selection.createRange();
    		    return textrange.text;
            }
            else {
                return null;
            }
        }
        else if (this.iframe.getSelection) {
            var textrange = this.iframe.getSelection().getRangeAt(0);
            if (!textrange.collapsed) {
                return textrange.toString();
            }
            else {
                return null;
            }
        }
        else {
            return null;
        }
	}
	this.getSelectedHtml = function() {
        if (this.iframe.document.selection) {
            if (this.iframe.document.selection.type == 'Text') {
                var textrange = this.iframe.document.selection.createRange();
    		    return textrange.htmlText;
            }
            else {
                return null;
            }
        }
        else if (this.iframe.getSelection) {
            //html not yet supported
            var textrange = this.iframe.getSelection().getRangeAt(0);
            if (!textrange.collapsed) {
                return textrange.toString();
            }
            else {
                return null;
            }
        }
        else {
            return null;
        }
	}
	this.surroundContents = function(newNode, textrange) {
        if (this.iframe.document.selection) {
            if (this.iframe.document.selection.type == 'Text') {
    		    var cntnts = textrange.htmlText;
		        newNode.innerHTML = cntnts;
	            textrange.pasteHTML(newNode.outerHTML);
            }
        }
        else if (this.iframe.getSelection) {
            if (!textrange.collapsed) {
                textrange.surroundContents(newNode);
            }
        }
	}
	this.replaceContents = function(newNode, textrange) {
	    if (this.iframe.document.selection) {
	        if (textrange == null) {
	            this.appendContents(newNode);
	        }
	        else {
	            textrange.select();
	            try {
	                textrange.pasteHTML(newNode.outerHTML);	                
	            }
	            catch (error) {
	                alert(error.message);
	            }
	        }
	    }
	    else if (this.iframe.getSelection) {
	        textrange.deleteContents();
	        textrange.insertNode(newNode);
	    }
	}
	this.appendContents = function(newNode) {
        if (this.iframe.document.selection) {
            var textrange = this.iframe.document.body.createTextRange();
            textrange.move('textedit');
            textrange.select();
            try {
                textrange.pasteHTML(newNode.outerHTML);
            }
            catch(error) {
                alert(error.message);
            }
        }
        else if (this.iframe.getSelection) {
            //seems not needed
            //textrange.deleteContents();
            //textrange.insertNode(newNode);
        }
	}
	this.newLink = function() {	    
	    var selected_html = this.getSelectedHtml();
	    this.activeTextrange = this.getTextrange();
	    //editNewLink(selected_html);
	    __doPostBack(this.toolbarId, 'toolbar=link&action=newlink&text=' + escape(selected_html));
	}
	this.insertLink = function(new_url, new_text, new_target) {
	    var link = this.iframe.document.createElement("a");
	    link.href = new_url;
	    link.innerHTML = new_text;
	    if(new_target != "")
	        link.target = new_target;
	    this.replaceContents(link, this.activeTextrange);
	    this.activeTextrange = null;
        AdminButton_changeFace(this.linkButtonId, 'up');
	}
	this.insertLine = function() {	   
	    var line = this.iframe.document.createElement("hr");
	    line.className = "blackline";
	    this.appendContents(line);
	    //this.replaceContents(line, this.getTextrange());
	}
}
function editorActivate(articleId, textdivId, caller, controlId, dataId) {
	/*
	if (activeEditor != null) {
		activeEditor.close();
	}
	*/
	activeEditor = new textEditor();
	activeEditor.create(articleId, textdivId, caller, controlId, dataId);
}
function saveCallback(result) {
	if (activeEditor != null)
		activeEditor.saveCallback(result);
}
function clearFormattingCallback(result) {
	if (activeEditor != null)
		activeEditor.clearFormattingCallback(result);
}
function trimText(text) {
    text = text + "";
    startIndex = 0;
    endIndex = text.length;
    for (i=startIndex; i<text.length; i++) {
        if (text.charAt(i) == "\r" || text.charAt(i) == "\n" || text.charAt(i) == " ")
            startIndex = i + 1;
        else
            break;
    }
    for (i=endIndex - 1; i>=0; i--) {
        if (text.charAt(i) == "\r" || text.charAt(i) == "\n" || text.charAt(i) == " ")
            endIndex = i;
        else
            break;
    }
    return text.substring(startIndex, endIndex);
}
function updateState() {
    activeEditor.updateState();
}
