// Base class for page items handled by the Confluence plugin

function PageItem(name)
{
    this.commandName = name
}

// this method is passed the event
PageItem.prototype.OnClick = function( e )
{
    var target;

    //alert(DWRUtil.toDescriptiveString(e,2,1));
    if (!e.target)
    {
        // IE event model
        target = e.srcElement;
    }
    else
    {
        target = e.target;
    }
    this.selectNode(target);
}


// this method is passed the tag which has been clicked on
PageItem.prototype.OnDoubleClick = function( e )
{
    this.selectNode(e);
}

PageItem.prototype.findTarget = function(t)
{
    if (t == null)
    {
        return null;
    }
    else if (this.isOurNode(t))
    {
        return t;
    }
    else
    {
        return this.findTarget(t.parentNode);
    }
}

PageItem.prototype.selectNode = function(target)
{
    var a = this.findTarget(target);
    if ( a )
    {
        this.SelectedNode = a;
    }
    else
    {
        this.SelectedNode = undefined;
    }
    return this.SelectedNode;
}
ConfLink.prototype = new PageItem("ConfLink");

function ConfLink()
{
}
// Add a new element at the actual selection.
ConfLink.prototype.Add = function(link, show, tooltip, pageId )
{
	var oSpan = tinyMCE.selectedInstance.getDoc().createElement('A');
    this.SetupSpan(oSpan, link, show, tooltip, pageId) ;
    var range = tinyMCE.selectedInstance.getRng()
    if (tinyMCE.isMSIE)
    {
        range.pasteHTML(oSpan.outerHTML);
    }
    else
    {
        range.insertNode(oSpan);
    }

}

var replySpan;


ConfLink.prototype.reply_setupspan = function(html)
{
    if (html.indexOf('<p>') == 0)
    {
        html = html.substring(3);
    }
    if (html.lastIndexOf('</p>') == html.length - 4)
    {
        html = html.substring(0,html.length - 4);
    }
    // setOuterHTML
    if (tinyMCE.isMSIE)
    {
        replySpan.outerHTML = html;
    }
    else
    {
       //alert(DWRUtil.toDescriptiveString(replySpan));
       var r = replySpan.ownerDocument.createRange();
       r.setStartBefore(replySpan);
       var df = r.createContextualFragment(html);
       replySpan.parentNode.replaceChild(df, replySpan);
    }
}

// decode HTML encoded text
ConfLink.prototype.DecodeURI = function(encoded)
{
    return encoded;
}

// decode HTML encoded text
ConfLink.prototype.EncodeURI = function(unencoded)
{
    return unencoded;
}

ConfLink.prototype.SetupSpan = function(span, link, show, tooltip, pageId)
{
    replySpan = span;
    replySpan.innerHTML = show;
    span.setAttribute('linktype','raw');
	span.setAttribute('linktext',link);
	span.setAttribute('href','#');
	if (tooltip.length > 0)
	{
	    span.setAttribute('title', tooltip);
	}
    if (pageId)
    {
        DWREngine.setPostHook(this.DWRComplete);
        dwrInProgress = true;
        WysiwygConverter.convertWikiMarkupToXHtmlWithoutPage('[' + link + ']', pageId, this.reply_setupspan);
    }
}

ConfLink.prototype.DWRComplete = function()
{
    dwrInProgress = false;
}

ConfLink.prototype.isOurNode = function(t)
{
    return t.tagName == 'A' && t.getAttribute('linktext');
}

var  textField;

function reply_loadselected(markup)
{
    textField.value = markup;
}

ConfLink.prototype.LoadMarkup = function(xhtml, field, pageId)
{
    textField = field;
    if (pageId)
    {
        WysiwygConverter.convertXHtmlToWikiMarkupWithoutPage(xhtml, pageId, reply_loadselected);
    }
}

ConfLink.prototype.Ok = function(destinationStr, textStr, tooltipStr, eSelected, pageId)
{
    if ( destinationStr.length == 0 )
	{
		alert( tinyMCELang['lang_conflink_error_no_name'] ) ;
		return false ;
	}
	if ( tooltipStr.length > 0 && textStr.length == 0 )
	{
	    alert(tinyMCELang['lang_conflink_error_tooltip_requires_text']);
	    return false;
	}
	var linktext = destinationStr;
    var showtext = destinationStr;

	if (textStr.length > 0  && textStr != destinationStr)
	{
	    linktext = textStr + '|' + linktext;
	    showtext = textStr;
	}
	if (tooltipStr.length > 0)
	{
	    linktext = linktext + '|' + tooltipStr;
	}
    if (eSelected && !this.isOurNode(eSelected))
    {
        // we had a selection, but it wasn't an existing link
        // so delete the existing contents then add
        tinyMCE.selectedInstance.getRng().deleteContents();
        eSelected = null;
    }
    if (eSelected)
    {
        this.SetupSpan(eSelected, this.EncodeURI(linktext), showtext, tooltipStr, pageId ) ;
    }
    else
    {
	    this.Add(this.EncodeURI(linktext), showtext, tooltipStr, pageId) ;
	}
}
ConfImage.prototype = new PageItem("ConfImage");

function ConfImage()
{
    window.ConfImage = this;
}

ConfImage.prototype.Add = function( name, imagetext, pageNumber )
{
    // Regardless of how the image is being aligned, wrap it in a div, so the image has a parent node
    var div = tinyMCE.selectedInstance.getDoc().createElement('DIV');
    var oImg = tinyMCE.selectedInstance.getDoc().createElement('IMG');
    div.appendChild(oImg);

    this.SetupImg(oImg, name, imagetext, pageNumber) ;

    // Insert the div into the current range
    var range = tinyMCE.selectedInstance.getRng();
    if (tinyMCE.isMSIE)
    {
        range.pasteHTML(div.outerHTML);
    }
    else
    {
        range.insertNode(div);
    }
}


ConfImage.prototype.SetupImg = function(img, filename, imagetext, pageNumber)
{
    img.setAttribute("imagetext", imagetext);
    var location;
    if (this.imageProperties['thumbnail'])
    {
        location = 'thumbnails';
    }
    else
    {
        location = 'attachments';
    }
    var src;
    // check whether this is a remote image
    if (filename.indexOf("http://") != 0 && filename.indexOf("https://") != 0)
    {
        src = tinyMCE.getParam('context_path') + '/download/' + location + '/' + pageNumber + '/' + filename
    }
    else
    {
        src = filename;
    }
    img.setAttribute("src", src);

    if (this.imageProperties['align'])
    {
        img.setAttribute('align', this.imageProperties['align']);
    }
    else
    {
        img.removeAttribute('align');
    }
    this.adjustParent(this.imageProperties['align'], img);

    img.removeAttribute('width');
    img.removeAttribute('height');
}

ConfImage.prototype.adjustParent = function(alignment, imgTag)
{
    // If the image is centered...
    if (alignment && alignment == 'center')
    {
        // If the image is not centered already...
        if (!this.isCentered(imgTag))
        {
            // Set the alignment in the parent node
            var parent = imgTag.parentNode;
            parent.setAttribute('align', 'center');
        }
    }
    else
    {
        // If the image is currently centered, but should not be...
        if (this.isCentered(imgTag))
        {
            // Remove the align attribute
            var div = imgTag.parentNode;
            div.removeAttribute('align');
        }
    }
 }

 ConfImage.prototype.isCentered = function (imgTag)
 {
     if (imgTag.parentNode == undefined)
        return false;
     
     if (imgTag.parentNode.tagName == undefined)
         return false;

     if (imgTag.parentNode.tagName != 'DIV')
         return false;

     return imgTag.parentNode.getAttribute('align') == 'center';
 }

ConfImage.prototype.isOurNode = function (t)
{
    return t.tagName == 'IMG' && t.getAttribute('imagetext');
}

ConfImage.prototype.Ok = function (fileName, thumbnail, alignment, tag, pageId)
{
    if (this.imageProperties == undefined)
    {
        this.imageProperties = new Object();
    }

    this.imageProperties['fileName'] = fileName;
    this.imageProperties['thumbnail'] = thumbnail;
    if (alignment == 0)
    {
        this.imageProperties['align'] = undefined;
    }
    else if (alignment == 1)
    {
        this.imageProperties['align'] = 'left';
    }
    else if (alignment == 2)
    {
        this.imageProperties['align'] = 'center';
    }
    else if (alignment == 3)
    {
        this.imageProperties['align'] = 'right';
    }
    var imagetext = this.createImageTextFromProperties();
    if (tag)
    {
        this.SetupImg(tag, fileName, imagetext, pageId );
    }
    else
    {
	    this.Add(fileName, imagetext, pageId);
	}
}

ConfImage.prototype.createImageTextFromProperties = function ()
{
    var imagetext = this.imageProperties['fileName'];
    var sep = '|';
    for (var i in this.imageProperties)
    {
        if (i != 'fileName')
        {
            var value = null;
            if (this.imageProperties[i] != null)
            {
                if (this.imageProperties[i] === true)
                {
                    value = i;
                }
                else if (this.imageProperties[i] !== false)
                {
                    value = i + '=' + this.imageProperties[i];
                }
                if (value)
                {
                    imagetext = imagetext + sep + value;
                    sep = ','
                }
            }
        }
    }
    return imagetext;
}
String.prototype.trim = function()
{
	return this.replace( /(^\s*)|(\s*$)/g, '' ) ;
}
/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('confluence', 'en');

tinyMCE.confLink = new ConfLink();
tinyMCE.confImage = new ConfImage();

function TinyMCE_emotions_getInfo() {
	return {
		longname : 'Confluence',
		author : 'Atlassian',
		authorurl : 'http://atlassian.com',
		infourl : 'http://atlassian.com/software/confluence',
		version : '1.0'
	};
};

/**
 * Returns the HTML contents of the emotions control.
 */
function TinyMCE_confluence_getControlHTML(control_name) {
	switch (control_name) {
    case "conflink":
        return '<img id="{$editor_id}_conflink" src="{$pluginurl}/images/conflink.gif" title="{$lang_conflink_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');tinyMCE.execInstanceCommand(\'{$editor_id}\',\'conflink\');">';
    case "confimage":
        return '<img id="{$editor_id}_confimage" src="{$pluginurl}/images/confimage.gif" title="{$lang_confimage_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');tinyMCE.execInstanceCommand(\'{$editor_id}\',\'confimage\');">';
	}

	return "";
}

function TinyMCE_confluence_doExecCommand(editor_id,actionName)
{
    var template = new Array();	// Handle commands
        template['file'] = tinyMCE.getParam('context_path') + '/users/' + actionName + '.action?pageId=' + tinyMCE.getParam('page_id') + '&currentspace=' +
tinyMCE.getParam('space_key') + '&formname=' + tinyMCE.getParam('form_name') + '&fieldname=' + tinyMCE.getParam('field_name') + '&mode=search';
        template['width'] = 620;
        template['height'] = 550;

        tinyMCE.openWindow(template, {editor_id : editor_id, inline : "yes", resizable : "yes", scrollbars: "yes"});
}

/**
* Executes the mceEmotion command.
*/
function TinyMCE_confluence_execCommand(editor_id, element, command, user_interface, value) {

	switch (command) {
    case "conflink":
        TinyMCE_confluence_doExecCommand(editor_id,'wysiwyginsertlink');
        return true;
    case "confimage":
        TinyMCE_confluence_doExecCommand(editor_id,'wysiwyginsertimage');
        return true;
	}
	// Pass to next handler in chain
	return false;
}
