/* $Id$ */

/**
 *Explanations for the parameters
 *location              -   Location of the editor, where to load
 *name & textAreaID     -   name and the id for the text area of the editor
 */
function openEditor(location,name,textAreaID,replyLinkLocation,editorMode,utilContLocation)
{
    var $toMask = location.show(); //make sure it is visible
    var $attachmentContainer = $toMask.next();
    var $ta = $('<textArea name = "' + name + '" id = "' + textAreaID + '" style = "width:100%;max-height:400px;min-height:200px;height:' + $toMask.innerHeight() + 'px"></textarea>');
    var originalValue = '';
    var appendSignature = true; 
    if(editorMode == "Edit" || name == "privateMsgContent")
    {
        appendSignature = false; 
    }
    else if($('#writeNewTopic').attr('isDraft') == "true")
    {
        appendSignature = false; 
    }
    if($toMask.is(':input'))
    {
	originalValue = $toMask.val();
    }
    else
    {
	originalValue = $toMask.html();
    }
    originalValue = ' ' + originalValue;
//dhan - remove the view code and edit code links.
    var temp_content = document.createElement ('div');
    temp_content.innerHTML = originalValue;
    $(temp_content).find('div.__zd_findAndReplace').remove();
    $(temp_content).find('div.__zd_findAndReplaceParent').remove();
    originalValue = temp_content.innerHTML;

    if(appendSignature == true)
    {
        originalValue = originalValue + userSignature;
    }
    $ta.val($.trim(originalValue));

    var $frm;
    
    if(replyLinkLocation)
    {
        $frm = $('<form id = "editorHolder"></form>');
        //this is the case where we are constructing editor for response or thread
        //for response we need some meta details like topicId, forumId,categoryId........
        //get those details from replyLinkLocation
        $replyLinkLocation = $('#'+replyLinkLocation);
        if(name == "privateMsgContent")
        {
            var toMember = $replyLinkLocation.attr('toMember');
            
            if(replyLinkLocation == "UserPM" || editorMode == "Edit")
            {   
                var postTitle = $replyLinkLocation.attr('postTitle');
                if(editorMode == "Edit")
                {
                    $frm.append('<input value="'+postTitle+'" name = "forumPostTitle" class="replyTextBox" type="text" style="width:98%;height:18px;padding:3px;margin:0px 0px 6px 0px;"/>')
                }
                else
                {
                    $frm.append('<input value="" name = "forumPostTitle" class="replyTextBox" type="text" style="width:98%;height:18px;padding:3px;margin:0px 0px 6px 0px;"/>')
                }
            }
            if(replyLinkLocation != "UserPM")
            {
                var forumTopicId = $replyLinkLocation.attr('forumTopicId');
                $frm.append('<input type = "hidden" name = "forumTopicId" value = "'  + forumTopicId + '">')
            }
            $frm.append('<input type = "hidden" name = "toMember" value = "'  + toMember + '">')
                .append('<input type = "hidden" name = "forumGroupId" value = "'  +forumGroupId+ '">')
                .append('<input type = "hidden" name = "'+ csrfParamName +'" value = "'+ csrfToken +'">')
            
                
        }//if(replyLinkLocation == "UserPM")
        else
        {
            var forumTopicId = $replyLinkLocation.attr('forumTopicId');
            forumTopicId = forumTopicId || $replyLinkLocation.parents('div[parentCont="actualParent"]').attr('forumTopicId');
            var responseId = $replyLinkLocation.attr('responseId');
            var isPrivate = $replyLinkLocation.attr('isPrivate');
            var isThread = $replyLinkLocation.attr('isThread');
            var forumId = $replyLinkLocation.attr('forumId');
            var categoryId = $replyLinkLocation.attr('categoryId');
            var postTitle = $replyLinkLocation.attr('postTitle');

            var responseAuthorId = $replyLinkLocation.attr('responseAuthorId');
            $frm.append('<input value="'+postTitle+'" name = "forumPostTitle" class="normalText" type="text" style="width:98.5%;height:18px;padding:3px;margin:0px 0px 6px 0px;"/>')
                .append('<input type = "hidden" name = "forumTopicId" value = "'  + forumTopicId + '">')    
                .append('<input type = "hidden" name = "responseId" value = "'  + responseId + '">')
                .append('<input type = "hidden" name = "forumGroupId" value = "'  +forumGroupId+ '">')
                .append('<input type = "hidden" name = "isPrivate" value = "'  + isPrivate + '">')
                .append('<input type = "hidden" name = "isThread" value = "'  + isThread + '">')
                .append('<input type = "hidden" name = "forumId" value = "'  + forumId + '">')
                .append('<input type = "hidden" name = "categoryId" value = "'  + categoryId + '">')
                .append('<input type = "hidden" name = "'+ csrfParamName +'" value = "'+ csrfToken +'">')
                .append('<input type = "hidden" name = "detectSpamPresence" value = "'  + 1 + '">')

            if((editorMode && editorMode == "Edit") && responseAuthorId == ZUID)
            {
                $frm.append('<input type = "hidden" name = "responseowner" value = "true">');
            }
        }
    }//if(replyLinkLocation)
    else
    {
        $frm = $('<div id = "editorHolder"></div>');
    }//else
    $frm.append($ta);
    $frm.insertAfter ($toMask.hide()).show();

    if(editorMode)
    {
        $replyLinkLocation = $('#'+replyLinkLocation);
        var forumTopicId = $replyLinkLocation.attr('forumTopicId');
        var responseId = $replyLinkLocation.attr('responseId');
        var publishButtoTxt = (editorMode == "Write")?i18n['zohodiscussions.general.publish']:i18n['zohodiscussions.general.update'];
        var $publishButton = $('<button id="publishResponse" class="ashBtn normalText boldText">'+publishButtoTxt+'</button>');
        $publishButton.click(function()
        {   
            if(name=="privateMsgContent")
            {   
                var type="";
                if(replyLinkLocation == "UserPM")
                {
                    type="UserPM";
                }
                addPrivateMsg(forumTopicId,editorMode,responseId,type);
            }
            else
            {
                addForumResponse(forumTopicId,editorMode,responseId);
            }
        });       
        var $cancelButton = $("<button id='cancelResponse' class='ashBtn normalText boldText'>"+i18n['zohodiscussions.general.cancel']+"</button>");
        $cancelButton.click(function()
        {              
            $('#postContentTA').editor('cancel');
            $toMask.show();
            $('#'+utilContLocation).data('inEditMode',false);
            var replyContainer = "";
            if($('#newThreadResponseCont_'+responseId ).is(':visible'))
            {
                replyContainer='#newThreadResponseCont_'+responseId;
            }
            else if($('#newResponseCont_'+forumTopicId ).is(':visible'))
            {
                replyContainer='#newResponseCont_'+forumTopicId;
            }
            else if($('#eachTopicReplyCont_'+forumTopicId ).is(':visible'))
            {
                replyContainer='#eachTopicReplyCont_'+forumTopicId;
            }
            if(replyContainer != '')
            {
                $(''+replyContainer+'').hide();
            }
            if(utilContLocation == "privateMsgInboxContainer")
            {
                $('#privateMsgCont_'+forumTopicId).hide();
            }
            else if(utilContLocation == "privateMsgSentContainer")
            {
                $('#privateMsgCont_'+forumTopicId).hide();
                if($('#topicContent_'+forumTopicId).parent().find('div.bigMinusIcon').length > 0)
                {
                    $('#topicContent_'+forumTopicId).show();
                }
            }
            else if(utilContLocation =="editorContainer_PM")
            {   
                processHash("user/"+$('#UserPM').attr('authorName'));
            }
            else if(utilContLocation =="eachTopic_"+responseId)
            {
               var $topicListContainer = $('#paginationContainer');
               $topicListContainer.data('inEditMode',false);
               $('#singlePostActions_'+responseId).show();
               $('#linkedTopic_'+responseId).show();
               $('#recent_ResPonse_'+responseId).find('div.navigationCont').show();
            }
            else if(utilContLocation == "topicContainer_"+forumTopicId)
            {
                $('#postTypeActions_'+responseId).show();
                $('#linkTopicCont_'+forumTopicId).show();
                $('#statusContainer').show();
            }
            if($attachmentContainer.is('.Attachments'))
            {
                $attachmentContainer.show();
            }
            if($('#responsePreviewContainer').is(":visible"))
            {
                //if it is visible means it is already there then why did you check for its length
                if(($('#responsePreviewContainer').length > 0) || ($singleThreadPreviewCont.length > 0))
                {
                    $('#responsePreviewContainer').remove();
                    $('#fullThreadResponseContainer').remove();
                } 
            }
            if(($('#responseContentContainer_'+responseId).is(":visible")) == true)
            {
                $('#fullResponseContainer_'+responseId).find('div.postTypeActions').show();
                var $previewButtonContainer = $('#responsePreviewButton');
                var $editorLocation = $('#fullResponseContainer_'+responseId);
                var $responseContentContainer = $('#responseContentContainer_'+responseId);
                //this is used to cancelling the preview action
                CancelPreview($previewButtonContainer,$editorLocation,$responseContentContainer);
            }
            if(($('#recentResponseContent_'+responseId).is(":visible")) == true)
            {
                $('#postTextContent_'+responseId).find('ul.singlePostActions').show();
                $('#resposeVoteLink_'+responseId).show();
                $('#chooseBestResponse_'+responseId).show();
                var $previewButtonContainer = $('#responsePreviewButtonInTopicList');
                var $editorLocation = $('#postTextContent_'+responseId);
                var $recentResponseContent = $('#recentResponseContent_'+responseId);
                //this is used to cancelling the preview action
                CancelPreview($previewButtonContainer,$editorLocation,$recentResponseContent);
            }
        });   
        //this preview button is used to preview while editing in topicList , editing/replyiny in full view thread(single post)
        var $previewButton = $('<button id="previewResponse" class="ashBtn normalText boldText">'+i18n['zohodiscussions.writePost.preview']+'</button>');
        $previewButton.click(function()
        {
            var $this = $(this);
            var location = $this.attr('location');
            var topicTitle = $('#editorHolder').find('input[name=forumPostTitle]') .val();
            var finalTopicTitle = topicTitle.replace(/^<+|<+$/g,'&lt;').replace(/<+/g,'&lt;').replace(/^>+|>+$/g,'&gt;').replace(/>+/g,'&gt;');
            var forumTopicId = $this.attr('forumTopicId');
            var responseId = $this.attr('responseId');
            //content of editing or replying post
            var contentToPost = $('#postContentTA').data('editor').val();
            contentToPost = contentToPost.replace(/^\s+/g, '').replace(/\s+$/g, ''); 
            //this is ,while editing the response or topic
            if(location == 'editResponse' || location == 'editTopic')
            {
                var responseId = $this.attr('responseId');
                
                //while editing topic or response in single post, preview action buttons (update, back to edit ,cancel ) are added
                //previewButtonTemplate is in popupcontainer, here clone of previewButtonTemplate is taken
                if($('#responsePreviewButton').length == 0)
                {
                    $responsePreviewButton = $('#previewButtonTemplate').clone();
                    $responsePreviewButton .attr('id','responsePreviewButton');
                }
                else
                {
                    $responsePreviewButton = $('#responsePreviewButton');
                }
                
                //this is for editing topic 
                if(location == 'editTopic')
                {
                    $('#fullResponseContainer_'+responseId).find('div.postTypeActions').hide();
                    $responsePreviewButton.insertAfter($('#fullResponseContainer_'+responseId).find('div.postTypeActions')).show();
                }
                
                //this is editor location
                var $editorLocation = $('#fullResponseContainer_'+responseId);
                
                $editorLocation.find('h3.header').html(finalTopicTitle);
               
                //this method is used to previewing edited topic or response
                editAndPreviewPost($responsePreviewButton,$('#postTypeActions_'+responseId),$editorLocation,location);
                
                //this is used to get the attachment container in topic or response while editing .suppose there is no attachment in post ,there will be no ($attachmentContInResponse) container
                //this is original attachment container
                $attachmentContInResponse = $('#fullResponseContainer_'+responseId).find('div.attachmentListCont').hide();
                
                //this is used to show the attachment in post while preview '$attachmentPreview' is created
                //this is created only for preview purpose
                var $attachmentPreview = $('#fullResponseContainer_'+responseId).find('div[purpose ="attachmentListContForPreview"]');
                
                //this is response content container
                var $contentContainer = $('#responseContentContainer_'+responseId);
                
                
                //this is for previewing attachment(either user may add extra attachment or delete )
                attachmentPreview($contentContainer,$attachmentContInResponse,$editorLocation,$this);
                
                //suppose cancel button in editor container is disabled,cancel button in previewbuttoncontainer also disabled,since both action are same
                if(($('#cancelResponse').attr('disabled')) == true)
                {
                    $('#responsePreviewButton').find('button[purpose="cancelPreviewResponse"]').attr('disabled',true);
                }
                $attachmentPreview.show();
                
                // this method is used to show the content of previewing response 
                previewContentContainer($('#responseContentContainer_'+responseId),contentToPost);
                
                //this method is used to performing the previewing action("update","back to edit","cancel")
                previewActions($('#fullResponseContainer_'+responseId),forumTopicId,responseId,$cancelButton,$publishButton); 

            }
            else if(location == 'topicListEditResponse')//this is used for editing  responses in topic list
            {
                //while editing response in topiclist, preview action buttons (update, back to edit ,cancel ) are added
                //previewButtonTemplate is in popupcontainer, here clone of previewButtonTemplate is taken
                if($('#responsePreviewButtonInTopicList').length == 0)
                { 
                    $responsePreviewButton = $('#previewButtonTemplate').clone();
                    $responsePreviewButton .attr('id','responsePreviewButtonInTopicList');
                }
                else
                {
                    $responsePreviewButton = $('#responsePreviewButtonInTopicList');
                }
                
                //this is editor location
                var $editorLocation = $('#postTextContent_'+responseId);
                
                //this is response content container
                var $contentContainer = $('#recentResponseContent_'+responseId);
                
                //this is used to get the attachment container in topic or response while editing .suppose there is no attachment in post ,there will be no ($attachmentContInResponse) container
                //this is original attachment container
                var $attachmentContInResponse = $('#postTextContent_'+responseId).find('div.attachmentListCont').hide();
               
                //this is used to show the attachment in post while preview '$attachmentPreview' is created
                //this is created only for preview purpose
                var $attachmentPreview = $('#postTextContent_'+responseId).find('div[purpose ="attachmentListContForPreview"]');
                $attachmentPreview.show();
               
                //suppose cancel button in editor container is disabled,cancel button in previewbuttoncontainer also disabled,since both action are same
                if(($('#cancelResponse').attr('disabled')) == true)
                {
                    $('#responsePreviewButtonInTopicList').find('button[purpose="cancelPreviewResponse"]').attr('disabled',true);
                }
                
                //this is for previewing attachment(either user may add extra attachment or delete )
                attachmentPreview($contentContainer,$attachmentContInResponse,$editorLocation,$this);
                
                // this method is used to show the content of previewing response 
                previewContentContainer( $('#recentResponseContent_'+responseId),contentToPost);
                
                //this method is used to previewing edited topic or response
                editAndPreviewPost($responsePreviewButton,$('#postTextContent_'+responseId),$editorLocation,location);
                 
                //this method is used to performing the previewing action("update","back to edit","cancel")
                previewActions($('#responsePreviewButtonInTopicList'),forumTopicId,responseId,$cancelButton,$publishButton); 
            }
            else
            {
            
                //this is used to get the clone of  'responsePreviewContainerTemplate'       
                if($('#responsePreviewContainer').length == 0)
                { 
                    $responsePreviewContainer = $('#responsePreviewContainerTemplate').clone();
                    $responsePreviewContainer.attr('id','responsePreviewContainer');
                }
                else
                {
                    $responsePreviewContainer = $('#responsePreviewContainer');
                }
                //this is for previewing the thread response
                if(replyLinkLocation == 'newThreadReply_'+responseId)
                {
                    if($('#fullThreadResponseContainer').length == 0)
                    { 
                        var $singleThreadPreviewCont=$('<div id="fullThreadResponseContainer" purpose = "threadResponseContainer" class="threadContainer"><div class="threadArrow" purpose="threadArrow"></div><div purpose ="singleThreadPreview"></div></div>');
                    }
                    else
                    {
                        var $singleThreadPreviewCont = $('#topicContainer_'+forumTopicId).find('div[purpose="threadResponseContainer"]');
                    }
                }
                
                //this is used to set the 'id' of clone for attachment
                $responsePreviewContainer.find('[purpose="previewResponseAttachment"]').attr('id','attachmentForResponsePreview');
                //this is for thread reply
                if(replyLinkLocation == 'newThreadReply_'+responseId)
                {
                    $singleThreadPreviewCont.find('div[purpose="singleThreadPreview"]').append($responsePreviewContainer);
                    $singleThreadPreviewCont.insertAfter('#newThreadResponseCont_'+responseId);
                    $responsePreviewContainer.find('button[purpose="backToEditorResponse"]').attr('location','threadResponse');
                    $('#replyToTopicBtn_'+forumTopicId).attr('location','threadResponse');
                }
                else//this is for topic reply
                {
                    $responsePreviewContainer.insertAfter('#newResponseCont_'+forumTopicId);
                    $responsePreviewContainer.find('button[purpose="backToEditorResponse"]').attr('location','topicResponse');
                    $('#replyToTopicBtn_'+forumTopicId).attr('location','topicResponse');
                }
                $responsePreviewContainer.find('h3[purpose="topicTitleOfResponse"]').html(finalTopicTitle);
                $responsePreviewContainer.find('div[purpose="responseContPreviewContainer"]').html(contentToPost);
                if(replyLinkLocation == 'newThreadReply_'+responseId)
                {
                    $('#newThreadResponseCont_'+responseId).hide();
                    $singleThreadPreviewCont.show();
                    $singleThreadPreviewCont.find('div.singleReplyContainer').show();
                }
                else//(replyLinkLocation == 'replyToTopicBtn_'+forumTopicId)
                {
                    $responsePreviewContainer.show();
                    $('#newResponseCont_'+forumTopicId).hide();
                } 

                //this is used to append the attachment in clone
                var attachmentDetails = $this.find('input[name="attachmentId"]');
                $.each(attachmentDetails, function(index, item)
                {
                    var eachAttachmentDetails = $(item).attr('attachmentDetails').split(',');
                    var $eachResponseAttachment = $('<li class="singleList" id="eachAttachmentForPreview_'+ eachAttachmentDetails[0] +'" ><div class="flLeft iconCont"><div class="attachIcon imgAttachmentTh"></div></div>  <ul class="ulNoStyle detailsListNew"> <li class="header"> <a>'+eachAttachmentDetails[1]+'</a> </li> <li class="forumDetailsList"> <span>Size:'+eachAttachmentDetails[2]+'</span></li></ul></li>');
                    $('#attachmentForResponsePreview').append($eachResponseAttachment);
                });
                
                //this there is any attachment  '$responsePreviewContainer' container is shown else hidden
                if($('#attachmentForResponsePreview > li').length > 0)
                {
                    $responsePreviewContainer.find('[purpose="attachmentResponsePreviewCont"]').show();
                }
                else
                {
                    $responsePreviewContainer.find('[purpose="attachmentResponsePreviewCont"]').hide();
                }
                 //this method is used to performing the previewing action("update","back to edit","cancel")
                previewActions($responsePreviewContainer,forumTopicId,responseId,$cancelButton,$publishButton); 
            }
        });
        var $responseAttachmentContActual = $('#responseAttachmentContTemplate').clone();
        $responseAttachmentContActual.attr('id','responseAttachmentContActual');    
        var $whiteAttachmentBox = $responseAttachmentContActual.find('div.whiteAttachmentBox').show();
        $responseAttachmentContActual.find('div[attachmentPurpose="browseBox"]').attr('id','attachBrowseCont');
        var $attachmentsList = $whiteAttachmentBox.find('ul[purpose="responseAtatchmentsListCont"]').attr('id','attachmentsListCont');
        if(editorMode == "Edit")
        {
            if($attachmentContainer.is('.Attachments'))
            {
                //this response contains attachments, so we need to add this in editor
                var $attachmentUtilCont = $attachmentContainer.find('div[purpose="attachmenUtilCont"]');
                var attachmentIds = $attachmentUtilCont.attr('attachmentIds');
                var attachmentNames = $attachmentUtilCont.attr('attachmentNames');
                var attachmentSizes = $attachmentUtilCont.attr('attachmentSizes');
                //now we have collection of all attachment ids and their names
                //split them and construct all attachments in editor
                var attachIdsColl = attachmentIds.split(",");
                var attachNamesColl = attachmentNames.split(",");
                var attachSizesColl = attachmentSizes.split(",");
                for(index = 0 ; index < attachIdsColl.length ; index++)
                {
                    var thisAttachmentId = attachIdsColl[index];
                    var thisAttachmentName = attachNamesColl[index];
                    var thisAttachmentSize = attachSizesColl[index];
                    var attachmentDetails = thisAttachmentId+','+thisAttachmentName+','+thisAttachmentSize;
                    $currentAttachment = $('#responseEachAttachmentTemplate').clone();
                    $currentAttachment.attr('id','newAttachment_' +thisAttachmentId).attr('attachmentDetails', attachmentDetails).show();
                    $currentAttachment.find('[attachmentPurpose="attachmentName"]').html(thisAttachmentName);
                    $currentAttachment.find('[attachmentPurpose="attachmentSize"]').html(thisAttachmentSize);
                    $currentAttachment.find('div.imgAshDelete').attr('thisAttachmentId',thisAttachmentId).attr('thisAttachmentName',thisAttachmentName);
                    $currentAttachment.find('div.imgAshDelete').click(function(event)
                    {
                        if(confirm(i18n['zohodiscussions.generalmessage.deleteAttachmentConfirmMsg']))
                        {
                            showSmallLoadingImage(event);
                            $this = $(this);
                            var deletingAttachmentId = $this.attr('thisAttachmentId');
                            var options = {};
                            options.forumGroupId = forumGroupId;
                            options.forumTopicId = forumTopicId;
                            options.fileName = $this.attr('thisAttachmentName');
                            options.fileId = deletingAttachmentId;
                            options[csrfParamName] = csrfToken;
                            doAjaxAction('/deleteAttachment.do',options , function(data)//No internationalization
                            {
                                hideLoadingImage();
                                if(data == "SUCCESS")
                                {
                                    $('#newAttachment_'+deletingAttachmentId).remove();
                                    $('#eachAttachmentForPreview_'+deletingAttachmentId).remove();
                                    $('#fullResponseContainer_'+responseId).find('li[attachmentId="'+ deletingAttachmentId +'" ]').remove();
                                    showTipper(i18n['zohodiscussions.generalmessage.deleteAttachmentSuccessMsg'],'info');
                                    loadUploadAttachmentsCont();
                                    $cancelButton.attr('disabled',true);
                                    $cancelButton.unbind('click');
                                }
                            });
                        }//
                    });
                    $attachmentsList.append($currentAttachment);
                }
                $attachmentContainer.hide();
            }//if($attachmentContainer.is('.Attachments'))
            $('#postTypeActions_'+responseId).hide();        
        }//if(editorMode == "Edit")
        var editorMainParentContStyle = "padding:3px;";
        if(name == "privateMsgContent")
        {
            editorMainParentContStyle = editorMainParentContStyle+""+((editorMode == "Write")?"width:97%":"width:99%"); //No I18N
        }
        else
        {
            editorMainParentContStyle = editorMainParentContStyle+""+((editorMode == "Write")?"width:93.2%":"width:99%");
        }
        $('#editorHolder').wrap('<div class="flLeft" style="'+editorMainParentContStyle+'" purpose="editorMainParentCont"></div>');
        if(name != "privateMsgContent")
        {
            if(maxAttachmentsPerPost > 0)
            {
                $('#editorHolder').append($responseAttachmentContActual.css('margin-top',25).show());
                var $editorActionUtilCont = $('<div class="flRight btnContainer" purpose="editorActionUtilCont" style="margin-right:10px;"></div>')
            }
            else
            {
                var $editorActionUtilCont = $('<div class="flRight btnContainer" purpose="editorActionUtilCont" style="margin-top:25px;margin-right:10px;"></div>')
            }
            $editorActionUtilCont.append($publishButton)
            if(utilContLocation != "paginationContainer")
            {
                $editorActionUtilCont.append($previewButton)
            }
            $editorActionUtilCont.append($cancelButton).insertAfter($('#editorHolder').parent());
        }
        else
        {
            var $replyPMContActual = $('#replyPMContTemplate').clone();
            $replyPMContActual.attr('id','replyPMContActual'); 
            $('#editorHolder').append($replyPMContActual.css('margin-top',25).hide());
            $('<div class="flRight btnContainer" style="margin-top:30px;margin-right:30px;"  purpose="editorActionUtilCont"></div>').append($publishButton).append($cancelButton).insertAfter($('#editorHolder').parent());
        }
        loadUploadAttachmentsCont();
        if(editorMode == "Write")
        {
            //insert the author profile image left side to editor
            var $authProfileConnt = $('#editorAuthProfileTemp').clone().show();
            $authProfileConnt.attr('id','');
            $authProfileConnt.insertBefore($('#editorHolder').parent());
        }
    }//if(editorMode)
    $toMask.data(textAreaID, $ta);
    var _linkPrompter = function(selectedNode)
    {
        //create a new instance of dialog
        var $myLinkDialog = $("#linkDialog");

        $myLinkDialog.show()
            .find(':button[action="cancel"], span.imgCloseDialog').click(function(){$myLinkDialog.hide();})
            .end()
            .find(':button[action="insertLink"]').unbind().click(function()
            {   
                var displayText = $myLinkDialog.find(':input[name="displayText"]').val()
                var optionsAttrs = "";
                if ($('#linkDiv').is(":visible"))
                {
                    
                    var chosenURL = sanitizeURL($.trim('' + $myLinkDialog.find(':input[name="url"]').val()));
                    if (chosenURL== '')
                    {
                        chosenURL = sanitizeURL($.trim('' + $myLinkDialog.find(':text:last').val()));
                    }
                    if(chosenURL == '') 
                    {
                        alert(i18n['zohodiscussions.createforumgroup.LinkInvalid']);
                        $myLinkDialog.find(':input[name="url"]').focus().select();
                        return;
                    }
                    var title  = $myLinkDialog.find(':input[name="title"]').val();                        
                    var target = $myLinkDialog.find(':input[name="target"]').val();
                    var rel    = $myLinkDialog.find(':input[name="rel"]').val();
                    if(target != "")
                    {
                        optionAttrs = " target = '"+target+"' ";
                    }
                    if (rel != "") 
                    {
                        optionAttrs += " rel = '" + rel + "' ";
                    }
                    if (title != "") 
                    {
                        optionAttrs += " title = '" + title + "' ";
                    }
                    if (displayText == "")
                    {
                        displayText = $myLinkDialog.find(':input[name="url"]').val();
                    }
                }
                else
                {   
                    var email_pattern = /^[a-zA-Z0-9]([\w\-\.\+]*)@([\w\-\.]*)(\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2}){0,2})$/i;
                    chosenURL = $.trim('' + $myLinkDialog.find(':input[name="email"]').val());
                    if(chosenURL == "" || chosenURL.match(email_pattern) == null ) 
                    {
                        alert(i18n['zohodiscussions.writePost.inValidEmailMessage']);
                        $myLinkDialog.find('[name="email"]').focus().select();
                        return;
                    }

                    chosenURL = "mailto:" + chosenURL;
                    if (displayText == "")
                    {
                        displayText = $myLinkDialog.find(':input[name="email"]').val();
                    }
                    optionAttrs ="";
                }
                if ($myLinkDialog.data("alreadyLinked") == "true") {
                $(selectedNode).remove();
            }
                $ta.data('editor').addLink(chosenURL, displayText, optionAttrs);
                $myLinkDialog.hide();
            })
            .end()
            
            .find('div[purpose="urlSection"]').unbind('click').click(function () {
            toggleSections($(this).parents('div.editorPopup2'), 'urlSection');
            //$myLinkDialog.find('[name="url"]').focus().select();
        })
        .end()
        .find('div[purpose="emailSection"]').unbind('click').click(function () {
            toggleSections($(this).parents('div.editorPopup2'), 'emailSection');
            //$myLinkDialog.find('[name="email"]').focus().select();
        })
        .end()
        .attr('tabIndex', -1)
        .unbind('keydown').keydown(function (e) {
            switch (e.keyCode) {
                case 27:
                    // ESC key was pressed
                    $myLinkDialog.find(':button[action="cancel"]').trigger('click');
                break;

                case 13:
                    // Enter key was pressed
                    $myLinkDialog.find(':button[action="insertLink"]').trigger('click');
                break;
            }
        })
        .show()
		.find('[purpose="urlSection"]').trigger('click');

        if (selectedNode)
        {
            if (selectedNode.tagName && selectedNode.tagName.toLowerCase() == "a") {

                var $currentNode = $(selectedNode);
                var oldLink = $currentNode.attr("href");

                if (oldLink.substr(0, 7) == "mailto:" ) {
                    $myLinkDialog.find(':input[name="email"]').val(oldLink.substr(7))
                    .end()
                    .find("[purpose='emailSection']").click();
                } else {
                    $myLinkDialog.find(':input[name="url"]').val(oldLink)
                    .end()
                    .find("[purpose='urlSection']").click();
                }

                $myLinkDialog.find(':input[name="displayText"]').val($currentNode.html())
                .end().find(':input[name="title"]').val($currentNode.attr("title"))
                .end().find(':input[name="rel"]').val($currentNode.attr("rel"));

                if ($currentNode.attr("target") == "_blank") {
                    $myLinkDialog.find(':input[name="linktarget"]').val(["new"])
                }

                $myLinkDialog.data("alreadyLinked", "true");
            } 
            else
            {
                $myLinkDialog.find(':input[name="displayText"]').val(selectedNode);

                // This is a hack to prevent the text "[object]" from getting displayed in IE.
                // This is a ugliest of all the ugly hacks.
                // TODO: This should be prevented in a better way
                if ($myLinkDialog.find(':input[name="displayText"]').val() == "[object]") {
                    $myLinkDialog.find(':input[name="displayText"]').val("");
                }
            }
        }

    }//_linkPrompter

    var _imagePrompter = function(selectedNode)
    {
        var $myImageDialog = $("#imageDialog");

        $myImageDialog.find("input[type='text']").val('')
            .end().find("[name='imgSize']").val(["FullSize"])
            .end().find("[name='imgAlignment']").val(["none"])
            .end().find("[name='imageFileName']").val("")
            .end().find("#image_error").html("")
            .end().find('#imagePreview').attr('src', "/images/img-preview.gif")
            .end().show()
            .find(':button[action="cancel"], span.imgCloseDialog').click(function()
            {
                $myImageDialog.find('input[type = "text"]').val('');
                $myImageDialog.find('input[type = "file"]').val('');
                $myImageDialog.find('input[name="responseId"]').val('');
                $myImageDialog.find('input[name="responseId"]').val('');
                $myImageDialog.find('input[name="uploadedImageUrl"]').val('');
                $myImageDialog.find('input[name="linkTo"').val('');
                $myImageDialog.hide();
            })
            .end()
            .find(':button[action="insertImage"]').attr("disabled", "disabled").unbind().click(function()
            {
                // Check whether the user has entered any non numeric characters for padding or for border.
                /*
                if (isNaN($myImageDialog.find(":input[name='border']").val()))
                {
                    alert("Please enter a valid number for border!");
                    $myImageDialog.find(":input[name='border']").focus();
                    return;
                }

                if (isNaN($myImageDialog.find(":input[name='padding']").val())) 
                {
                    alert("Please enter a valid number for padding!");
                    $myImageDialog.find(":input[name='padding']").focus();
                    return;
                }
                */
                if ($('#urldiv').is(':visible'))
                {
                    var urlToAdd = $myImageDialog.find(':input[name="url"]').val();
                    //TODO: Validate if an url has been typed.
                    if(urlToAdd && $.trim(urlToAdd) != '')
                    {
                        //url_pattern = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
                        //url_pattern = "^f|(ht)tps?://[A-Za-z0-9-_]+(?:\\.[A-Za-z0-9-_%&\?\/.=]+)*$";
                        //url_pattern = "https?://[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9-_%&?/.=:]+)*";
                        var url_pattern = /^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(\:\d+)?(\/[-a-zA-Z\d%_.~+]*)*(\?[;&a-zA-Z\d%_.~+=-]*)?(\#[-a-zA-Z\d_]*)?$/ ; //  /^(?:(?:\w|\d)+\.)+[a-zA-Z0-9]{2,6}$/;
                        if(urlToAdd.match(url_pattern) != null)
                        {
                            //validated, add the image to the url
                            //$ta.data('editor').addImage(urlToAdd);
                            //$myImageDialog.hide();
                            imageAdded(urlToAdd,textAreaID);
                        }//if(urlToAdd.match(url_pattern) != null)
                        else
                        {
                            alert(i18n['zohodiscussions.createforumgroup.LinkInvalid']);
                        }
                    }//if(urlToAdd && $.trim(urlToAdd) != '')
                    else
                    {
                        alert(i18n['zohodiscussions.createforumgroup.LinkInvalid']);
                    }//else
                }//if($myImageDialog.find('div[purpose="urlSection"]').is(':visible'))
                else
                {
                    imageAdded($myImageDialog.find(':input[name="uploadedImageUrl"]').val(),textAreaID);
                    return;
                    //Create thumbnail if necessary.
                    /*
                    switch ($myImageDialog.find('[name="imgSize"]').filter(':checked').val())
                    {
                        case "Medium":
                        case "Custom":
                        case "Small"    :
                            // Submit for to create attachment
                            var $formToSubmit = $myImageDialog.find('form');
                            $formToSubmit.find(':hidden[name="blogId"]').val($('#frmBlogPost :hidden[name="blogId"]').val());
                            $formToSubmit.find(':hidden[name="editorId"]').val(textAreaID);
                            $formToSubmit.attr('action', '/createThumbnail.do');
                            $formToSubmit.attr('enctype', "application/x-www-form-urlencoded").attr( "encoding", "application/x-www-form-urlencoded");
                            $formToSubmit.get(0).submit();
                            break;

                         case "FullSize"   :
                             //alert($myImageDialog.find(':input[name="uploadedImageUrl"]').val());
                            imageAdded($myImageDialog.find(':input[name="uploadedImageUrl"]').val(),textAreaID);
                            break;
                    }
                    */
                }
            })
            .end()
            .find(':button[action="linkToNone"]').unbind().click(function() 
            {
                $myImageDialog.find(':input[name="linkTo"]').val("");
            })
            .end()
            .find(':button[action="linktoImageUrl"]').unbind().click(function() 
            {
                fillImageUrl();
            })
            .end()
            .find('#url').unbind().blur(function () 
            {
                fillImageUrl();
            })
            .end()
            .find(':radio[name="imgSize"]').unbind().change(function() 
            {
                switch ($myImageDialog.find(':input[name="imgSize"]').filter(':checked').val()) {
                    case "Small":
                        $myImageDialog.find(':input[name="width"]').val("100").attr('readonly', 'true');
                        $myImageDialog.find(':input[name="height"]').val("100").attr('readonly', 'true');
                        break;
                    case "Medium":
                        $myImageDialog.find(':input[name="width"]').val("250").attr('readonly', 'true');
                        $myImageDialog.find(':input[name="height"]').val("250").attr('readonly', 'true');
                        break;
                    case "FullSize":
                        $myImageDialog.find(':input[name="width"]').val("").attr('readonly', 'true');
                        $myImageDialog.find(':input[name="height"]').val("").attr('readonly', 'true');
                        break;

                    case "Custom":
                        $myImageDialog.find(':input[name="width"]').removeAttr('readonly');
                        $myImageDialog.find(':input[name="height"]').removeAttr('readonly');
                        break;
                }
            })
            .end()
            .find('[name="imageFileName"]').unbind().change(function () 
            {
                return uploadImage();
            })
            .end()
            .find(':text:first').focus();

        if (selectedNode) 
        {
            $('#urlSection').click();
            var linkto = "";
            var currentImage = "";
            if (selectedNode.tagName.toLowerCase() == "img") 
            {
                currentImage = selectedNode;
            } 
            else 
            {
                while(selectedNode.childNodes && selectedNode.childNodes[0].tagName.toLowerCase() != "img") 
                {
                    if (selectedNode.childNodes[0].tagName.toLowerCase() == "a") 
                    {
                        linkto = $(selectedNode.childNodes[0]).attr("href");
                    }
                    selectedNode = selectedNode.childNodes[0];
                }
                currentImage = selectedNode.childNodes[0];
            }
            $('#url').val($(currentImage).attr("src")).blur();

        }
    }//_imagePrompter
    var _objectPrompter = function()
    {
	    //create a new instance of dialog
	    var $myObjectDialog = $("#objectDialog");

	    $myObjectDialog.show()
		.find(':button[action="cancel"], span.imgCloseDialog').click(function(){$myObjectDialog.hide().find('textarea').val('');})
		.end()
		.find(':button[action="insertObject"]').unbind('click').click(function()
		{
		    var givenObject = sanitize($.trim('' + $myObjectDialog.find(':input:first').val()));
		    if(givenObject == '') {alert('Please enter a valid Object');return;}
		    $ta.data('editor').insertObject(givenObject);
		    $myObjectDialog.hide().find('textarea').val('');
		})
		.end()
		.find(':text:first').focus();
            $('#boxcontent_content').find(':textarea').focus();   //No I18N
    }//_objectPrompter

    $ta.editor({linkPrompter:_linkPrompter, imagePrompter: _imagePrompter, objectPrompter: _objectPrompter});
}//openEditor();

function toggleSections($context, sectionToShow)
{
    $context
	.find('div[purpose]').hide()
	.end()
	.find('div[purpose="' + sectionToShow + '"]').show()
	.end()
	.find('li[purpose]').removeClass('selectedMenu')
	.end()
	.find('li[purpose="' + sectionToShow + '"]').addClass('selectedMenu');
}//function toggleSections($context, sectionToHide, sectionToShow)

/**
 * errmsg - Error Message
 */
function uploadError(errmsg) 
{
    var $myImageDialog = $("#imageDialog");
    $myImageDialog.find('#image_error').hide().html(errmsg).css("background", "#FFF1A8").fadeIn();
}
//this method is used to performing the previewing action("update","back to edit","cancel")
function previewActions($responsePreviewContainer,forumTopicId,responseId,$cancelButton,$publishButton)
{
    $responsePreviewContainer.find('button[purpose="backToEditorResponse"]').unbind('click').click(function()
    {
        var $this = $(this);
        var location = $this.attr('location');
        if(location == 'topicResponse')
        {
            $responsePreviewContainer.hide();
            $('#newResponseCont_'+forumTopicId).show();
        }
        else if(location == 'editEachResponse')
        {
            $('#resposeVoteLink_'+responseId).show();
            $('#chooseBestResponse_'+responseId).show();
            
            //this method is used for back to editor while editing
            backtoEditorWhilePreviewing( $('#fullResponseContainer_'+responseId),$('#responseContentContainer_'+responseId),$('#responsePreviewButton'));
        }
        else if(location == 'topicListEditResponse')
        {
             //this method is used for back to editor while editing
            backtoEditorWhilePreviewing( $('#postTextContent_'+responseId),$('#recentResponseContent_'+responseId),$('#responsePreviewButtonInTopicList'));
            
        }
        else
        {
            $('#newThreadResponseCont_'+responseId).show();
            $('#fullThreadResponseContainer').hide();
        }
        $('#attachmentForResponsePreview').html(' ');
    });
    $responsePreviewContainer.find('button[purpose="publishPreviewResponse"]').unbind('click').click(function()
    {
        $publishButton.trigger('click');
    });
   
    $responsePreviewContainer.find('button[purpose="cancelPreviewResponse"]').unbind('click').click(function()
    {
        $cancelButton.trigger('click');
    });
  }//function previewActions($responsePreviewContainer,forumTopicId,responseId,$cancelButton,$publishButton)

 //this method is used to previewing edited topic or response
function editAndPreviewPost($responsePreviewButton,$insertAfterThisContainer,$editorLocation,location)
{
    var location = (location == "editResponse" || location == "editTopic")? "editEachResponse":"topicListEditResponse";
    $responsePreviewButton.insertAfter($insertAfterThisContainer).show();
    $editorLocation.find('div[purpose="editorMainParentCont"]').hide();
    $editorLocation.find('div[purpose="editorActionUtilCont"]').hide();
    $responsePreviewButton.find('button[purpose="publishPreviewResponse"]').html(i18n['zohodiscussions.general.update']);

    $responsePreviewButton.find('button[purpose="backToEditorResponse"]').attr('location',location);
    $responsePreviewButton.find('button[purpose="publishPreviewResponse"]').attr('location',location);
    $responsePreviewButton.find('button[purpose="cancelPreviewResponse"]').attr('location',location);
    
}//function editAndPreviewPost($responsePreviewButton,$insertAfterThisContainer,$editorLocation,location)

//this is used to cancelling the preview action
function CancelPreview($previewButtonContainer,$editorLocation,$responseContentContainer)
{
    $previewButtonContainer.remove();
    $editorLocation.find('div.Attachments').show();
    $editorLocation.find('div.attachmentListCont').show();
    $editorLocation.find('div[purpose ="attachmentListContForPreview"]').hide();
    $responseContentContainer.show();
    $('#previewContentContainer').remove();
    $('#newAttachmentForPreview').remove();
}//function CancelPreview($previewButtonContainer,$editorLocation,$responseContentContainer)

// this method is used to show the content of previewing response 
function previewContentContainer($responseContentContainer,previewContent)
{
    $responseContentContainer.hide();
    if($('#previewContentContainer').length == 0)
    {
        var $previewContentContainer = $('<div id="previewContentContainer" class="postContent"> </div>');
    }
    else
    {
        $previewContentContainer = $('#previewContentContainer');
    }
    $previewContentContainer.insertAfter($responseContentContainer);
    $previewContentContainer.html(previewContent).show();
}//function previewContentContainer($responseContentContainer,previewContent)

//this method is used for back to editor while editing
function backtoEditorWhilePreviewing($editorLocation,$contentContainer,$previewButtonContainer)
{
    $editorLocation.find('div[purpose="editorMainParentCont"]').show();
    $editorLocation.find('div[purpose="editorActionUtilCont"]').show();
    $contentContainer.hide(); 
    $editorLocation.find('div.Attachments').hide();
    $('#previewContentContainer').hide();
    var $attachmentListCont = $editorLocation.find('div[purpose ="attachmentListContForPreview"] > ul');
    $attachmentListCont.html(' ');
    var $newAttachment = $('#newAttachmentForPreview').find('ul[purpose="previewResponseAttachment"]');
    $newAttachment.html(' ');
    $previewButtonContainer.hide();   
}//function backtoEditorWhilePreviewing($editorLocation,$contentContainer,$previewButtonContainer)

//this method is used append the attachment in clone for previewing 
function attachmentListPreview($appendingAttachmentCont,attachmentListCont)
{
    //this is used to append the attachment in clone
    $.each(attachmentListCont, function(index, item)
    {
        var eachAttachmentDetails = $(item).attr('attachmentDetails').split(',');
        var $eachResponseAttachment = $('<li class="singleList" id="eachAttachmentForPreview_'+ eachAttachmentDetails[0] +'" ><div class="flLeft iconCont"><div class="attachIcon imgAttachmentTh"></div></div>  <ul class="ulNoStyle detailsListNew"> <li class="header"> <a>'+eachAttachmentDetails[1]+'</a> </li> <li class="forumDetailsList"> <span>Size:'+eachAttachmentDetails[2]+'</span></li></ul></li>');
        $appendingAttachmentCont.append($eachResponseAttachment).show();
    });
}//function attachmentListPreview($appendingAttachmentCont,attachmentListCont)

//this is for previewing attachment(either user may add extra attachment or delete )
function attachmentPreview($contentContainer,$attachmentContInResponse,$editorLocation,$this)
{
    
    //this is for preview attachment container
    var $attachmentPreview = $editorLocation.find('div[purpose ="attachmentListContForPreview"]');
    if($attachmentPreview.length == 0 && $('#newAttachmentForPreview').length == 0)
    {
        var $attachmentListContforPreview = $('<div class="attachmentListCont" purpose ="attachmentListContForPreview"> <ul class="ulNoStyle"> </ul></div>');
        $attachmentListContforPreview.insertAfter($attachmentContInResponse);
    }
        
    //if there is no attachment in the response,while editing the response, if suppose user add new attachment , initially there is no attachment container for this case
    // so newattachmentforpreview container is added
    if($('#newAttachmentForPreview').length == 0)
    {
        if(($('#attachmentsListCont').find('li[purpose="attachmentDetails"]')).length > 0 && $attachmentContInResponse.length == 0)
        {
            $newAttachmentForPreview = $('#responsePreviewContainerTemplate').find('div[purpose ="attachmentResponsePreviewCont"]').clone();
            $newAttachmentForPreview.attr('id',"newAttachmentForPreview");
            $newAttachmentForPreview.insertAfter($contentContainer);
            $newAttachmentForPreview.find('div.attachmentListCont').show();
        }
    }     
    if($('#newAttachmentForPreview').length > 0)
    {
        $('#newAttachmentForPreview').show();
        var attachmentDetails = $this.find('input[name="attachmentId"]');
        var $appendingAttachmentCont = $('#newAttachmentForPreview').find('ul[purpose="previewResponseAttachment"]');
        attachmentListPreview($appendingAttachmentCont,attachmentDetails); 
        $newAttachmentForPreview.find('div.attachmentListCont').show();
    }
    else //(this case : response has already attachment)
    {
        var attachmentDetails = $('#attachmentsListCont').find('li[purpose="attachmentDetails"]');
        var $appendingAttachmentCont = $editorLocation.find('div[purpose ="attachmentListContForPreview"] > ul');
        attachmentListPreview($appendingAttachmentCont,attachmentDetails); 
    }
    
    // if all attachment deleted, no need to show the attachment container
    if($editorLocation.find('div[purpose ="attachmentListContForPreview"] > ul > li').length > 0 || $('#newAttachmentForPreview').find('ul[purpose ="previewResponseAttachment"] > li').length > 0)
    {
        $editorLocation.find('div.Attachments').show();
    }
    else
    {
        $editorLocation.find('div.Attachments').hide();
    }
}//function attachmentPreview($contentContainer,$attachmentContInResponse,$editorLocation,$this)

function imageUploaded(imageURL,attachmentId, context,actualImageURL)
{
    $('#imagePreview').attr({src: imageURL, width: '100', height: '100'});
    var $myImageDialog = $("#imageDialog");
    $myImageDialog.find("#image_error").html('');
    $myImageDialog.find(':input[name="linkTo"]').val(actualImageURL)
    $myImageDialog.find(':button[action="insertImage"]').attr("disabled", "").end()
                  .find(':input[name="uploadedImageUrl"]').val(imageURL);

}//function foo(imageURL, context)
function imageAdded(imageURL,textAreaID)
{
    var $imgDialog = $('#imageDialog');
    var props = {};

    /*
    switch($imgDialog.find('[name="imgAlignment"]').filter(':checked').val())
    {
        //handle alignment changes
        case 'left':
            props.htmlClass = 'flLeft';
            break;
        case 'right':
            props.htmlClass = 'flRight';
            break;
        case 'center':
            props.htmlClass = "alCenter";
            break;
    }//switch($imgDialog.find('[name="imgAlignment"]').val())

    try { props.width = parseInt($imgDialog.find('[name="width"]').val()); }catch(ex){}
    try { props.height = parseInt($imgDialog.find('[name="height"]').val()); }catch(ex){}
    try { props.border = parseInt($imgDialog.find('[name="border"]').val()); }catch(ex){}
    
    // Even though the input is coming from a dropdown, we are checking it so as to prevent input tampering
    if ($imgDialog.find('[name="border_px"]').val() == "em") {
        props.border_px = "em";
    } else {
        props.border_px = "px";
    }

    try { props.padding = parseInt($imgDialog.find('[name="padding"]').val()); }catch(ex){}

    // Even though the input is coming from a dropdown, we are checking it so as to prevent input tampering
    if ($imgDialog.find('[name="padding_px"]').val() == "em") {
        props.padding_px = "em";
    } else {
        props.padding_px = "px";
    }
    */
    props.title = $imgDialog.find('[name="title"]').val();
    props.altText = $imgDialog.find('[name="altText"]').val();
    
    props.linkTo = $imgDialog.find('[name="linkTo"]').val();
    props.imgSize = $imgDialog.find('[name="imgSize"]').filter(':checked').val();

    $('#' + textAreaID).data('editor').addImage(imageURL, props);
    $('#imageDialog').hide();
}//function imageAdded(imageURL, context)

function toggleSections($context, sectionToShow)
{
    $context
	.find('div[purpose]').hide()
	.end()
	.find('div[purpose="' + sectionToShow + '"]').show()
	.end()
	.find('span[purpose]').removeClass('select').addClass('default')
	.end()
	.find('span[purpose="' + sectionToShow + '"]').removeClass('default').addClass('select');
}//function toggleSections($context, sectionToHide, sectionToShow)

function fillImageUrl() 
{
    var $myImageDialog = $("#imageDialog");
    
    if($myImageDialog.find('#urldiv').is(':visible'))    {
        var urlToAdd = $myImageDialog.find(':input[name="url"]').val();
        
        if (urlToAdd && $.trim(urlToAdd) != '' ) {
          if ($.trim(urlToAdd) != '' && isValidUrl(urlToAdd)) {
              $myImageDialog.find(':input[name="linkTo"]').val(urlToAdd)
              .end()
              .find('#imagePreview').attr({src: urlToAdd, width: '100', height: '100'})
              .end()
              .find(':button[action="insertImage"]').attr("disabled", "");
          } else {
              alert(i18n['zohodiscussions.createforumgroup.LinkInvalid']);
              $myImageDialog.find(':input[name="url"]').focus();
          }
        }
    } else {
        var urlToAdd = $myImageDialog.find(':input[name="uploadedImageUrl"]').val();        
        $myImageDialog.find(':input[name="linkTo"]').val(urlToAdd);                    
    }
}//function fillImageUrl() 

function isValidUrl(url) 
{
    if(url && $.trim(url) != '')
    {
        //url_pattern = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
        //url_pattern = "^f|(ht)tps?://[A-Za-z0-9-_]+(?:\\.[A-Za-z0-9-_%&\?\/.=]+)*$";
        url_pattern = "^https?://[A-Za-z0-9-_]+(?:\\.[A-Za-z0-9-_%&\?\/.=]+)*$";
        if(url.match(url_pattern) != null)
        {
            //validated
            return true;
        }//if(url.match(url_pattern) != null)
        else
        {
            return false;
//            alert("Please enter a valid URL!");
        }
    }//if(url && $.trim(url) != '')
    else {
        return false;
    }
}

function uploadImage() 
{
    var $myImageDialog = $("#imageDialog");

    if ($.trim($myImageDialog.find("[name='imageFileName']").val()) != "") 
    {
        // Don't submit if the file control is empty
        var $formToSubmit = $myImageDialog.find('form');

        $myImageDialog.find("#image_error").html("<em>Uploading .. <img src = '/images/progressbarsmall.gif' /></em>")
        .end()
        .find(':button[action="insertImage"]').attr("disabled", "true");

        $formToSubmit.find(':hidden[name="responseId"]').val($('#editorHolder :hidden[name="responseId"]').val());
        $formToSubmit.attr('action', '/uploadImage.do');
        $formToSubmit.attr('enctype', "multipart/form-data").attr( "encoding", "multipart/form-data" ); // encoding - to fix a bug with IE
        $formToSubmit.get(0).submit();
    }//
}//function uploadImage() 

function toggleImageSelection(curr) 
{
    if ($(curr).attr('id') == "uploadSection") 
    {
        $(curr).addClass("select");
        $("#urlSection").removeClass("select");
        $("#uploaddiv").show();
        $("#urldiv").hide();
    }
    else 
    {
        $(curr).addClass("select");
        $("#uploadSection").removeClass("select");
        $("#uploaddiv").hide();
        var $urlDiv = $("#urldiv");
        $urlDiv.show();
        $urlDiv.find(':inpur[name="url"]').focus();
    }
}