tangler.manager.TopicState=function(){var _701=function(){this.groupId=0;this.topicId=0;this.authorId=0;this.topicUrl=null;this.messageCount=0;this.isTopicWatched=false;_701.superclass.constructor.call(this);};Ext.extend(_701,Ext.util.Observable,{setGroupId:function(_702){this.groupId=_702;},getGroupId:function(){return this.groupId;},getTopicUrl:function(){return "/conversations/"+this.topicId;},setMessageCount:function(_703){this.messageCount=_703;},getMessageCount:function(){return this.messageCount;},setAuthorId:function(aId){this.authorId=aId;},getAuthorId:function(){return this.authorId;},setTopicId:function(tId){this.topicId=tId;},getTopicId:function(){return this.topicId;},setTopicWatched:function(_706){this.isTopicWatched=_706;},getTopicWatched:function(){return this.isTopicWatched;}});return new _701();}();tangler.manager.AuthorState=function(){var _707=function(){this.delayedTask=null;this.focusedAuthorId=0;this.focusedAuthorScreenName="";this.addEvents({"authorFocused":true,"authorUnfocused":true});_707.superclass.constructor.call(this);};Ext.extend(_707,Ext.util.Observable,{setFocusAuthor:function(id,ele,_70a){this.focusedAuthorId=id;if(this.focusedAuthorId!=0){if(this.delayedTask==null){this.delayedTask=new Ext.util.DelayedTask();}this.delayedTask.delay(700,function(){this.fireEvent("authorFocused",id,ele,_70a);},this);}else{if(this.delayedTask!=null){this.delayedTask.cancel();}this.fireEvent("authorUnfocused");}},getFocusAuthorId:function(){return this.focusedAuthorId;},setFocusAuthorScreenName:function(_70b){if(_70b!=null&&_70b!=""){this.focusedAuthorScreenName=_70b;}},getFocusAuthorScreenName:function(){return this.focusedAuthorScreenName;}});return new _707();}();tangler.manager.Message=function(_70c,_70d){this._inputId=_70c;this._editor=null;this._submitFunction=null;this._isChat=tangler.util.Options.getOptionalArgument("isChat",_70d,false);this._setContent=null;};tangler.manager.Message.prototype={setSubmitFunction:function(_70e){this._submitFunction=_70e;},toggleChatMode:function(_70f){this._isChat=_70f;if(this._editor){this._editor.toggleChatMode(_70f);}},showInput:function(_710){if(!this._editor){try{this._editor=new tinymce.Editor(this._inputId,{mode:"textareas",theme:"advanced",plugins:"media,inlinepopups,paste,linkautodetect",content_css:"css/content.css",theme_advanced_toolbar_location:"top",theme_advanced_toolbar_align:"left",theme_advanced_buttons1:"bold,italic,underline,strikethrough,forecolor,separator,bullist,numlist,link,separator,image,media,cemoties",theme_advanced_buttons2:"",theme_advanced_more_colors:0,theme_advanced_buttons3:"pastetext,pasteword,selectall",paste_auto_cleanup_on_paste:true,paste_convert_headers_to_strong:false,paste_strip_class_attributes:"all",paste_remove_spans:true,paste_remove_styles:true,paste_text_sticky:true,paste_retain_style_properties:"",setup:function(ed){ed.onInit.add(function(ed){ed.pasteAsPlainText=true;});}});this._editor.onKeyPress.add(function(ed,e){if(!e.shiftKey&&e.keyCode==13){var _715=true;_715=ed.editorId=="editor"?true:false;if(_715){var _716=ed.selection.getNode();if(_716.tagName.toUpperCase()=="LI"){return;}_self.submitMessage();setTimeout(function(){_self.resetEditor();},10);}return;}});this._editor.onPostRender.add(function(ed){if(tangler.info.Session.getSecurity().isAuthenticated()||tangler.info.Session.getSecurity().isAnonymousPoster()){setTimeout(function(){ed.focus();},200);}});this._editor.render();}catch(e){if(tangler.util.Element.getEl(this._inputId)==null){var _718=tangler.util.Element.createNode("textarea",{attributes:[["id",this._inputId]]});document.appendChild(_718);}this._editor=new tinymce.Editor(this._inputId,{mode:"textareas",theme:"advanced",plugins:"media,inlinepopups,paste,linkautodetect",content_css:"css/content.css",theme_advanced_toolbar_location:"top",theme_advanced_toolbar_align:"left",theme_advanced_buttons1:"bold,italic,underline,strikethrough,forecolor,separator,bullist,numlist,link,separator,image,media,cemoties",theme_advanced_buttons2:"",theme_advanced_buttons3:"",theme_advanced_more_colors:0,theme_advanced_buttons3_add:"pastetext,pasteword,selectall",paste_auto_cleanup_on_paste:true,paste_remove_spans:true,paste_convert_headers_to_strong:false,paste_strip_class_attributes:"all",paste_remove_styles:true,paste_text_sticky:true,paste_retain_style_properties:"",setup:function(ed){ed.onInit.add(function(ed){ed.pasteAsPlainText=true;});}});this._editor.onKeyUp.add(function(ed,e){if(!e.shiftKey&&e.keyCode==13){var _71d=true;_71d=ed.editorId=="editor"?true:false;if(_71d){var _71e=ed.selection.getNode();if(_71e.tagName.toUpperCase()=="LI"){return;}_self.submitMessage();setTimeout(function(){_self.resetEditor();},10);}return;}});this._editor.onPostRender.add(function(ed){if(tangler.info.Session.getSecurity().isAuthenticated()||tangler.info.Session.getSecurity().isAnonymousPoster()){setTimeout(function(){ed.focus();},200);}});this._editor.render();}if(this._setContent){this._editor.selectAll();this._editor.insertHTML(this._setContent);this._setContent=null;}}},submit:function(){if(this._editor){this._submitFunction();}},hideInput:function(_720){if(this._editor){this._editor.hide();}},resetInput:function(){if(this._editor){this._editor.setContent("");}},focusInput:function(){if(tangler.info.Session.getSecurity().isAuthenticated()||tangler.info.Session.getSecurity().isAnonymousPoster()){setTimeout(this.focusInputCallback(this),200);}else{setTimeout(this.blurInputCallback(this),200);}},focus:function(){if(_self._editor){_self._editor.focus();}},blurInputCallback:function(_721){return function(){window.focus();if(_721._editor){_721._editor.blur();}};},focusInputCallback:function(_722){return function(){if(_722._editor){_722._editor.focus();}};},setInputContent:function(_723){if(this._editor){this._editor.setContent(_723);}else{this._setContent=_723;}},getInputContent:function(){if(this._editor){return this._editor.getContent();}else{return null;}}};tangler.manager.QueProcessor=function(){var _724=new Array();var _725=false;var _726=true;var _727=false;var _728=50;return {isInited:function(){return _727;},init:function(){_727=true;setInterval(this.processQueue,_728);},queue:function(msg){_724.push(msg);},priorityQueue:function(msg){_724.unshift(msg);},processQueue:function(){if(!_726){return;}_726=false;try{var _72b=_724.shift();if(_72b){var _72c=_72b.detail.globalId;_self.onMessagEventProxy(_72b);if(typeof (_72b.undelivered)!="undefined"&&_72b.undelivered==true){_self.markMessageUndelivered(_72b.detail.globalId);}else{if(typeof (_72b.undelivered)!="undefined"&&_72b.undelivered==false){MessageHandler.createMessage(_72b.detail.globalTopicId,_72b.detail.quoteMessage,_72b.detail.parentMessageId,{callback:function(msg){_self._updateCreatedMessage(msg,_72c);},errorHandler:_self._createMessageFailed});}}}}catch(e){try{console.log("Error occured while processing queue ");}catch(ex){}}_726=true;}};};tangler.manager.TopicMessageList=function(){var _72e=tangler.manager.AuthorState;var _72f=tangler.manager.TopicState;var _730=tangler.view.TopicLifecycleConvertor;var _731=tangler.manager.Comms;var _732=null;var _733=false;var _734=null;var _735=null;var _736=null;var _737=0;var _738=0;var _739=0;var _73a=null;var _73b=null;var _73c=false;var _73d;var _73e=null;var _73f=null;var _740=0;var _741="";var _742=30000;var _743="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";var _744=1;var _745=true;var _746=500;var _747=new Date().getTime();var _748=0;var _749=new tangler.manager.QueProcessor();var _74a=0;var _74b=0;var _74c="";var _74d;var _74e=false;var _74f=new Ext.Template("<div class=\"authorInfo\">","   <div class=\"avatar\"><img src=\"{authorAvatarUrl}\"/></div>","   <div class=\"details\">","      <h4>{authorScreenName}</h4>","      <div id=\"authorFullname\" class=\"subDetails\">{authorFullname}</div>","      <div id=\"authorLocation\" class=\"subDetails\">{authorLocation}</div>","      <div id=\"me\" class=\"me\">me</div>","      <div id=\"authorActions\" class=\"subDetails\">","         <a href=\"{profileUrl}\" id=\"profileLink\">View Profile</a> <span id=\"followOpt\">| <a href=\"{interactionUrl}\" id=\"followUserAuthorPopup\">{interactionType}</a> </span>","      </div>","\t\t{banButton}","      </div>","   </div>","</div>");var _750=function(){_750.superclass.constructor.call(this);_self=this;};Ext.extend(_750,Ext.util.Observable,{init:function(_751){if(_73c){return;}_735=new tangler.manager.Message("editor",{isChat:false});_735.setSubmitFunction(_self._sendMessage);_735.showInput({simpleButtons:false});_736=new tangler.manager.Message("editMessageInput");_72e.on("authorFocused",_self._onAuthorFocused);_72e.on("authorUnfocused",_self._onAuthorUnfocused);_73d=tangler.util.Options.getOptionalArgument("messagesDiv",_751,"messages");if(tangler.info.Session.getSecurity().isAnonymousPoster()){tangler.util.Element.getEl("messageEditorOverlay").hide();}var _752=tangler.util.Options.getOptionalArgument("topicId",_751,0);var _753=tangler.util.Options.getOptionalArgument("topicCreatorId",_751,0);var _754=tangler.util.Options.getOptionalArgument("groupId",_751,0);var _755=tangler.util.Options.getOptionalArgument("isWatched",_751,false);var _756=tangler.util.Options.getOptionalArgument("messageCount",_751,0);_72f.setTopicId(_752);_72f.setAuthorId(_753);_72f.setGroupId(_754);_72f.setTopicWatched(_755);_72f.setMessageCount(_756);if(!_749.isInited()){_749.init();}return;},getEditor:function(){return _735;},getMessages:function(_757){tangler.util.Element.removeChildNodes(_73d);tangler.util.Element.getEl(_73d).removeClass("hide");tangler.util.Element.getEl(_73d).dom.appendChild(tangler.util.Element.createSmallLoadingElement());MessageHandler.getMessagesAndLastRead(_757,{callback:_self._getMessagesAndLastReadCallback,errorHandler:_self._getMessagesAndLastReadError,timeout:_742});},getMessagesAndScroll:function(_758,_759){_737=_759;this.getMessages(_758);},reset:function(){tangler.cache.CacheManager.clearMessageCache();_73f=null;_740=0;_738=0;tangler.info.Session.setMessageLastViewedDate(0);},setLastRead:function(_75a){_73f=_75a;},onMessageEvent:function(_75b){_749.queue(_75b);},onBannedMessageEvent:function(_75c){alert("You are banned from this topic!");},onMessagEventProxy:function(_75d){var _75e=tangler.util.Element.getEl("message-"+_75d.detail.globalId);if(_75e==null){var _75f=tangler.util.Helper.canScroll("messageViewPort","messages");_self._buildMessage(_75d,{lastRead:new Date(),ignoreLastRead:true,doSort:true});if(_75d.permissions.quotable!=null){if(!tangler.info.Page.isFocused()){tangler.util.Functions.attractUser(_75d);}}if(_75f){tangler.util.Helper.scrollElementToEnd("messageViewPort");}}else{if(_75d.permissions.quotable){var _760=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_75d.detail.body);if(_760==null||_760==""){_75d.permissions.quotable=false;}}var msg=new tangler.domain.MessageElement(_75d.detail,_75d.permissions,_75d.auditHistory);msg.updateElement();if(msg.checkAndRemoveMessageAuthor(_739)){_self._updatePreviousAuthorDetails();}delete msg;}var _762=tangler.util.formatter.formatDateTime(_75d.detail.lastModified);if(_762>tangler.info.Session.getMessageLastViewedDate()){tangler.info.Session.setMessageLastViewedDate(_762);_self._sendTopicLastMessageViewed(tangler.info.Session.getTopicId());}},submitMessage:function(){_74e=false;_735.submit();_735.focusInput();},tweetMessage:function(){if(!tangler.manager.TopicPage.isTwitterAuth()){window.open("/twitterauthchat.action?mode=twchat","Chat_with_Twitter","width=560,height=530,resizable=1");}else{if(tangler.manager.TopicPage.isTwitterChatEnabled()){tangler.manager.TopicPage.setTwitterChatEnabled(false);MessageHandler.enableOrDisableTwitterChat("false",{callback:_self.desableTwitterChat});}else{tangler.manager.TopicPage.setTwitterChatEnabled(true);MessageHandler.enableOrDisableTwitterChat("true",{callback:_self.enableTwitterChat});}}},enableTwitterChat:function(){Ext.fly("posttweet").removeClass("twbuttonDisabled");Ext.fly("posttweet").addClass("twbuttonEnabled");},desableTwitterChat:function(){Ext.fly("posttweet").removeClass("twbuttonEnabled");Ext.fly("posttweet").addClass("twbuttonDisabled");},resetEditor:function(){_735.setInputContent("");_735.focus();window.focus();},_updatePreviousAuthorDetails:function(){var _763=tangler.util.Element.getEl("messages").select("div.author").elements;if(_763.length>0){var _764=_763[_763.length-1];var _765=_764.id;var _766=_765.split("@")[1].split("|")[0];var _767=parseInt(_765.split("@")[1].split("|")[1]);if(_740!=_767&&_741!=_766){_740=_767;_741=_766;}}else{_740=0;_741="";}},_sendMessage:function(){if(!_74e){messagePending=_735.getInputContent().trim();_74b=0;_74c="";}else{messagePending=_736.getInputContent().trim();}if(messagePending.indexOf("__RP_Callback_Helper(str,")!=-1){Ext.MessageBox.show({title:"Message Warning",msg:"You appear to have Real Player installed and it is inserting some text into your comment:<br>"+"<p>&lt;script type=\"text/javascript\"&gt;&lt;!-- function __RP_Callback_Helper...&lt;/script&gt;</p><br>"+"Press 'Cancel' and remove the Real Player Browser Record Plugin to prevent this or 'OK' to continue. \"",buttons:Ext.MessageBox.OKCANCEL,fn:function(btn,text){if(btn=="ok"){_self._processSendingMessage(messagePending);}else{return;}}});return;}else{_self._processSendingMessage(messagePending);}},_editMessage:function(){var _76a=_736.getInputContent().trim();if(_self._isMessageEmpty(_76a)){_736.resetInput();return;}_73a.hide();if(_738!=null&&_738!=0){var _76b="";var _76c=document.getElementById("quoteMessage-"+_738);if(!tangler.util.StringUtil.isEmpty(_76c)){_76b=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_76c.innerHTML);_76b="<quote>"+_76b+"</quote>";}if(_76a.length>1000){if(_73e==null){_73e=new tangler.widget.DialogWrapper("sending-dlg",{width:150,height:105});}_73e.showDialog();}_76a=_76a.replace(/<br \/>&nbsp;<\/p>/g,"</p>");_76a=_76a.replace(/<br\/>&nbsp;<\/p>/g,"</p>");_76a=_76a.replace(/<br>&nbsp;<\/p>/g,"</p>");MessageHandler.modifyMessage(_738,_76b+_76a,{callback:_self._modifyMessageCallback,errorHandler:_self._modifyMessageError});}},_modifyMessageCallback:function(_76d){if(_73e!=null&&_73e.isVisible()){_73e.hide();}_738=0;var _76e=new tangler.domain.MessageElement(_76d.detail,_76d.permissions,_76d.auditHistory);var _76f={};_76f=_self._setCreateMessageEventArguments(_76f,_76d);_76e.updateElement(_76f);delete _76e;},_modifyMessageError:function(_770){if(_73e!=null&&_73e.isVisible()){_73e.hide();}alert("Failed to edit message");},_processSendingMessage:function(_771){if(_self._isMessageEmpty(_771)){if(_74e){_736.resetInput();return;}else{_735.resetInput();return;}}var _772=tangler.info.Session.getTopicId();_735.resetInput();if(_771.length>1000){if(_73e==null){_73e=new tangler.widget.DialogWrapper("sending-dlg",{width:100,height:100});}_73e.showDialog();}_771=_771.replace(/%25/g,"%");_771=_771.replace(/<br \/>&nbsp;<\/p>/g,"</p>");_771=_771.replace(/<br\/>&nbsp;<\/p>/g,"</p>");_771=_771.replace(/<br>&nbsp;<\/p>/g,"</p>");var _now=new Date();var _774=null;var _775=tangler.info.Session.getSecurity().isAnonymousPoster();if(_775){_774={anonymousScreenName:tangler.info.Session.getUser(),remoteIp:"127.0.0.1"};}var _776=tangler.info.Session.getAvatar();var _777=Math.random().toString().substring(2);var _778={undelivered:false,auditHistory:null,permissions:{deletable:false,modifiable:false},detail:{showAttribs:false,anonymousDetail:_774,author:{anonymous:_775,avatar:_776,created:_now,lastModified:_now,fullName:"",screenName:_775?"anonymousUser":tangler.info.Session.getUser(),globalId:_775?1:tangler.info.Session.getUserId()},body:_74c+_771,created:_now,lastModified:_now,globalId:_777,globalTopicId:_772,parentMessageId:_74b,quoteMessage:_74c+_771}};_thisMessageTime=new Date().getTime();if(_thisMessageTime-_747<=_746){_747=new Date().getTime();_748++;}else{_748=0;}if(_748>5&&_thisMessageTime-_747<=_746){_778.undelivered=true;}_749.priorityQueue(_778);_747=new Date().getTime();},markMessageUndelivered:function(_779){var _77a=Ext.get("message-"+_779);if(_77a){_77a.addClass("undeliverd");var _77b=_77a.select("span.msgOptions").elements;if(_77b!=null&&_77b.length>0){var _77c=_77b[0];var _77d={};_77d=_self._setCreateRepostEventArguments(_77d,_779);var _77e=new tangler.domain.MessageElement().createMessageRepostOption(_77d);_77c.appendChild(_77e);}}},_onAuthorFocused:function(_77f,_780,_781){if(_732==null){_732=new tangler.widget.DialogWrapper("author-dlg",{autoHeight:true,width:240,resizable:false,draggable:true,modal:false,shadow:false});_732.getDialog().getEl().on("mouseover",_self._onAuthorDialogMouseOver);_732.getDialog().getEl().on("mouseout",_self._onAuthorDialogMouseOut);}tangler.util.Element.removeChildNodes("messageAuthorDetails");tangler.util.Element.getEl("messageAuthorDetails").appendChild(tangler.util.Element.createLoadingElement());if(_77f==-1&&_781!=null){_self._getanonymousProfileCallback(_781,_780);}else{DWRUserHandler.getUserProfile(_77f,{callback:function(_782){_self._getUserProfileCallback(_782,_780);},errorHandler:function(_783){alert(_783);}});}_732.showDialog({"element":tangler.util.Element.getEl(_780)});},_onAuthorUnfocused:function(){if(_734==null){_734=new Ext.util.DelayedTask();}_734.delay(500,function(){if(_732&&!_733){_732.hide();}},this);},_onAuthorDialogMouseOver:function(){_733=true;},_onAuthorDialogMouseOut:function(){if(_733){_733=false;_self._onAuthorUnfocused();}},_removeMessageCallback:function(_784){var _785=new tangler.domain.MessageElement(_784.detail,_784.permissions,_784.auditHistory);_785.removeElement();var _786=document.getElementById("quoteMessage-"+_784.detail.globalId);if(_786!=null){_786.parentNode.removeChild(_786);}if(_785.checkAndRemoveMessageAuthor(_739)){_self._updatePreviousAuthorDetails();}delete _785;_735.focusInput();},_onRepostMessage:function(_787){return function(){var _788=Ext.get("message-"+_787);var _789=tangler.cache.CacheManager.getMessage(_787);if(_788!=null&&_789!=null){_788.dom.parentNode.removeChild(_788.dom);_self._processSendingMessage(_789.body);}};},_onEditMessage:function(_78a){return function(){var _78b=tangler.util.Element.getEl("message-"+_78a);var _78c=tangler.util.Element.getElementsByClassName(_78b,"div",["msgBody"])[0];var _78d=false;if(_73a==null){_73a=new tangler.widget.DialogWrapper("editMessage-dlg",{width:485,height:290,resizable:false,draggable:false,acceptLabel:"Send",acceptFunction:function(){if(_736){_736.submit();}_73a.hide();},declineLabel:"Cancel",declineFunction:function(){_73a.hide();}});_73a.addListener("beforeHide",function(_78e){_736.resetInput();_736.hideInput();_736.focusInput();});Ext.get("editMessageInput").dom.value=_78c.innerHTML;_78d=true;_736.showInput({simpleButtons:tangler.info.Page.isEmbed()});}_736.setSubmitFunction(_self._editMessage);if(_73a.isVisible()){return;}var _78f=document.getElementById("quoteMessage-"+_78a);var _790=null;var _791=null;if(!tangler.util.StringUtil.isEmpty(_78f)){var _792="";_792=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_78f.innerHTML);var msg="";if(!tangler.util.StringUtil.isEmpty(_792)){_792=_792.replace(/"/g,"");if(_792.length>80){msg=_792.substring(_792.indexOf(":")+1,80)+"...";}else{msg=_792.substring(_792.indexOf(":")+1,_792.length)+"...";}_790=_792.substring(0,_792.indexOf(":"));_791=" <p id=\"quoteMsg\" class=\"p\"> <strong>"+_790+" :</strong><br> "+msg+" </p>";}}_73a.setTitle("Edit message");var _794=Ext.get("quoteMessage-div");if(_791==null){_794.dom.style.display="none";}else{_794.dom.innerHTML=_791;_794.dom.style.display="block";}_73a.showDialog();_736._editor.show();if(!_78d){_736.setInputContent(_78c.innerHTML);}_738=_78a;};},_onClickQuoteButton:function(_795){return function(){if(_73a==null){_73a=new tangler.widget.DialogWrapper("editMessage-dlg",{height:290,resizable:false,draggable:false,acceptLabel:"Send",acceptFunction:function(){if(_736){_74e=true;_736.submit();_73a.hide();}},declineLabel:"Cancel",declineFunction:function(){_74e=false;_73a.hide();}});_736.showInput({simpleButtons:false});}_736.setSubmitFunction(_self._sendMessage);var _796=tangler.cache.CacheManager.getMessage(_795);_74b=_795;var _797=_796.body;_797=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_797);var _798=null;if(!tangler.util.StringUtil.isEmpty(_797)){if(_797.length>100){_797=_797.substring(0,100)+"...";}if(_796.author.anonymous){_798=_796.anonymousDetail.anonymousScreenName;_74c="<quote>"+_796.anonymousDetail.anonymousScreenName+" said : \""+_797+"\"</quote>";}else{_798=_796.author.screenName;_74c="<quote>"+_796.author.screenName+" said : \""+_797+"\"</quote>";}if(_797.length>50){_797=_797.substring(0,50)+"...";}else{_797=_797+"...";}}_73a.addListener("beforeHide",function(_799){_736.resetInput();_736.hideInput();_736.focusInput();});_73a.setTitle("Quote message");if(_73a.isVisible()){return;}_73a.showDialog();var _79a=Ext.get("quoteMessage-div");var _79b=" <p id=\"quoteMsg\" class=\"p\"> <strong>"+_798+" said :</strong><br> "+_797+" </p>";_79a.dom.innerHTML=_79b;_79a.dom.style.display="block";_736._editor.show();};},_onDeleteMessage:function(_79c){return function(){if(_73b==null){_73b=new tangler.widget.DialogWrapper("deleteMessage-dlg",{minHeight:100,width:330,height:130,draggable:false,resizable:false,acceptLabel:"Yes",defaultFocus:"Yes",acceptFunction:function(){_73b.hide();if(_739!=null&&_739!=0){MessageHandler.removeMessage(_739,{callback:_self._removeMessageCallback,errorHandler:function(_79d){alert("Failed to remove message");_735.focusInput();}});}},declineLabel:"No",declineFunction:function(){_73b.hide();_735.focusInput();}});}if(_73b.isVisible()){return;}var _79e=tangler.util.Element.getEl("message-"+_79c);var _79f=tangler.util.Element.getElementsByClassName(_79e,"div",["msgBody"])[0];_739=_79c;_73b.showDialog();};},_highlight:function(_7a0){return function(){tangler.util.Element.getEl("message-"+_7a0).dom.className+=" highlight";};},_removeHighlight:function(_7a1){return function(){tangler.util.Element.getEl("message-"+_7a1).dom.className=tangler.util.Element.getEl("message-"+_7a1).dom.className.replace(new RegExp(" highlight\\b"),"");};},_buildMessage:function(_7a2,_7a3){var _7a4=tangler.info.Session.getMessageLastViewedDate();var utc=_7a2.detail.created.toUTCString();var _7a6=new Date();var _7a7=tangler.util.Options.getOptionalArgument("lastRead",_7a3,0);var dom=tangler.util.Options.getOptionalArgument("fragment",_7a3,tangler.util.Element.getEl("messages"));var _7a9=tangler.util.Options.getOptionalArgument("doSort",_7a3,false);if(_7a2.detail.globalTopicId==tangler.info.Session.getTopicId()){if(_7a2.permissions.quotable){var _7aa=tangler.util.StringUtil.getQuoteMessageOrMessageBody(_7a2.detail.body,false);var _7ab=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_7aa);if(_7ab==null||_7ab==""){_7a2.permissions.quotable=false;}}var msg=new tangler.domain.MessageElement(_7a2.detail,_7a2.permissions,_7a2.auditHistory);_7a3=_self._setCreateMessageEventArguments(_7a3?_7a3:{},_7a2);var _7ad=msg.createMessage(dom,_7a3);_740=_7a2.detail.author.globalId;_741=_7a2.detail.author.screenName;if(_7a2.detail.author.screenName=="anonymousUser"){_741=_7a2.detail.anonymousDetail.anonymousScreenName;}delete msg;}},_buildMessages:function(_7ae,_7af){var _7b0=tangler.util.formatter.formatDateTime(_73f);var _7b1=0;for(var i=0;i<_7ae.length;++i){if(_7ae[i].auditHistory&&_7ae[i].auditHistory.operation=="DELETE"){continue;}_self._buildMessage(_7ae[i],_7af);var _7b3=tangler.util.formatter.formatDateTime(_7ae[i].detail.lastModified);if((_7b0==0&&i==0)||(_7b3<_7b0)){_7b1=_7ae[i].detail.globalId;}if(_7b3>tangler.info.Session.getMessageLastViewedDate()){tangler.info.Session.setMessageLastViewedDate(_7b3);}}return _7b1;},_buildOlderMessage:function(_7b4,_7b5,_7b6){var _7b7=tangler.info.Session.getMessageLastViewedDate();var utc=_7b4.detail.created.toUTCString();var _7b9=new Date();var _7ba=tangler.util.Options.getOptionalArgument("lastRead",_7b5,0);var dom=tangler.util.Options.getOptionalArgument("fragment",_7b5,tangler.util.Element.getEl("messages"));var _7bc=tangler.util.Options.getOptionalArgument("doSort",_7b5,false);if(_7b4.detail.globalTopicId==tangler.info.Session.getTopicId()){if(_7b4.permissions.quotable){var _7bd=tangler.util.StringUtil.getQuoteMessageOrMessageBody(_7b4.detail.body,false);var _7be=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_7bd);if(_7be==null||_7be==""){_7b4.permissions.quotable=false;}}var msg=new tangler.domain.MessageElement(_7b4.detail,_7b4.permissions,_7b4.auditHistory);_7b5=_self._setCreateMessageEventArguments(_7b5?_7b5:{},_7b4);var _7c0=msg.createOlderMessage(dom,_7b5,_7b6);_740=_7b4.detail.author.globalId;_741=_7b4.detail.author.screenName;if(_7b4.detail.author.screenName=="anonymousUser"){_741=_7b4.detail.anonymousDetail.anonymousScreenName;}delete msg;}},_buildOlderMessages:function(_7c1,_7c2){var _7c3=tangler.util.formatter.formatDateTime(_73f);var _7c4=0;var _7c5=0;for(var i=0;i<_7c1.length;++i){if(_7c1[i].auditHistory&&_7c1[i].auditHistory.operation=="DELETE"){_7c5--;continue;}_self._buildOlderMessage(_7c1[i],_7c2,_7c5);_7c5++;var _7c7=tangler.util.formatter.formatDateTime(_7c1[i].detail.lastModified);if((_7c3==0&&i==0)||(_7c7<_7c3)){_7c4=_7c1[i].detail.globalId;}if(_7c7>tangler.info.Session.getMessageLastViewedDate()){tangler.info.Session.setMessageLastViewedDate(_7c7);}}return _7c4;},_setCreateMessageEventArguments:function(_7c8,_7c9){_7c8.onModifyMouseOver=_self._highlight(_7c9.detail.globalId);_7c8.onModifyMouseOut=_self._removeHighlight(_7c9.detail.globalId);_7c8.onDeleteMouseOver=_self._highlight(_7c9.detail.globalId);_7c8.onDeleteMouseOut=_self._removeHighlight(_7c9.detail.globalId);_7c8.onDeleteClick=_self._onDeleteMessage(_7c9.detail.globalId);_7c8.onEditMouseOver=_self._highlight(_7c9.detail.globalId);_7c8.onEditMouseOut=_self._removeHighlight(_7c9.detail.globalId);_7c8.onEditClick=_self._onEditMessage(_7c9.detail.globalId);_7c8.onQuoteClick=_self._onClickQuoteButton(_7c9.detail.globalId);_7c8.onQuoteMouseOver=_self._highlight(_7c9.detail.globalId);_7c8.onQuoteMouseOut=_self._removeHighlight(_7c9.detail.globalId);_7c8.onTimespanMouseOver=_self._highlight(_7c9.detail.globalId);_7c8.onTimespanMouseOut=_self._removeHighlight(_7c9.detail.globalId);return _7c8;},_setCreateRepostEventArguments:function(_7ca,_7cb){_7ca.onRepostMouseOver=_self._highlight(_7cb);_7ca.onRepostMouseOut=_self._removeHighlight(_7cb);_7ca.onRepostClick=_self._onRepostMessage(_7cb);return _7ca;},_isMessageEmpty:function(_7cc){var _7cd=_7cc.replace(/&nbsp;/g,"");_7cd=_7cd.replace(/<p>/g,"");_7cd=_7cd.replace(/<\/p>/g,"");_7cd=_7cd.replace(/<ul>/g,"");_7cd=_7cd.replace(/<\/ul>/g,"");_7cd=_7cd.replace(/<ol>/g,"");_7cd=_7cd.replace(/<\/ol>/g,"");_7cd=_7cd.replace(/<br \/>/g,"");_7cd=_7cd.replace(/<strong>/g,"");_7cd=_7cd.replace(/<\/strong>/g,"");_7cd=_7cd.replace(/<em>/g,"");_7cd=_7cd.replace(/<\/em>/g,"");_7cd=_7cd.replace(/<u>/g,"");_7cd=_7cd.replace(/<\/u>/g,"");_7cd=_7cd.replace(/<del>/g,"");_7cd=_7cd.replace(/<\/del>/g,"");if(_7cd.trim().length==0){return true;}if(_7cd.trim().length==1&&_7cd.charCodeAt(0)==160){return true;}return false;},_getMessagesAndLastReadError:function(_7ce){_messageListLoaded=false;tangler.util.Element.getEl(_73d).dom.innerHTML="";var li=tangler.util.Element.createNode("li",{attributes:[["class","error"]],children:[document.createTextNode("An error occurred while retrieving messages."+_7ce),tangler.util.Element.createNode("br")]});li.className="error";tangler.util.Element.getEl(_73d).dom.appendChild(li);var _7d0=tangler.util.Element.createNode("a",{attributes:[["href","#"]],children:[document.createTextNode("Try again")]});li.appendChild(_7d0);},heartbeatCallback:function(){},onBeforeHeartbeat:function(){},_getMessagesAndLastReadCallback:function(_7d1){tangler.util.Element.removeChildNodes(_73d);tangler.cache.CacheManager.clearMessageCache();_73f=_7d1.lastRead;var _7d2=50;var _7d3=_7d1.totalAndReadMessageCountReport.totalMessageCount;var _7d4=_7d1.totalAndReadMessageCountReport.globalParentId;if(_7d3>_7d2){var _7d5=Ext.get("viewOldMessageButton");_7d5.dom.style.display="block";_7d5.on("click",_self._viewOlderMessages);_74a=_7d2;}_self._showTopicHeader(_7d1.topic);_730.setTopicLifecycle(_7d1.topic);var _7d6=!tangler.info.Session.getSecurity().isAuthenticated();var _7d7=_self._buildMessages(_7d1.messages,{lastRead:_73f,ignoreLastRead:_7d6});if(_737!=0&&tangler.util.Element.getEl("message-"+_737)){tangler.util.Helper.scrollElementTo("message-"+_737,"messageViewPort");tangler.util.Element.getEl("message-"+_737).highlight("fffbb4",{easing:"easeIn",duration:10});}else{if(_737!=0&&tangler.util.Element.getEl("quoteMessage-"+_737)){tangler.util.Helper.scrollElementTo("quoteMessage-"+_737,"messageViewPort");tangler.util.Element.getEl("quoteMessage-"+_737).highlight("fffbb4",{easing:"easeIn",duration:10});}else{tangler.util.Helper.scrollElementToEnd("messageViewPort");}}if(_7d1.messages.length>0){var _7d8=tangler.info.Session.getMessageLastViewedDate();var _7d9=tangler.util.formatter.formatDateTime(_73f);if(_7d9==0||(_7d9!=_7d8)){_self._sendTopicLastMessageViewed(tangler.info.Session.getTopicId());}}if(_7d1.messages.length==0){var now=new Date();var _7db=Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes(),now.getSeconds(),0);if(_7db!=null&&tangler.info.Session.getSecurity().isAuthenticated()){DWRTopicHandler.setTopicLastMessageViewed(tangler.info.Session.getTopicId(),_7db);}}var _7dc=_7d1.messages[_7d1.messages.length-1];var _7dd=new Date().addMinutes(-15);_731.shortHeartbeat({beforeHeartbeat:tangler.manager.TopicMessageList.onBeforeHeartbeat,callback:tangler.manager.TopicMessageList.heartbeatCallback});if(!tangler.info.Session.getSecurity().isAuthenticated()&&!tangler.info.Page.isEmbed()){new Ext.util.DelayedTask(function(){Ext.get("screenName").focus();},_self).delay(200);}},_viewOlderMessages:function(){Ext.get("viewOldMessageButton").dom.style.display="none";Ext.get("olderMessageLabel").dom.style.display="block";MessageHandler.getOlderMessages(tangler.info.Session.getTopicId(),_74a,{callback:_self._getOlderMessageReadCallback,errorHandler:_self._getMessagesAndLastReadError,timeout:_742});},_getOlderMessageReadCallback:function(_7de){var _7df=100;var _7e0=_7de.totalAndReadMessageCountReport.totalMessageCount;var _7e1=_7de.totalAndReadMessageCountReport.globalParentId;var _7e2=parseInt(_74a+_7df);if(_7e0>_7e2){Ext.get("olderMessageLabel").dom.style.display="none";Ext.get("viewOldMessageButton").dom.style.display="block";_74a=_74a+_7df;}else{Ext.get("viewOldMessageButton").dom.style.display="none";Ext.get("olderMessageLabel").dom.style.display="none";}_73f=_7de.lastRead;var _7e3=!tangler.info.Session.getSecurity().isAuthenticated();var _7e4=_self._buildOlderMessages(_7de.messages,{lastRead:_73f,ignoreLastRead:_7e3});var _7e5=null;if(!tangler.cache.CacheManager.isMessageCacheEmpty()){_7e5=tangler.cache.CacheManager.getMessageCache();}if(_7e5!=null&&_7e5[0].globalId!=0&&tangler.util.Element.getEl("message-"+_7e5[0].globalId)){tangler.util.Helper.scrollElementTo("message-"+_7e5[0].globalId,"messageViewPort");tangler.util.Element.getEl("message-"+_7e5[0].globalId).highlight("fffbb4",{easing:"easeIn",duration:5});}else{tangler.util.Helper.scrollElementToEnd("messageViewPort");}if(_7de.messages.length>0){var _7e6=tangler.info.Session.getMessageLastViewedDate();var _7e7=tangler.util.formatter.formatDateTime(_73f);if(_7e7==0||(_7e7!=_7e6)){_self._sendTopicLastMessageViewed(tangler.info.Session.getTopicId());}}},_scrollToMessage:function(_7e8){if(_7e8>0){tangler.util.Helper.scrollElementTo("message-"+_7e8,"messageViewPort");}},_sendTopicLastMessageViewed:function(_7e9){if(tangler.info.Session.getSecurity().isAuthenticated()){if(_7e9==0){return;}var _7ea=tangler.info.Session.getMessageLastViewedDate();var dt=tangler.util.formatter.getDateObject(_7ea);if(dt==null||dt=="undefined"){return;}DWRTopicHandler.setTopicLastMessageViewed(_7e9,tangler.util.formatter.getDateObject(_7ea));}},_getanonymousProfileCallback:function(_7ec,_7ed){var _7ee=tangler.util.Helper.getCnameValue("/images/defaulticons/contact_48.png");var _7ef=tangler.info.Page.wrapCnameContextUrl("/images/defaulticons/contact_48.png",_7ee);var _7f0="";var _7f1=1;var _7f2=1;var _7f3=_7ec.anonymousScreenName;_74d=tangler.manager.TopicPage.getBannedUserList();if((_74d==null||!_74d.contains(_7ec.remoteIp))&&tangler.manager.TopicPage.isUserBannPermission()==true){_7f0="<input type='button' id='banButton' value='Ban!' onclick='_self._onClickUserBanButton("+_7f2+",\""+_7f3+"\",\""+_7ec.remoteIp+"\","+_7f1+")'/>";}_74f.overwrite("messageAuthorDetails",{authorAvatarUrl:_7ef,authorScreenName:"<strong>Guest: </strong>"+tangler.util.Helper.escapeHtml(_7ec.anonymousScreenName),banButton:_7f0,authorLocation:"<strong>IP: </strong>"+_7ec.remoteIp});tangler.util.Element.hideElement("me");tangler.util.Element.hideElement("authorFullName");tangler.util.Element.hideElement("authorActions");},_getUserProfileCallback:function(_7f4,_7f5){var _7f6=tangler.util.Helper.getCnameValue("/images/defaulticons/contact_48.png");var _7f7=tangler.info.Page.wrapCnameContextUrl("/images/defaulticons/contact_48.png",_7f6);var _7f8="";var _7f9="";var _7fa="";var _7fb="";var gUID=0;var _7fd=_7f4.publicProfile.contact?"Chat to ":"Follow ";if(_7f4.publicProfile.profileDetail){gUID=_7f4.publicProfile.profileDetail.globalId;if(_7f4.publicProfile.profileDetail.avatar!=null){_7f7=tangler.util.Avatar.getAvatarUrl(_7f4.publicProfile.profileDetail.avatar,{height:48,width:48,avatarType:"user"});}_7f8=_7f4.publicProfile.profileDetail.name?_7f4.publicProfile.profileDetail.name.fullName:"";_7f9="";_7fa=_7f4.publicProfile.profileDetail.occupation?_7f4.publicProfile.profileDetail.occupation:"";_7fb=_7f4.publicProfile.profileDetail.gender?_7f4.publicProfile.profileDetail.gender.description:"";if(_7f4.publicProfile.profileDetail.location){if(_7f4.publicProfile.profileDetail.location.city!=null&&_7f4.publicProfile.profileDetail.location.city.length>0){_7f9+=_7f4.publicProfile.profileDetail.location.city;}if(_7f4.publicProfile.profileDetail.location.state!=null&&_7f4.publicProfile.profileDetail.location.state.length>0){_7f9+=(((_7f9.length>0)?", ":"")+_7f4.publicProfile.profileDetail.location.state);}if(_7f4.publicProfile.profileDetail.location.country.countryName&&_7f4.publicProfile.profileDetail.location.country.countryName!="null"){_7f9+=(((_7f9.length>0)?", ":"")+_7f4.publicProfile.profileDetail.location.country.countryName);}}}var _7fe=tangler.util.Helper.escapeHtml(_72e.getFocusAuthorScreenName());var _7ff=tangler.info.Page.wrapContextUrl("/user/"+_7fe);if(_7f4.followed){_7fd="Stop Following";}else{_7fd="Follow";}var _800="Add as Friend";var _801=(_72f.getAuthorId()==gUID);var _802=0;var _803="";_74d=tangler.manager.TopicPage.getBannedUserList();var _804="0";if(!_801&&(_74d==null||!_74d.contains(gUID))&&tangler.manager.TopicPage.isUserBannPermission()==true){_803="<input type='button' id='banButton' value='Ban!' onclick='_self._onClickUserBanButton("+gUID+",\""+_7fe+"\",\""+_804+"\","+_802+")'/>";}_74f.overwrite("messageAuthorDetails",{authorAvatarUrl:_7f7,authorScreenName:_7fe,profileUrl:_7ff,authorFullName:_7f8,authorLocation:_7f9,authorOccupation:_7fa,authorGender:_7fb,interactionUrl:"javascript:void(null);",addFriendLabel:_800,interactionType:_7fd,banButton:_803});var _805=tangler.util.Element.getEl("followUserAuthorPopup");if(_805){if(!tangler.info.Session.getSecurity().isAuthenticated()){Ext.EventManager.addListener(_805,"click",tangler.manager.ProfileState.onFollowAsAnonymousUser,null,{preventDefault:true});}else{Ext.EventManager.addListener(_805,"click",tangler.manager.ProfileState.onToggleFollow,{button:_805,userId:gUID,user:_7fe,followed:_7f4.followed},{preventDefault:true});}}var _806=tangler.util.Element.getEl("addAsFriendAuthorPopup");if(_806){Ext.EventManager.addListener(_806,"click",tangler.manager.ProfileState.onAddAsFriend,{button:_806,userId:gUID},{preventDefault:true});}tangler.util.Element.hideElement("me");if(!tangler.info.Session.getSecurity().isAuthenticated()){tangler.util.Element.hideElement("interactionLink");tangler.util.Element.hideElement("friend");}if(_72e.getFocusAuthorId()==tangler.info.Session.getUserId()){tangler.util.Element.hideElement("authorActions");tangler.util.Element.showElement("me");}if(tangler.info.Page.isEmbed()){tangler.util.Element.getEl("profileLink").dom.href="javascript:void(0);";tangler.util.Element.getEl("profileLink").on("click",function(){window.open(_7ff);},this,{preventDefault:true});}if(!_7f4.publicProfile.contact){}else{tangler.util.Element.hideElement("friendOpt");}if(_7f8==""){tangler.util.Element.hideElement("authorFullName");}if(_7f9==""){tangler.util.Element.hideElement("authorLocation");}if(_7fa=""){tangler.util.Element.hideElement("authorOccupation");}if(_7fb==""){tangler.util.Element.hideElement("authorGender");}},_onClickUserBanButton:function(_807,_808,_809,_80a){if(confirm("Are you sure that you want to ban this user?")){var _80b=tangler.info.Session.getTopicId();var _80c="USER_ID|"+_807+"|SCREEN_NAME|"+_808+"|ANONYMOUS_USER|"+_80a+"|REMOTE_IP_ADDRESS|"+_809+"";var _80d=-1;MessageHandler.createMessage(_80b,_80c,_80d,{callback:function(msg){_self._updateCreatedMessage(msg);},errorHandler:_self._createMessageFailed});if(_74d==null){if(_80a==0){_74d[0]=_807;}else{_74d[0]=_809;}}else{var _80f=_74d.length;if(_80a==0){_74d[_80f]=_807;}else{_74d[_80f]=_809;}}}},_createMessageCallback:function(_810){if(_73e!=null&&_73e.isVisible()){_73e.hide();}if(_810==null){_735.setInputContent(messagePending);_735.focusInput();return;}_73f=_810.detail.lastModified;_self._buildMessage(_810,{ignoreLastRead:true});_self._scrollToMessage(_810.detail.globalId);tangler.info.Session.setMessageLastViewedDate(tangler.util.formatter.formatDateTime(_810.detail.lastModified));if(tangler.info.Session.getSecurity().isAuthenticated()&&!_72f.getTopicWatched()){_72f.setTopicWatched(true);}if(tangler.util.Helper.canScroll("messageViewPort","messages")){tangler.util.Helper.scrollElementToEnd("messageViewPort");}_self._sendTopicLastMessageViewed(tangler.info.Session.getTopicId());if(Ext.isSafari){}_745=true;},_createMessageFailed:function(_811){if(_73e!=null&&_73e.isVisible()){_73e.hide();}if(_811=="Banned User"){alert("You are banned from this topic!");var _812=tangler.util.Element.getEl("messageEditorOverlay");var _813=tangler.util.Element.createNode("div",{attributes:[["class","ieFill"]]});var _814="You have been banned from this conversation. The reason being that your contributions to this topic have resulted in the topic creator electing to ban you.";var _815=tangler.util.Element.createNode("div",{attributes:[["class","input"]]});var msg=tangler.util.Element.createNode("div",{attributes:[["class","message"]]});var br=tangler.util.Element.createNode("br");var h4=tangler.util.Element.createNode("h3",{attributes:[[]],children:[document.createTextNode(_814)]});var _819=tangler.util.Element.createNode("div",{attributes:[["id","tnc_div"],["class","tnc_div"]],children:[_813,msg,_815,br,h4]});tangler.util.Element.removeChildNodes("messageEditorOverlay");_812.appendChild(_819);_812.show();}else{alert("We were unable to send your message, please try again");_735.setInputContent(messagePending);_735.focusInput();}},_updateCreatedMessage:function(_81a,_81b){if(_81a.detail.parentMessageId!=null&&_81a.detail.parentMessageId<0){alert("You have successfully banned this user from this topic.");return;}var _81c=tangler.util.Element.getEl("message-"+_81b);if(_73e!=null&&_73e.isVisible()){_73e.hide();}if(_81a.permissions.quotable){var _81d=tangler.util.StringUtil.getQuoteMessageOrMessageBody(_81a.detail.body,false);var _81e=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_81d);if(_81e==null||_81e==""){_81a.permissions.quotable=false;}}var _81f=new tangler.domain.MessageElement(_81a.detail,_81a.permissions,_81a.auditHistory);var _820={};_74b=0;_74c="";_820=_self._setCreateMessageEventArguments(_820,_81a);_81f.updateElementOnCallback(_81b,_820,_81a);if(tangler.manager.TopicPage.isTwitterChatEnabled()&&tangler.manager.TopicPage.isTwitterAuth()){var _821=tangler.util.StringUtil.getTextAndRemoveHtmlTags(_81a.detail.body);var _822="";var _823="";var _824=_81a.detail.globalId;if(_81a.detail.body.match(/<img.*?src=\"(.*?)\".*?\/>/gi)){if(_81a.detail.body.match(/<img.*?src=\".*\/plain\/js\/TinyMCEEditor\/plugins\/emotions\/img\/.*?\".*?\/>/gi)){_822="";}else{_822="[PIC:"+_824+"]";}}if(_81a.detail.body.match("(<object[^>]*>)?(s*<param[^>]*>s*(</param>)?)*(s*<param[^>]*>s*(</param>)?s*)*(</object>)")){_822+="[VIDEO:"+_824+"]";}_823=_822+_821;if(_823!=""){Ext.fly("posttweet").removeClass("twbuttonEnabled");Ext.fly("posttweet").addClass("twbuttonDisabled");var _825=tangler.manager.TopicPage.getTwitterTag();var tId=tangler.manager.TopicState.getTopicId();MessageHandler.postToTwitter(tId,_823,_825,_824,{callback:function(){Ext.fly("posttweet").removeClass("twbuttonDisabled");Ext.fly("posttweet").addClass("twbuttonEnabled");Ext.fly("notify_div").applyStyles({display:"block"});window.setTimeout(function(){Ext.fly("notify_div").applyStyles({display:"none"});},4000);},errorHandler:function(_827){if(_827=="Status is a duplicate."){Ext.fly("notify_div_duplicate_status").applyStyles({display:"block"});}else{Ext.fly("notify_div_error").applyStyles({display:"block"});}Ext.fly("posttweet").removeClass("twbuttonDisabled");Ext.fly("posttweet").addClass("twbuttonEnabled");}});}}delete _81f;},_showTopicHeader:function(_828,_829){_730.setTopicLifecycle(_828);var _82a=_828.detail.topicDetail.name;var _82b=_82a==null?"General Conversation":_82a;_82b=tangler.util.Helper.escapeHtml(_82b);var _82c="http://"+window.location.host+tangler.info.Page.wrapContextUrl("/topics/viewTopic.action?tId="+tangler.info.Session.getTopicId());tangler.util.Element.getEl("topicName").update(_82b);var _82d=tangler.util.Element.getEl("userFollowOption");var _82e=_82d==null?30:_82d.getWidth()+80;if(tangler.info.Page.isEmbed()){_82d=tangler.util.Element.getEl("topicOptionsContainer");_82e=_82d==null?30:_82d.getWidth()+80;}},_autoPostDaemon:function(){if(!_745){return;}_745=false;_735.setInputContent(_self._makeRandomStr());_self.submitMessage();},_makeRandomStr:function(){var msg="";var _830=_743.length;var _831=Math.floor(Math.random()*10)+1;for(i=0;i<_831;i++){for(j=0;j<8;j++){var _832=Math.floor(Math.random()*_830);msg+=_743.charAt(_832);}msg+=" ";}msg="<strong>"+(_744++)+"</strong> "+msg;return msg;}});return new _750();}();
tangler.widget.SocialNWSites={twitter:"twitter",facebook:"facebook",digg:"digg"};tangler.widget.TopicWidgets=function(){var _539="grabLinkTxt";var _53a="grabLinkBtn";var _53b="grabEmbedTxt";var _53c="grabEmbedBtn";var _53d="twittBtn";var _53e="facebookBtn";var _53f="diggBtn";var _540=null;var _541="grabPrivateUrl";var _542="grabPrivateUrlBtn";var _543=false;var _544;var _545=0;var _546="";var _547="http://tlive.me/";var _548=false;var _549="";var _54a=function(){this.topicAuthorId=0;_54a.superclass.constructor.call(this);};Ext.extend(_54a,Ext.util.Observable,{init:function(_54b){_545=tangler.util.Options.getOptionalArgument("topicId",_54b,0);_546=tangler.util.Options.getOptionalArgument("topicName",_54b,"");_548=tangler.util.Options.getOptionalArgument("isPrivate",_54b,0);_549=tangler.util.Options.getOptionalArgument("topicEncId",_54b,0);_543=tangler.util.Options.getOptionalArgument("isFirstVisit",_54b,0);if(!_548){_547=_547+_545;}else{_547=_547+"p/"+_549;}this._topicId=_545;this._topicName=_546;this._shortUrl=_547;this.setTopicLink();this.setEmbedText();if(_548&&_543){this.setPrivateTopicLink();}if(!_548){Ext.EventManager.addListener(Ext.get(_53e),"click",this.faceBookIt,this,{preventDefault:true});}var _54c=tangler.info.Page.wrapFullContextUrl("/flash/ZeroClipboard.swf");ZeroClipboard.setMoviePath(_54c);this.clipBoard=new ZeroClipboard.Client();this.clipBoard.setHandCursor(true);_widgetRef=this;Ext.EventManager.addListener(Ext.get(_53a),"mouseover",function(evt,t,o){this.clipBoard.setText(document.getElementById("grabLinkTxt").value);if(this.clipBoard.div){this.clipBoard.receiveEvent("mouseout",null);this.clipBoard.reposition(evt.target);}else{this.clipBoard.glue(evt.target);}this.clipBoard.receiveEvent("mouseover",null);},_widgetRef,{preventDefault:true});Ext.EventManager.addListener(Ext.get(_53c),"mouseover",function(evt,t,o){this.clipBoard.setText(document.getElementById("grabEmbedTxt").value);if(this.clipBoard.div){this.clipBoard.receiveEvent("mouseout",null);this.clipBoard.reposition(evt.target);}else{this.clipBoard.glue(evt.target);}this.clipBoard.receiveEvent("mouseover",null);},_widgetRef,{preventDefault:true});if(_548&&_543){Ext.EventManager.addListener(Ext.get(_542),"mouseover",function(evt,t,o){this.clipBoard.setText(document.getElementById("grabPrivateUrl").value);if(this.clipBoard.div){this.clipBoard.receiveEvent("mouseout",null);this.clipBoard.reposition(evt.target);}else{this.clipBoard.glue(evt.target);}this.clipBoard.receiveEvent("mouseover",null);},_widgetRef,{preventDefault:true});}},grabLink:function(){},embedTopic:function(){},twittIt:function(){this._postOnSWNSitesResponse(tangler.widget.SocialNWSites.twitter);DWRTopicHandler.addPostOnSNWService(tangler.widget.SocialNWSites.twitter,this._topicId,{callback:function(data){},errorHandler:this._postOnSWNSitesResponseError});},faceBookIt:function(){this._postOnSWNSitesResponse(tangler.widget.SocialNWSites.facebook);DWRTopicHandler.addPostOnSNWService(tangler.widget.SocialNWSites.facebook,this._topicId,{callback:function(data){},errorHandler:this._postOnSWNSitesResponseError,async:false});},diggIt:function(){this._postOnSWNSitesResponse(tangler.widget.SocialNWSites.digg);DWRTopicHandler.addPostOnSNWService(tangler.widget.SocialNWSites.digg,this._topicId,{callback:function(data){},errorHandler:this._postOnSWNSitesResponseError});},shareIt:function(){if(_544==null){_544=new tangler.widget.DialogWrapper("shareTopic-dlg",{height:160,resizable:false,draggable:false,acceptLabel:"Invite",acceptFunction:function(){_544.hide();},declineLabel:"Cancel",declineFunction:function(){_544.hide();}});_544.addListener("beforeHide",function(_559){alert("Emails sent!");});}if(_544.isVisible()){return;}_544.showDialog();},setAction:function(_55a){alert(_55a);},setTopicLink:function(){if(this._topicId!=0){Ext.get(_539).dom.value=this._shortUrl;}},setPrivateTopicLink:function(){Ext.get(_541).dom.value=tangler.info.Page.wrapFullContextUrl("/conversation/"+tangler.manager.TopicPage.getTopicEncId());},setEmbedText:function(){if(this._topicId!=0){var _55b=null;if(!_548){_55b=tangler.info.Page.wrapFullContextUrl("/widget/embedtopic.js?id="+this._topicId);}else{_55b=tangler.info.Page.wrapFullContextUrl("/widget/embedtopic.js?id="+_549);}if(tangler.info.Page.isDebug()){_55b+="&cUrl="+tangler.info.Page.wrapFullContextUrl("");}var _55c=null;if(!_548){_55c="<p style=\"width:100%;height:714px;\" id=\"tangler-embed-topic-"+this._topicId+"\"></p><script src=\""+_55b+"\"></script>";}else{_55c="<p style=\"width:100%;height:714px;\" id=\"tangler-embed-topic-"+_549+"\"></p><script src=\""+_55b+"\"></script>";}Ext.get(_53b).dom.value=_55c;}},_postOnSWNSitesResponse:function(data){var _55e="http://tlive.me/"+tangler.widget.TopicWidgets._topicId;if(data){var _55f="";switch(data){case tangler.widget.SocialNWSites.facebook:_55f="http://www.facebook.com/sharer.php?u="+_55e;break;case tangler.widget.SocialNWSites.digg:_55f="http://digg.com/submit?phase=2&url="+_55e;break;}var win=null;if(data==tangler.widget.SocialNWSites.facebook){win=window.open(_55f,"newwindow","width=700,height=307,resizable=0");}else{win=window.open(_55f);}if(!win){alert("There was an error when tanglerlive tried to post on "+data+"!\nPlease check if you have blocked pop-ups.");}}},_postOnSWNSitesResponseError:function(_561){alert("Some errors occured during the operation: "+_561);}});return new _54a();}();tangler.manager.TopicPage=function(){var _562=tangler.util.Options;var _563=tangler.manager.TopicMessageList;var _564=tangler.util.Element;var _565=tangler.manager.Comms;var _566=tangler.info.Page;var _567=tangler.util.Helper;var _568=tangler.info.Session;var _569=tangler.widget.TopicWidgets;var _56a=0;var _56b=0;var _56c=false;var _56d;var _56e=false;var _56f=null;var _570=0;var _me=this;var _572=null;var _573=null;var _574=false;var _575;var href=null;var _577;var _578=false;var _579=false;var _57a=null;function renderDiscuss(_57b){_563.init(_57b);var _57c=_56b;if(_57c!=0){_563.getMessagesAndScroll(_57c,_570);}}function onDiscussClicked(){}return {initTopicLayout:function(_57d){var _57e=_564.getEl(_562.getOptionalArgument("messageOverlay",_57d,"messageEditorOverlay"));if(_568.getSecurity().isAuthenticated()&&_57e){_57e.hide();}else{if(_57e){_57e.show();}}var _57f=tangler.info.Page.isEmbed();_566.setView(_57f?tangler.info.ViewType.TopicEmbedDiscuss:tangler.info.ViewType.TopicDiscuss);var _580=_562.getOptionalArgument("topicId",_57d,0);var _581=_562.getOptionalArgument("groupId",_57d,0);_570=_562.getOptionalArgument("messageToShow",_57d,0);_56b=_580;_56a=_581;tangler.info.Session.setGroupId(_581);tangler.info.Session.setTopicId(_580);dwr.engine.beginBatch();DWRGroupHandler.registerGroup(tangler.info.Session.getGroupId());dwr.engine.endBatch();_56d=_562.getOptionalArgument("messagesDiv",_57d,"messages");var _582=_562.getOptionalArgument("topicCreatorId",_57d,0);_56c=(_582==tangler.info.Session.getUserId());_574=_562.getOptionalArgument("bannUserPermission",_57d,0);_575=_562.getOptionalArgument("bannedUserArray",_57d,0);_577=_562.getOptionalArgument("twitterTag",_57d,null);_578=_562.getOptionalArgument("twitterchat",_57d,0);_579=_562.getOptionalArgument("twitterAuth",_57d,false);_57a=_562.getOptionalArgument("topicEncId",_57d,0);Ext.QuickTips.init();renderDiscuss(_57d);if(!_57f){_569.init(_57d);}if(!_568.getSecurity().isAuthenticated()){if(Ext.isSafari){var _583=_564.getEl("messageSendButton");_583.on("focus",function(){document.getElementById("joinAnonymously").focus();},null);}var _584=_564.getEl("joinAnonymously");_584.on("click",this.validateAnonymousJoin,this);_584.on("mouseover",function(){this._inTcCc=true;this._TcnCcFocused();},this);_584.on("mouseout",function(){this._inTcCc=false;this._TcnCcUnFocused();},this);var _585=_564.getEl("tnc_div");_585.on("mouseover",function(){this._inTcCc=true;},this);_585.on("mouseout",function(){this._inTcCc=false;this._TcnCcUnFocused();},this);}},isTopicOwner:function(){return _56c;},isUserBannPermission:function(){return _574;},getBannedUserList:function(){return _575;},getTwitterTag:function(){return _577;},isTwitterChatEnabled:function(){return _578;},setTwitterChatEnabled:function(_586){_578=_586;},isTwitterAuth:function(){return _579;},setTwitterAuth:function(_587){_579=_587;},setTopicEncId:function(_588){this.topicEncId=_588;},getTopicEncId:function(){return _57a;},shutdown:function(_589){DWRGroupHandler.deregisterGroup(tangler.info.Session.getTopicId());},removeTopic:function(){if(confirm("Are you sure that you want to delete this topic?")){window.parent.alertUserOnLeaving=false;DWRTopicHandler.removeTopic(tangler.info.Session.getTopicId(),{callback:this._removeTopicCallback,errorHandler:this._removeTopicErrCallback});}},_removeTopicCallback:function(){alert("The topic was succesfully deleted.\nHowever, it may take a while to remove from cache!");window.location.href="/home";},_removeTopicErrCallback:function(){alert("We were not able to delete that topic.");},initDiscussionPage:function(_58a){},validateAnonymousJoin:function(){if($("screenName").value.trim()==""){this._anonymousJoinCallback("SN:invalid");return;}DWRTopicHandler.joinAnonymously($("screenName").value,$("captchaInput").value,tangler.info.Session.getTopicId(),{callback:this._anonymousJoinCallback,errorHandler:this._anonymousJoinCallbackError});},_anonymousJoinCallback:function(_58b){_564.getEl("captchaError").hide();_564.getEl("screenNameError").hide();if(_58b==""){if(Ext.isSafari){var _58c=_564.getEl("messageSendButton");_58c.on("focus",null,null);}_564.getEl("tnc_div").hide();_564.getEl("messageEditorOverlay").hide();_568.getSecurity().joinAnonymously(true);_568.setUser($("screenName").value);_563.getEditor().focusInput();return;}else{if(_58b==("C:"+$("captchaInput").value)){_564.getEl("captchaError").show();tangler.manager.TopicPage.reloadCaptcha();}else{if(_58b==("SN:"+$("screenName").value)){_564.getEl("screenNameError").dom.title="The Screen Name already exists. Please try another.";_564.getEl("screenNameError").dom.innerHTML="Name taken";_564.getEl("screenNameError").show();tangler.manager.TopicPage.reloadCaptcha();}else{if(_58b=="SN:invalid"){_564.getEl("screenNameError").dom.title="Invalid Screen Name.";_564.getEl("screenNameError").dom.innerHTML="Invalid screen name";_564.getEl("screenNameError").show();tangler.manager.TopicPage.reloadCaptcha();}}}}_564.getEl("captchaInput").dom.value="";},_anonymousJoinCallbackError:function(_58d){alert("Error: "+_58d);},reloadCaptcha:function(){var _58e=_564.getEl("captchaImage").dom.src;var _58f=_58e;var rand=Math.floor(Math.random()*10);if(_58e.endsWith("/tl")){_58f+="/"+rand;}else{_58f+=rand;}Ext.get("captchaImage").dom.src=_58f;},_TcnCcFocused:function(){Ext.get("tnc_div").show();},_TcnCcUnFocused:function(){if(this._TcCcDelayedTask==null){this._TcCcDelayedTask=new Ext.util.DelayedTask();}this._TcCcDelayedTask.delay(1000,function(){if(this._inTcCc==true){return;}Ext.get("tnc_div").fadeOut({endOpacity:0,easing:"easeOut",duration:0.5,remove:false,useDisplay:false,callback:function(){Ext.get("tnc_div").hide();}});},this);},sortAlg:function(a,b){var _593=a.screenName.toLowerCase();var _594=b.screenName.toLowerCase();if(_593<_594){return -1;}else{if(_593>_594){return 1;}else{return 0;}}},presenceEvent:function(_595,_596){var _597=Ext.get("participants");if(_595.length==0){return;}if(tangler.info.Page.isEmbed()){var _598=_564.getEl("chatMembersCount");var _599=_598.dom.innerHTML*1;if(_596){_599--;}else{_599++;}_598.dom.innerHTML=_599;return;}var _59a=_595[0];if(_59a.anonymous&&(_59a.screenName==null||_59a.screenName=="")){return;}var pid="id-"+_59a.screenName+"-"+_59a.globalId;var _59c=_597.child("#"+pid);var _59d=Ext.get("chatMembersCount");var cnt=_59d.dom.innerHTML*1;var _59f=_597.child("#id-anon > #id-anoncnt");if(_59a.screenName=="anonymousUser"){if(_59f!=null){var _5a0=_59f.dom.innerHTML*1;if(_596){_5a0--;}else{_5a0++;}_59f.dom.innerHTML=_5a0;}return;}if(_596){if(_59c!=null){_59c.remove();cnt=cnt-1;_59d.dom.innerHTML=cnt;}return;}if(_59c!=null){return;}var _5a1=_597.createChild({"tag":"li","id":pid});if(_59a.anonymous){_5a1.dom.innerHTML="Guest: "+_59a.screenName;}else{_5a1.dom.innerHTML="<a target='_blank' href='/user/"+_59a.globalId+"'>"+_59a.screenName+"</a>";}cnt=cnt+1;_59d.dom.innerHTML=cnt;},toggleDaemon:function(_5a2){var val=Ext.get("jsDaemonButton").dom.value;if(_572==null){_572={run:_563._autoPostDaemon,interval:_5a2};}if(val=="Stop Test Task"){Ext.TaskMgr.stop(_572);Ext.get("jsDaemonButton").dom.value="Run Test Task";}else{Ext.TaskMgr.start(_572);Ext.get("jsDaemonButton").dom.value="Stop Test Task";}},upLoadUserGroupDetails:function(_5a4){var _5a5=tangler.info.Session.getTopicId();var url=tangler.info.Page.wrapContextUrl("/uploadUsergroup.action?dec=dialog&tId="+_5a5);var _5a7=new tangler.util.Helper.createIframeWindow({url:url,width:700,height:490});_5a7.showWindow({refreshOnClose:false});},onEmptyMessage:function(_5a8){if(_573==null){_573=new tangler.widget.DialogWrapper("emptyMsg-dlg",{minHeight:80,width:260,height:105,draggable:false,resizable:false,acceptLabel:"Leave this page",defaultFocus:"Stay on the page",acceptFunction:function(){window.location.href=href;_573.hide();},declineLabel:"Stay on the page",declineFunction:function(){window.onbeforeunload=confirmExit;_573.hide();}});}if(_573.isVisible()){return;}href=_5a8;_573.showDialog();}};}();
tangler.manager.ProfileState=function(){var _674=null;var _675=function(){this.isFollowed=false;this.isFollower=false;this.isContact=false;this.profileId=0;this.profileOwnerScreenName=null;this.viewerId=0;this.viewType=null;_675.superclass.constructor.call(this);_pState=this;};Ext.extend(_675,Ext.util.Observable,{setFollwer:function(_676){this.isFollower=_676;},getFollower:function(){return this.isFollower;},setFollwed:function(_677){this.isFollowed=_677;},getFollowed:function(){return this.isFollowed;},setProfileId:function(id){this.profileId=id;},getProfileId:function(){return this.profileId;},setViewerId:function(id){this.viewerId=id;},getViewerId:function(){return this.viewerId;},setContact:function(_67a){this.isContact=_67a;},isContact:function(){return this.isContact;},setProfileOwnerScreenName:function(_67b){this.profileOwnerScreenName=_67b;},getProfileOwnerScreenName:function(){return this.profileOwnerScreenName;},onAddAsFriend:function(){var _67c=(this.userId!="undefined"&&this.userId!=null)?this.userId:_pState.profileId;var args={button:this.button};DWRUserHandler.addAsFriend(_67c,"",{callback:function(data){_pState._addedFriendCallbackSuccess(data,args);},errorHandler:_pState._addedFriendCallbackFailure});},onToggleFollow:function(){var _67f=(this.userId!="undefined"&&this.userId!=null)?this.userId:0;var _680=(this.followed!="undefined"&&this.followed!=null)?this.followed:_pState.isFollowed;var args=null;if(_67f==0){_67f=_pState.profileId;args={button:this.button};}else{args=this;}args.followUserId=_67f;DWRUserHandler.toggleFollow(_67f,!_680,{callback:function(data){_pState._toggleCallbackSuccess(data,args);},errorHandler:_pState._toggleCallbackFailure});},_toggleCallbackSuccess:function(_683,args){if(!_683){Ext.MessageBox.show({title:"Message Warning",msg:"There was some problem while executing your request. <br />Please try after sometimes.",buttons:Ext.MessageBox.OK});}var _685="";if(args.userId!=null){var _686=!args.followed?"Stop Following ":"Follow ";_685=_686;args.followed=!args.followed;}else{var _686=!_pState.isFollowed?"Stop Following ":"Follow ";_pState.setFollwed(!_pState.isFollowed);_685=_686;}tangler.util.Element.getEl(args.button).update(_685);Ext.EventManager.removeListener(args.button,"click",tangler.manager.ProfileState.onToggleFollow);Ext.EventManager.addListener(args.button,"click",tangler.manager.ProfileState.onToggleFollow,args,{preventDefault:true});if(tangler.info.Page.getView()==tangler.info.ViewType.TopicDiscuss&&args.userId!=null&&args.userId==_pState.profileId){if(tangler.util.Element.getEl("followTopicOwner")){tangler.util.Element.getEl("followTopicOwner").update(_685);}}else{if(tangler.info.Page.getView()==tangler.info.ViewType.Profile&&args.userId!=null&&args.userId==_pState.profileId){}}},_toggleCallbackFailure:function(){},_addedFriendCallbackSuccess:function(data,args){if(data==true){Ext.get(args.button).dom.style.display="none";}},_addedFriendCallbackFailure:function(){},onFollowAsAnonymousUser:function(){if(_674==null){_674=new tangler.widget.DialogWrapper("join-dlg",{minHeight:80,width:230,height:80,draggable:false,resizable:false,acceptLabel:"Ok",defaultFocus:"Ok",acceptFunction:function(){_674.hide();}});}if(_674.isVisible()){return;}_674.showDialog();},init:function(_689){this.isFollower=tangler.util.Options.getOptionalArgument("isFollower",_689,false);this.isFollowed=tangler.util.Options.getOptionalArgument("isFollowed",_689,false);this.profileId=tangler.util.Options.getOptionalArgument("profileId",_689,0);this.profileOwnerScreenName=tangler.util.Options.getOptionalArgument("profileName",_689,null);this.viewerId=tangler.util.Options.getOptionalArgument("viewerId",_689,0);this.viewType=tangler.util.Options.getOptionalArgument("viewType",_689,null);if(!tangler.info.Page.isEmbed()&&!tangler.info.Session.getSecurity().isAuthenticated()){var view=tangler.info.Page.getView();var _68b=null;switch(view){case tangler.info.ViewType.Profile:_68b=tangler.util.Element.getEl("followUserButton");if(_68b!=null){_68b.on("click",tangler.manager.ProfileState.onFollowAsAnonymousUser,this);}break;case tangler.info.ViewType.TopicDiscuss:_68b=tangler.util.Element.getEl("followTopicOwner");if(_68b!=null){_68b.on("click",tangler.manager.ProfileState.onFollowAsAnonymousUser,this);}break;}}}});return new _675();}();

var isSafari = false;

if (typeof navigator.vendor != "undefined" && navigator.vendor.indexOf("Apple Computer, Inc.") != -1)
{
	isSafari = true;
}

var widgPlugins = {};

//TW-1781
var widgInstance = null;

/* Setup the onload events to convert textareas */
Ext.EventManager.onDocumentReady(widgInit);

/* Find all the textareas that need to be converted */
function widgInit()
{
	/* Detects if designMode is available, and also if browser is IE or Mozilla (excludes earlier versions of Safari) */
	if (typeof(document.designMode) == "string" && (document.all || document.designMode == "off"))
	{
		var textareas = document.getElementsByTagName("textarea");
		
		for (var i = 0; i < textareas.length; i++)
		{
			var textarea = textareas[i];
			
			if (Ext.get(textarea).hasClass("widgEditor"))
			{
				if (textarea.id == null || textarea.id == "")
				{
					textarea.id = textarea.name;
				}

				textarea.style.visibility = "hidden";
				
				setTimeout("new widgEditor('" + textarea.id + "')", 500 * (i));
			}
		}
	}
	else
	{
		return false;
	}
	
	return true;
};




/* Class for each individual widgEditor */
function widgEditor(replacedTextareaID, options)
{
	var self = this;
	
	if (typeof options == "undefined")
	{
		options = {};
	}
	
	if (typeof options.toolbarButtons == "undefined")
	{
		options.toolbarButtons = widgConfig.toolbarButtons
	}
	
	if (typeof options.toolbarSelects == "undefined")
	{
		options.toolbarSelects = widgConfig.toolbarSelects
	}

	this.id = replacedTextareaID;
	this.toolbarButtons = options.toolbarButtons;
	this.toolbarSelects = options.toolbarSelects;
	this.textarea = document.getElementById(replacedTextareaID);
	
	if (typeof document.all == "undefined" && this.textarea.value.match(/^\s*$/))
	{
		this.textarea.value = "<br />";
	}
	
	this.ready = false;
	this.cancelToolbarCheck = false;
	this.dialogLock = false;
	this.pasteCache = "";
	this.chatMode = false;
	this.submitAction = function()
	{
		var self = this;
		var theForm = this.container.parentNode;
		var oldOnsubmit = null;
		
		/* Find the parent form element */
		while (theForm.parentNode != null && theForm.nodeName.toLowerCase() != "form")
		{
			theForm = theForm.parentNode;
		}
	
		if (theForm.parentNode != null)
		{
			theForm.submit();
		}
		
		return false;
	};
	
	/* Create DOM objects for editor */
	this.container = document.createElement("div");
	this.container.id = this.id + "WidgContainer";
	this.container.className = "widgContainer";
	this.container.style.visibility = "hidden";
	
		this.input = document.createElement("input");
		this.input.type = "hidden";
		this.input.id = this.id;
		this.input.name = this.textarea.name;
		this.input.value = this.textarea.value;
		this.input.editor = this;
		this.container.appendChild(this.input);

		this.toolbar = new widgToolbar(this, this.toolbarButtons, this.toolbarSelects);
		
		this.container.appendChild(this.toolbar.theList);

	this.textarea.parentNode.replaceChild(this.container, this.textarea);

	this.textarea.id += "WidgTextarea";
	this.textarea.name += "WidgTextarea";
	this.isQuote = false;

	this.createIframe();	
	
	/* Attach onsubmit to parent form */
	this.modifyFormSubmit();
	
	//TW-1781
	widgInstance = this;
	
	return this;
};




widgEditor.prototype.createIframe = function()
{
	if (typeof this.iframe != "undefined")
	{
		this.iframe.parentNode.removeChild(this.iframe);
		delete this.iframe;

		var self = this;
		
		/* timeout required for Safari, which takes a while to remove original iframe */
		setTimeout(function()
			{
				self.createIframe();
			},
			1
		);
		
		return false;
	}
	
	this.iframe = document.createElement("iframe");
	this.iframe.id = this.input.id + "WidgIframe";
	this.iframe.className = "widgIframe";
	this.iframe.setAttribute("frameborder", "0");
	this.iframe.setAttribute("frameBorder", "0");
	this.container.appendChild(this.iframe);

	this.iframeWindow = this.iframe.contentWindow;
	this.iframeDocument = this.iframeWindow.document;
	
	/* Fill editor with old textarea content */
	this.writeDocument(this.input.value);
	
	/* Make editor editable */
	this.initEdit();
};




/* Clean pasted content */
widgEditor.prototype.cleanPaste = function()
{
	if (widgConfig.autoClean || confirm("Do you wish to clean the HTML source of the content you just pasted?"))
	{
		markSelectionBoundaries(this.iframeWindow);
		
		this.paragraphise();
		//getting quote div from editor
		var quoteDisableText = this.iframeDocument.getElementById("quoteDisableText");
		
		this.input.value = cleanSource(this.iframeDocument.body.innerHTML, true);
		
		/* Strip out unaccepted attributes */
		this.input.value = this.input.value.replace(/<[^>]*>/g, function(match)
			{
				match = match.replace(/ ([^=]+)="[^"]*"/g, function(match2, attributeName)
					{
						if (attributeName == "alt" || attributeName == "href" || attributeName == "src" || attributeName == "title" || attributeName == "id" || attributeName == "class")
						{
							return match2;
						}

						return "";
					});

				return match;
			}
		);
		
		var tempNode = document.createElement("div");
		tempNode.innerHTML = this.input.value

		acceptableChildren(tempNode);

		this.input.value = tempNode.innerHTML;

		this.refreshDisplay(true);
		
		//for quote message div appending to the editor
		if(!tangler.util.StringUtil.isEmpty(quoteDisableText) )
		{
			this.iframeDocument.getElementsByTagName("body")[0].removeChild(this.iframeDocument.body.firstChild);
			this.iframeDocument.body.insertBefore( quoteDisableText, this.iframeDocument.body.firstChild );
			
		}
	}
	
	return true;
};




/* Check for pasted content */
widgEditor.prototype.detectPaste = function(theEvent)
{
	if (theEvent.ctrlKey && theEvent.getKey() == 86)
	{
		var self = this;
		
		this.pasteCache = this.iframeDocument.getElementsByTagName("body")[0].innerHTML;

		/* Because Mozilla can't access the clipboard directly, must rely on timeout to check pasted differences in main content */
		setTimeout(function(){self.cleanPaste(); return true;}, 100);
	}

	return true;
};




/* Check for shortcut keys */
widgEditor.prototype.detectShortcuts = function(event)
{
	if (event.ctrlKey)
	{
		switch(event.getKey())
		{
			case 13:

				this.handleControlKeys(event);
				
				break;
			
			/* Ctrl-b */
			case 66:
			
				var listItems = this.toolbar.theList.childNodes;
				var button = listItems[0];
				
				while (button != null && !Ext.get(button).hasClass("widgButtonBold"))
				{
					button = button.nextSibling;
				}
				
				var input = button.getElementsByTagName("input")[0];
				
				onclickBold.call(input);

				event.preventDefault();
				this.cancelToolbarCheck = true;
				return false;
			
				break;

			/* Ctrl-i */
			case 73:
			
				var listItems = this.toolbar.theList.childNodes;
				var button = listItems[0];
				
				while (button != null && !Ext.get(button).hasClass("widgButtonItalic"))
				{
					button = button.nextSibling;
				}
				
				var input = button.getElementsByTagName("input")[0];
				
				onclickItalic.call(input);
				
				event.preventDefault();
				this.cancelToolbarCheck = true;
				return false;
			
				break;

			/* Ctrl-u */
			case 85:
			
				var listItems = this.toolbar.theList.childNodes;
				var button = listItems[0];
				
				while (button != null && !Ext.get(button).hasClass("widgButtonUnderline"))
				{
					button = button.nextSibling;
				}
				
				var input = button.getElementsByTagName("input")[0];
				
				onclickUnderline.call(input);
				
				event.preventDefault();
				this.cancelToolbarCheck = true;
				return false;
			
				break;
		}
		
		this.cancelToolbarCheck = true;
	}

	return true;
};





/* Check keystrokes for control keys i.e. carriage return, backspace; and handle appropriately */
widgEditor.prototype.handleControlKeys = function(event)
{
	/* "return" key pressed */
	if (event.getKey() == 13)
	{
		/* Prevent IE from receiving keypresses from dialogs */
		if (this.dialogLock == true)
		{
			event.preventDefault();

			return false;
		}
		
		if ((!widgConfig.shiftSubmit && event.shiftKey == false) || (!widgConfig.shiftSubmit && event.ctrlKey == true) || (widgConfig.shiftSubmit && event.shiftKey == true) || (this.chatMode && event.ctrlKey != true && event.shiftKey != true))
		{
			this.submit();

			event.preventDefault();
		}
		else if (markSelectionBoundaries(this.iframeWindow))
		{
			this.paragraphise(false);

			var selectionStart = this.iframeDocument.getElementById("selectionStart");
			var selectionEnd = this.iframeDocument.getElementById("selectionEnd");

			deleteSelection(this.iframeWindow);

			/* Insert a <br> */
			if (event.shiftKey == true || event.ctrlKey == true)
			{
				var newBr = this.iframeDocument.createElement("br");

				selectionStart.parentNode.insertBefore(newBr, selectionStart);
			}
			/* Create new block element */
			else
			{
				var blockParent = selectionStart.parentNode;

				while (!blockParent.nodeName.isBlockName())
				{
					blockParent = blockParent.parentNode;
				}
				
				/* If the cursor has been newly inserted right at the start of the document i.e. just inside the body tag, move the cursor into the first block element */
				if (blockParent.nodeName.toLowerCase() == "body")
				{
					var firstBlock = blockParent.firstChild;
					
					while (firstBlock != null)
					{
						if (firstBlock.nodeType == 1 && firstBlock.nodeName.isBlockName())
						{
							blockParent = firstBlock;
							blockParent.insertBefore(selectionEnd, blockParent.firstChild);
							blockParent.insertBefore(selectionStart, blockParent.firstChild);
							
							break;
						}
						
						firstBlock = getNextElement(firstBlock);
					}

					if (firstBlock == null)
					{
						blockParent = this.iframeDocument.createElement("p");
						
						while (this.iframeDocument.body.firstChild != null)
						{
							blockParent.appendChild(this.iframeDocument.body.firstChild);
						}
						
						blockParent.insertBefore(selectionEnd, blockParent.firstChild);
						blockParent.insertBefore(selectionStart, blockParent.firstChild);
						
						this.iframeDocument.body.appendChild(blockParent);
					}
				}

				/* Last list item of a list is empty, create new paragraph */
				if (blockParent.nodeName.toLowerCase() == "li" && blockParent.innerHTML.match(/^(\s|&nbsp;|\xA0|<var[^>]*>|<\/var>|<br[^>]*>)*$/i) != null)
				{
					var newP = this.iframeDocument.createElement("p");
					newP.innerHTML = blockParent.innerHTML;
					blockParent.parentNode.parentNode.insertBefore(newP, blockParent.parentNode.nextSibling);
					
					blockParent.parentNode.removeChild(blockParent);
				}
				else
				{
					var blockCopy = blockParent.cloneNode(true);
					var blockCopySelectionStart = getNextElement(blockCopy);
	
					/* Find the cloned selectionStart */
					while (blockCopySelectionStart.id != "selectionStart")
					{
						blockCopySelectionStart = getNextElement(blockCopySelectionStart);
					}
	
					var nextElement = getNextElement(blockCopy);
	
					/* Remove elements from clone prior to selection point */
					while (nextElement.id != "selectionStart")
					{
						if (!isDescendantNode(blockCopySelectionStart, nextElement))
						{
							var currElement = nextElement;
							nextElement = getNextHigherElement(nextElement);
							currElement.parentNode.removeChild(currElement);
						}
						else
						{
							nextElement = getNextElement(nextElement);
						}
					}

					if (isEmptyElement(blockCopy, true))
					{
						blockCopy.innerHTML += "&nbsp;";
					}
					
					var anchors = blockCopy.getElementsByTagName("a")
					
					for (var i = anchors.length - 1; i >= 0; i--)
					{
						replaceNodeWithChildren(anchors[i]);
					}
	
					if (blockParent.nodeName.toLowerCase() == "li")
					{
						blockParent.parentNode.insertBefore(blockCopy, blockParent.nextSibling);
					}
					else
					{
						var newP = this.iframeDocument.createElement("p");
	
						newP.appendChild(blockCopy);
						replaceNodeWithChildren(blockCopy);
						blockParent.parentNode.insertBefore(newP, blockParent.nextSibling);
						
						newP.innerHTML += "&nbsp;"
					}
	
					var nextElement = selectionStart;
	
					/* Remove elements from original block after selection point */
					while (isDescendantNode(nextElement, blockParent))
					{
						var currElement = nextElement;
						nextElement = getNextHigherElement(nextElement);
						currElement.parentNode.removeChild(currElement);
					}

					if (isEmptyElement(blockParent))
					{
						blockParent.innerHTML += "&nbsp;";
					}
				}
			}

			/* Scroll so new element is in view */
			this.iframeWindow.scrollTo(0, getPosition(newBr || newP || blockCopy)[1] - this.iframe.clientHeight + 30);
			
			selectSelectionBoundaries(this.iframeWindow);
			deleteSelectionBoundaries(this.iframeWindow);

			event.preventDefault();
		}
		else
		{
			return false;
		}
	}
	
	return true;
};




/* Turn on document editing */
widgEditor.prototype.initEdit = function()
{
	var self = this;
	
	try
	{
		this.iframeDocument.designMode = "on";
	}
	catch (e)
	{
		/* setTimeout needed to counteract Mozilla bug whereby you can't immediately change designMode on newly created iframes */
		setTimeout(function(){self.initEdit()}, 250);
			
		return false;
	}

	this.container.style.visibility = "visible";
	this.textarea.style.visibility = "visible";
	
	/* Capture events on the iframe document */
	Ext.EventManager.addListener(this.iframeDocument, "mouseup", function()
		{
			widgToolbarCheckState(self);
		}
	);
	
	Ext.EventManager.addListener(this.iframeDocument, "keyup", function(event)
		{
			/* Delay checking of cursor context as keys are pressed -- reduce computation */
			if (typeof window.keyupTimer != "undefined")
			{
				clearTimeout(window.keyupTimer);
			}

			/* Don't allow ctrl-keyups to go through to the check */
			if (event.getKey() != 17)
			{
				window.keyupTimer = setTimeout(function()
					{
						widgToolbarCheckState(self);
					}, 250);
			}
		}
	);
	
	Ext.EventManager.addListener(this.iframeDocument, "keyup", function(event)
		{
			self.detectPaste(event);
		}
	);

	Ext.EventManager.addListener(this.iframeDocument, "keydown", function(event)
		{			
			self.detectShortcuts(event);
		}
	);

	Ext.EventManager.addListener(this.iframeDocument, "keypress", function(event)
		{
			self.handleControlKeys(event);
		}
	);
	
	Ext.EventManager.addListener(this.iframeWindow, "blur", function(event)
		{
			/* To determine when focus is on the editor window and selection boundaries should be deleted upon re-focus */
			if (document.all)
			{
				self.iframeWindow.editorFocus = false;
			}
		}
	);
	
	Ext.EventManager.addListener(this.iframeWindow, "focus", function(event)
		{
			if (document.all)
			{
				self.iframeWindow.editorFocus = true;
			}
		}
	);
	
	this.ready = true;

	return true;	
};




/* Add submit listener to parent form */
widgEditor.prototype.modifyFormSubmit = function()
{
	var self = this;
	var theForm = this.container.parentNode;
	var oldOnsubmit = null;
	
	/* Find the parent form element */
	while (theForm.parentNode != null && theForm.nodeName.toLowerCase() != "form")
	{
		theForm = theForm.parentNode;
	}

	if (theForm.parentNode != null)
	{
		/* Add onsubmit without overwriting existing function calls */
		oldOnsubmit = theForm.onsubmit;
	
		if (typeof theForm.onsubmit != "function")
		{
			theForm.onsubmit = function()
			{
				return self.submit();
			}
		}
		else
		{
			theForm.onsubmit = function()
			{
				self.submit();
	
				return oldOnsubmit();			
			}
		}
	}
	else
	{
		return false;
	}

	return true;
};




/* Add a listener to pre-process submit data */
widgEditor.prototype.addSubmitListener = function(handler)
{
	if (typeof this.submitListeners == "undefined")
	{
		this.submitListeners = [];
	}
	
	this.submitListeners[this.submitListeners.length] = handler;
};




/* Run the listeners to pre-process submit data */
widgEditor.prototype.runSubmitListeners = function()
{
	if (typeof this.submitListeners != "undefined")
	{
		for (var handler in this.submitListeners)
		{
			this.submitListeners[handler]();
		}
	}
}




/* "Submit" the widgEditor; perform some action */
widgEditor.prototype.submit = function()
{
	this.updateWidgInput();
	this.runSubmitListeners();
	this.submitAction();
};




/* Set a function to be executed on a submit() call to the editor */
widgEditor.prototype.setSubmit = function(submitAction)
{
	this.submitAction = submitAction;
};




/* Get the HTML from the editor */
widgEditor.prototype.getHTML = function()
{
	return this.iframeDocument.body.innerHTML;
};




/* Get the value that would be submitted from the editor */
widgEditor.prototype.getSubmitValue = function()
{
	this.updateWidgInput();
	
	var oldInputValue = this.input.value;
	
	this.runSubmitListeners();
	
	var newInputValue = this.input.value;
	this.input.value = oldInputValue;
	
	return newInputValue;
};





/* Format the HTML with paragraphs. Any parentless text is enclosed in a paragraph, double breaks are paragraph markers */
widgEditor.prototype.paragraphise = function(removeEmptyElements)
{
	if (typeof removeEmptyElements == "undefined")
	{
		removeEmptyElements = true;
	}
	
	var theBody = this.iframeWindow.document.getElementsByTagName("body")[0];

	var nextElement = getNextElement(theBody);
	var newParagraph = null;
	
	while (nextElement != null)
	{
		if (!nextElement.nodeName.isBlockName())
		{
			if (newParagraph == null && nextElement.id != "selectionStart" && nextElement.id != "selectionEnd")
			{
				newParagraph = this.iframeWindow.document.createElement("p");
				nextElement.parentNode.insertBefore(newParagraph, nextElement);
			}
			
			if (newParagraph != null)
			{
				newParagraph.appendChild(nextElement);
			}
		}
		else
		{
			newParagraph = null;
		}
			
		nextElement = getNextHigherElement(nextElement);
	}

	if (removeEmptyElements)
	{
//		removeEmpties(theBody);
	}

	return true;
};




/* Update display from hidden input */
widgEditor.prototype.refreshDisplay = function(selectSelection)
{
	/* In case document isn't available yet */
	try
	{
		this.iframeDocument.getElementsByTagName("body")[0].innerHTML = this.input.value;
		
		if (selectSelection)
		{
			selectSelectionBoundaries(this.iframeWindow);
			deleteSelectionBoundaries(this.iframeWindow);
		}
	}
	catch(error)
	{
		var self = this;
		
		setTimeout(function()
			{
				self.refreshDisplay();
			},
			250
		);
	}

	return true;
};




/* Select all content in the editor */
widgEditor.prototype.selectAll = function()
{
	var iframeBody = this.iframeDocument.getElementsByTagName("body")[0];

	var selectionStart = this.iframeDocument.createElement("var");
	selectionStart.id = "selectionStart";
	iframeBody.insertBefore(selectionStart, iframeBody.firstChild);
	
	var selectionEnd = this.iframeDocument.createElement("var");
	selectionEnd.id = "selectionEnd";
	iframeBody.appendChild(selectionEnd);
	
	selectSelectionBoundaries(this.iframeWindow);
	deleteSelectionBoundaries(this.iframeWindow);
	
//	this.focus();
};




/* Get the text of the selected elements */
widgEditor.prototype.getSelectedText = function()
{
	var selectionStart = this.iframeDocument.getElementById("selectionStart");
	
	var text = "";
	
	if (selectionStart != null)
	{
		for (var next = selectionStart; next.id != "selectionEnd"; next = getNextElement(next))
		{
			if (next.nodeType == 3)
			{
				text += next.nodeValue;
			}
		}
	}
	
	text.replace(/\s+/g, " ");
	
	return text;
};




/* Get the HTML of the selected elements */
widgEditor.prototype.getSelectedHTML = function()
{
	var selectionStart = this.iframeDocument.getElementById("selectionStart");
	
	var html = "";
	var cloneContainer = this.iframeDocument.createElement("div");
	
	if (selectionStart != null)
	{
		var next = getNextElement(selectionStart);
		
		for (var next = getNextElement(selectionStart); next.id != "selectionEnd"; next = getNextElement(next))
		{
			cloneContainer.appendChild(next.cloneNode(true));
		}
		
		html = cloneContainer.innerHTML;
	}

	html = cleanSource(html);

	return html;
};




/* Find parent of specified type common to start and end of selection */
widgEditor.prototype.getSelectionParent = function(type)
{
	var selectionStart = this.iframeDocument.getElementById("selectionStart");
	var selectionEnd = this.iframeDocument.getElementById("selectionEnd");
	
	if (selectionStart != null)
	{
		var parent = getCommonParent(selectionStart, selectionEnd);
		
		while (parent != null && typeof parent.nodeName != "undefined")
		{
			if (parent.nodeName.toLowerCase() == type)
			{
				return parent;
			}
			
			parent = parent.parentNode;
		}
	}
	
	return null;
};




/* Select specified element */
widgEditor.prototype.selectElement = function(element)
{
	deleteSelectionBoundaries(this.iframeWindow);
	
	var selectionStart = this.iframeDocument.createElement("var");
	selectionStart.id = "selectionStart";
	element.parentNode.insertBefore(selectionStart, element);
	
	var selectionEnd = this.iframeDocument.createElement("var");
	selectionEnd.id = "selectionEnd";
	Ext.get(selectionEnd).insertAfter(element);	
	
	selectSelectionBoundaries(this.iframeWindow);
};




/* Focus editor */
widgEditor.prototype.focus = function(moveToStart)
{
	if (typeof moveToStart != "undefined" && moveToStart == true)
	{
		if (typeof document.selection != "undefined")
		{
			/* IE doesn't access the body element for a while, so the call has to be repeated in a try/catch */
			try
			{
				var iframeBody = this.iframeDocument.getElementsByTagName("body")[0];
				
				var firstElement = null;
				
				for (var i = 0; i < iframeBody.childNodes.length; i++)
				{
					if (iframeBody.childNodes[i].nodeType == 1)
					{
						firstElement = iframeBody.childNodes[i];
						
						break;
					}
				}
				
				if (firstElement == null)
				{
					firstElement = iframeBody;
				}
			
				var selectionEnd = this.iframeDocument.createElement("var");
				selectionEnd.id = "selectionEnd";
				firstElement.insertBefore(selectionEnd, firstElement.firstChild);
				
				var selectionStart = this.iframeDocument.createElement("var");
				selectionStart.id = "selectionStart";
				firstElement.insertBefore(selectionStart, firstElement.firstChild);
				
				selectSelectionBoundaries(this.iframeWindow);
				deleteSelectionBoundaries(this.iframeWindow);
			}
			catch(error)
			{
				this.blur();
				
				var self = this;
				
				setTimeout(function()
					{
						self.focus(true);
					},
					500
				);
				
				return;
			}
		}
	}
	
	this.iframeWindow.focus();
	selectSelectionBoundaries(this.iframeWindow);
	deleteSelectionBoundaries(this.iframeWindow);	
};




/* Blur editor, doesn't work for Safari */
widgEditor.prototype.blur = function()
{
	window.focus();
};

/* Hide the entire editor from view */
widgEditor.prototype.hide = function()
{
	markSelectionBoundaries(this.iframeWindow);
	this.blur();
	this.updateWidgInput();
	Ext.get(this.container).addClass("widgContainerHidden");
}




/* Show the entire editor (after hiding) */
widgEditor.prototype.show = function()
{
	Ext.get(this.container).removeClass("widgContainerHidden");
	
	if (isSafari)
	{
		this.createIframe();
	}
	
	var self = this;
	
	setTimeout(function()
		{
			try
			{
				selectSelectionBoundaries(self.iframeWindow);
				deleteSelectionBoundaries(self.iframeWindow);
				self.focus(true);
			}
			catch(error)
			{
			}
		},
		1
	);
};




/* Toggle chat mode */
widgEditor.prototype.toggleChatMode = function(toggle)
{
	if (typeof toggle != "undefined")
	{
		this.chatMode = toggle;
	}
	else if (this.chatMode)
	{
		this.chatMode = false;
	}
	else
	{
		this.chatMode = true;
	}
	
	if (this.chatMode)
	{
		Ext.get(this.container).addClass("widgContainerChatMode");
	}
	else
	{
		Ext.get(this.container).removeClass("widgContainerChatMode");
	}
};




/* Update hidden input to reflect editor contents */
widgEditor.prototype.updateWidgInput = function()
{
	//removing the quote div from editor before saving
	var quoteDisableText =  this.iframeDocument.getElementById("quoteDisableText");
	if( !tangler.util.StringUtil.isEmpty(quoteDisableText) )
	{
		try
		{
			this.iframeDocument.getElementsByTagName("body")[0].removeChild(quoteDisableText);
		}
		catch (e) 
		{
			this.iframeDocument.getElementsByTagName("p")[0].removeChild(quoteDisableText);
		}
		this.isQuote = true;
		
	}else
	{
		this.isQuote = false;
	}
	this.paragraphise();
	this.input.value = this.iframeDocument.getElementsByTagName("body")[0].innerHTML;
	
	var cleanedSource = cleanSource(this.input.value);
	
	this.iframeDocument.getElementsByTagName("body")[0].innerHTML = cleanedSource;	
	this.input.value = cleanedSource;
	
	return true;
};

widgEditor.prototype.isQuote = function()
{
	return this.isQuote;
};


/* Write initial content to editor */
widgEditor.prototype.writeDocument = function(documentContent)
{
	/* HTML template into which the HTML Editor content is inserted */
	var documentTemplate = '\
		<html>\
			<head>\
				INSERT:STYLESHEET:END\
			</head>\
			<body id="iframeBody">\
				INSERT:CONTENT:END\
			</body>\
		</html>\
	';
	
	/* Insert dynamic variables/content into document */
	/* IE needs stylesheet to be written inline */
	if (typeof document.all != "undefined")
	{
		documentTemplate = documentTemplate.replace(/INSERT:STYLESHEET:END/, '<link rel="stylesheet" type="text/css" href="' + widgConfig.widgStylesheet + '"></link>');
	}
	/* Firefox can't have stylesheet written inline */
	else
	{
		documentTemplate = documentTemplate.replace(/INSERT:STYLESHEET:END/, "");
	}
	
	documentTemplate = documentTemplate.replace(/INSERT:CONTENT:END/, documentContent);
	
	this.iframeWindow.document.open();
	this.iframeWindow.document.write(documentTemplate);
	this.iframeWindow.document.close();

	/* In Firefox stylesheet needs to be loaded separate to other HTML, because if it's loaded inline it causes Firefox to have problems with an empty document */
	if (typeof document.all == "undefined")
	{
		var stylesheet = this.iframeWindow.document.createElement("link");
		stylesheet.setAttribute("rel", "stylesheet");
		stylesheet.setAttribute("type", "text/css");
		stylesheet.setAttribute("href", widgConfig.widgStylesheet);
		this.iframeWindow.document.getElementsByTagName("head")[0].appendChild(stylesheet);
	}
	
	return true;
};




/* Insert the specified inline HTML */
widgEditor.prototype.insertHTML = function(htmlString)
{
	markSelectionBoundaries(this.iframeWindow);
	deleteSelection(this.iframeWindow);

	var selectionStart = this.iframeDocument.getElementById("selectionStart");

	if (selectionStart != null)
	{
		var newSpan = this.iframeDocument.createElement("span");
		newSpan.innerHTML = htmlString;
		selectionStart.parentNode.insertBefore(newSpan, selectionStart);
	
		/* Remove temporary span, but keep its contents */
		replaceNodeWithChildren(newSpan);
	}
	
	this.focus();
	markSelectionBoundaries(this.iframeWindow);
	selectSelectionBoundaries(this.iframeWindow);
	deleteSelectionBoundaries(this.iframeWindow);

	return true;
};




/* Removes current content from the editor */
widgEditor.prototype.reset = function(content)
{
	if (typeof content == "undefined" || content.match(/^\s*$/))
	{
		if (typeof document.all == "undefined")
		{
			this.input.value = "<br />";
		}
		else
		{
			this.input.value = "";
		}
	}
	else
	{
		this.input.value = content;
	}
	
	var oldToolbarList = this.toolbar.theList;
	
	this.toolbar = new widgToolbar(this, this.toolbarButtons, this.toolbarSelects);
	this.container.replaceChild(this.toolbar.theList, oldToolbarList);

	this.refreshDisplay();
};




/* Checks whether the editor is ready to receive commands */
widgEditor.prototype.isReady = function()
{
	return this.ready;
};




/* Toolbar items */
function widgToolbar(editor, toolbarButtons, toolbarSelects)
{
	var self = this;
	
	this.editor = editor;
	
	/* Create toolbar ul element */
	this.theList = document.createElement("ul");
	this.theList.id = this.editor.input.id + "WidgToolbar";
	this.theList.className = "widgToolbar";
	this.theList.widgToolbarObject = this;

	/* Create toolbar items */
	for (var i = 0; i < toolbarButtons.length; i++)
	{
		this.addButton(toolbarButtons[i]);
	}
	
	return true;
};





/* Add button to toolbar */
widgToolbar.prototype.addButton = function(button)
{
	if (typeof button == "string")
	{
		this.addPlugin(button);
	}
	else
	{
		var menuItem = document.createElement("li");
		menuItem.id = this.theList.id + button.className;
		menuItem.className = "widgEditButton " + button.className;

			var input = document.createElement("input");
			input.type = "image";
			input.alt = button.title;
			input.title = button.title;
			input.src = button.image;
			input.genericOnclickHandler = onclickToolbarButton;
			input.onclickHandler = button.action;
			input.onclick = function()
			{
				if (this.genericOnclickHandler())
				{
					return this.onclickHandler();
				}
				else
				{
					return false;
				}
			};

			input.onmousedown = onmousedownButton;
			input.onmouseover = onmouseoverButton;
			input.onmouseout = onmouseoutButton;
			menuItem.appendChild(input);

		this.theList.appendChild(menuItem);
		
		return menuItem;
	}

	return true;
};




widgToolbar.prototype.addPlugin = function(plugin)
{
	var self = this;
	var pluginCapitalised = plugin.substring(0, 1).toUpperCase() + plugin.substring(1, plugin.length);
	var className = "widgButton" + pluginCapitalised;
	var image = widgConfig.pluginsPath + "/" + plugin + "/button.gif";
	var standinFunction = function()
	{
		alert("This plugin has not yet loaded");
		
		return false;
	};
			
	var menuItem = this.addButton(
		{
			className: className,
			title: plugin,
			action: standinFunction,
			image: image
		}
	);
	var input = menuItem.getElementsByTagName("input")[0];
	
	// Checks whether all components of the plugin have been loaded, then executes the plugin's JavaScript
	var checkReady = function()
	{
		var editor = self.editor;
		var pluginData = widgPlugins[plugin];
		
		if (typeof pluginData != "undefined" && typeof pluginData.description != "undefined" && typeof pluginData.html != "undefined" && typeof pluginData.js != "undefined")
		{
			if (editor.ready)
			{
				input.alt = pluginData.description.title;
				input.title = pluginData.description.title;
	
				var newDivId = editor.id + "widgPlugin" + pluginCapitalised;
				var existingDiv = document.getElementById(newDivId)
				
				if (existingDiv != null)
				{
					existingDiv.parentNode.removeChild(existingDiv);
				}

				var newDiv = document.createElement("div");
				newDiv.id = newDivId;
				newDiv.innerHTML = pluginData.html.replace(/(id="[^"]+)"/g, "$1" + editor.id + '"');
				document.getElementsByTagName("body")[0].appendChild(newDiv);
	
				// Closure for access to editor from plugin
				eval(widgPlugins[plugin].js);
				
				input.onclickHandler = function()
				{
					markSelectionBoundaries(editor.iframeWindow);
					selectSelectionBoundaries(editor.iframeWindow);
	
					return eval(pluginData.description.action)(this);
				};
			}
			else
			{
				setTimeout(function()
					{
						checkReady();
					},
					100
				);
			}
		}
	};

	if (typeof widgPlugins[plugin] == "undefined")
	{
		widgPlugins[plugin] = {};
		widgPlugins[plugin].ready = false;
		
		var pluginData = widgPlugins[plugin];
		
		var descriptionConnection = new Ext.data.Connection();
		descriptionConnection.request(
			{
				url: widgConfig.pluginsPath + plugin + "/description.js",
				callback: function(options, success, response)
					{
						// Creates variable "description"
						eval(response.responseText);
						
						pluginData.description = description;
						
						checkReady();
					}
			}
		);
		
		var templateConnection = new Ext.data.Connection();
		templateConnection.request(
			{
				url: widgConfig.pluginsPath + plugin + "/template.htm",
				callback: function(options, success, response)
					{
						pluginData.html = response.responseText;
						
						checkReady();
					}
			}
		);
		
		var behaviourConnection = new Ext.data.Connection();
		behaviourConnection.request(
			{
				url: widgConfig.pluginsPath + plugin + "/behaviour.js",
				callback: function(options, success, response)
					{
						pluginData.js = response.responseText;
						
						checkReady();
					}
			}
		);
	}
	
	checkReady();
};




/* Change the status of the selected toolbar item */
widgToolbar.prototype.setState = function(theItem, theStatus, targetElement)
{
	var theButton = document.getElementById(this.theList.id + theItem);

	if (theButton != null)
	{
		if (theStatus == "on")
		{
			Ext.get(theButton).addClass("on");

			if (typeof targetElement != "undefined")
			{
				theButton.targetElement = targetElement;
			}
		}
		else
		{
			Ext.get(theButton).removeClass("on");
			
			theButton.targetElement = null;
		}
	}
			
	return true;	
};




/* Check the nesting of the current cursor position/selection */
function widgToolbarCheckState(editor, resubmit)
{
	if (editor.cancelToolbarCheck == true)
	{
		editor.cancelToolbarCheck = false;
		
		return true;
	}
			
	if (typeof resubmit == "undefined")
	{
		setTimeout(function()
			{
				widgToolbarCheckState(editor, true);
			}, 500);
	}
	
	try
	{
		var theSelection = new selectionObj(editor.iframeWindow);
	}
	catch(error)
	{
		return false;
	}

	if (theSelection.selection == null || theSelection.textRange == null)
	{
		return false;
	}

	var theParentNode = null;
	
	/* Turn off all the buttons */
	var menuListItems = editor.toolbar.theList.childNodes;
	for (var i = 0; i < menuListItems.length; i++)
	{
		Ext.get(menuListItems[i]).removeClass("on");
	}
	
	/* IE image selected */
	if (document.selection)
	{
		if (theSelection.selection.type == "Control" && theSelection.textRange.length == 1 && theSelection.textRange.item(0).nodeName.toLowerCase() == "img")
		{
			if (Ext.get(theSelection.textRange.item(0)).hasClass("widgImageLeft"))
			{
				editor.toolbar.setState("widgButtonImageLeft", "on");
			}
			else if (Ext.get(theSelection.textRange.item(0)).hasClass("widgImageRight"))
			{
				editor.toolbar.setState("widgButtonImageRight", "on");
			}
		}
	}
	/* Mozilla image selected */
	else
	{
		var clonedContents = theSelection.textRange.cloneContents();
		
		if (clonedContents != null && clonedContents.childNodes.length == 1 && clonedContents.firstChild.nodeName.toLowerCase() == "img")
		{
			if (Ext.get(clonedContents.firstChild).hasClass("widgImageLeft"))
			{
				editor.toolbar.setState("widgButtonImageLeft", "on");
			}
			else if (Ext.get(clonedContents.firstChild).hasClass("widgImageRight"))
			{
				editor.toolbar.setState("widgButtonImageRight", "on");
			}
		}
	}
	
	/* IE selections */
	if (typeof theSelection.textRange.parentElement != "undefined")
	{
		theParentNode = theSelection.textRange.parentElement();
	}
	/* Mozilla/Safari selections */
	else if (typeof theSelection.textRange.commonAncestorContainer != "undefined")
	{
		theParentNode = theSelection.textRange.commonAncestorContainer;
		
		if (theParentNode.nodeName.toLowerCase() == "#document")
		{
			return false;
		}
	}
	else
	{
		return false;
	}
	
	var styleSet = false;

	while (!theParentNode.nodeName.isBlockName())
	{
		switch (theParentNode.nodeName.toLowerCase())
		{
			case "a":
				editor.toolbar.setState("widgButtonHyperlink", "on", theParentNode);
				
				break;
				
			case "del":
				editor.toolbar.setState("widgButtonStrikethrough", "on", theParentNode);
				
				break;
				
			case "em":
				editor.toolbar.setState("widgButtonItalic", "on", theParentNode);
				
				break;
				
			case "strong":
				editor.toolbar.setState("widgButtonBold", "on", theParentNode);
				
				break;
				
			case "u":
				editor.toolbar.setState("widgButtonUnderline", "on", theParentNode);
				
				break;
		}
	
		if (!styleSet)
		{
			var theSelect = document.getElementById(editor.toolbar.theList.id + "widgSelectStyle");

			if (theSelect != null)
			{
				for (var i = 0; i < theSelect.options.length; i++)
				{
					if (typeof theParentNode.className != "undefined" && Ext.get(theParentNode).hasClass(theSelect.options[i].value))
					{
						styleSet = true;
						editor.toolbar.setState("widgSelectStyle", theSelect.options[i].value);
					}
				}
			}
		}

		theParentNode = theParentNode.parentNode;
	}
	
	if (!styleSet)
	{
		var theSelect = document.getElementById(editor.toolbar.theList.id + "widgSelectStyle");

		if (theSelect != null)
		{
			for (var i = 0; i < theSelect.options.length; i++)
			{
				if (Ext.get(theParentNode).hasClass(theSelect.options[i].value))
				{
					styleSet = true;
					editor.toolbar.setState("widgSelectStyle", theSelect.options[i].value);
				}
			}
		}
	}
	
	if (!styleSet)
	{
					editor.toolbar.setState("widgSelectStyle", "");
	}

	switch (theParentNode.nodeName.toLowerCase())
	{
		case "blockquote":
			editor.toolbar.setState("widgButtonBlockquote", "on");

			break;

		case "li":
			if (theParentNode.parentNode.nodeName.toLowerCase() == "ol")
			{
				editor.toolbar.setState("widgButtonOrdered", "on");
			}
			else
			{
				editor.toolbar.setState("widgButtonUnordered", "on");
			}

			editor.toolbar.setState("widgSelectBlock", "");
			
			break;

		default:
			editor.toolbar.setState("widgSelectBlock", theParentNode.nodeName.toLowerCase());

			break;
	}
	
	/* Possible to have a block element inside a blockquote */	
	if (theParentNode.parentNode != null && theParentNode.parentNode.nodeName.toLowerCase() == "blockquote")
	{
		editor.toolbar.setState("widgButtonBlockquote", "on");
	}
		
	return true;			
};




/******************************************************************************/
/* EVENT HANDLERS */
/******************************************************************************/

function onclickBold()
{
	if (Ext.get(this.parentNode).hasClass("on"))
	{
		removeInlineElement("strong", this.parentNode.parentNode.widgToolbarObject.editor);

		this.parentNode.parentNode.widgToolbarObject.setState("widgButtonBold", "off");
	}
	else
	{
		if (insertInlineElement("strong", this.parentNode.parentNode.widgToolbarObject.editor))
		{
			this.parentNode.parentNode.widgToolbarObject.setState("widgButtonBold", "on");
		}
	}
	var quoteDisableText = this.parentNode.parentNode.widgToolbarObject.editor.iframeDocument.getElementById("quoteDisableText");
	if( quoteDisableText != null )
	{
		try
		{
			var strongTag = this.parentNode.parentNode.widgToolbarObject.editor.iframeDocument.getElementsByTagName("strong")[0];
			var pTag = this.parentNode.parentNode.widgToolbarObject.editor.iframeDocument.getElementsByTagName("p")[0];
			this.parentNode.parentNode.widgToolbarObject.editor.iframeDocument.getElementsByTagName("p")[0].removeChild(quoteDisableText);
			this.parentNode.parentNode.widgToolbarObject.editor.iframeDocument.getElementsByTagName("body")[0].insertBefore(quoteDisableText,pTag);
		}
		catch (e) {}
		
	}
	return false;
};




function onclickItalic()
{
	if (Ext.get(this.parentNode).hasClass("on"))
	{
		removeInlineElement("em", this.parentNode.parentNode.widgToolbarObject.editor);
		
		this.parentNode.parentNode.widgToolbarObject.setState("widgButtonItalic", "off");
	}
	else
	{
		if (insertInlineElement("em", this.parentNode.parentNode.widgToolbarObject.editor))
		{
			this.parentNode.parentNode.widgToolbarObject.setState("widgButtonItalic", "on");
		}
	}
	
	return false;
};




function onclickOrderedList()
{
	var toolbar = this.parentNode.parentNode.widgToolbarObject;
	var editor = toolbar.editor;
	
	var quoteDisableText = editor.iframeDocument.getElementById("quoteDisableText");
	
	editor.iframeDocument.execCommand("insertorderedlist", false, null);
	
	if( quoteDisableText != null )
	{
		try
		{
			var ulTag = editor.iframeDocument.getElementsByTagName("li")[0];
			ulTag.removeChild(quoteDisableText);
			editor.iframeDocument.getElementsByTagName("body")[0].insertBefore(quoteDisableText,editor.iframeDocument.getElementsByTagName("ol")[0]);
		}
		catch (e) {}
		
	}

	editor.toolbar.setState("widgButtonUnordered", "off");

	if (editor.iframeDocument.queryCommandState("insertorderedlist", false, null))
	{
		editor.toolbar.setState("widgButtonOrdered", "on");
		editor.toolbar.setState("widgSelectBlock", "");
	}
	else
	{
		editor.toolbar.setState("widgButtonOrdered", "off");
	}
	
	return false;
};




function onclickStrikethrough()
{
	if (Ext.get(this.parentNode).hasClass("on"))
	{
		removeInlineElement("del", this.parentNode.parentNode.widgToolbarObject.editor);
		
		this.parentNode.parentNode.widgToolbarObject.setState("widgButtonStrikethrough", "off");
	}
	else
	{
		if (insertInlineElement("del", this.parentNode.parentNode.widgToolbarObject.editor))
		{
			this.parentNode.parentNode.widgToolbarObject.setState("widgButtonStrikethrough", "on");
		}
	}
	
	return false;
};




function onclickToolbarButton()
{
	if (!Ext.get(this.parentNode.parentNode).hasClass("widgSource") || Ext.get(this).hasClass("widgButtonHTML"))
	{
		try
		{
			this.parentNode.parentNode.widgToolbarObject.editor.iframeWindow.focus();
		}
		catch (error)
		{
		}
	
		return true;
	}
	
	return false;
};




function onclickUnderline()
{
	if (Ext.get(this.parentNode).hasClass("on"))
	{
		removeInlineElement("u", this.parentNode.parentNode.widgToolbarObject.editor);

		this.parentNode.parentNode.widgToolbarObject.setState("widgButtonUnderline", "off");
	}
	else
	{
		if (insertInlineElement("u", this.parentNode.parentNode.widgToolbarObject.editor))
		{
			this.parentNode.parentNode.widgToolbarObject.setState("widgButtonUnderline", "on");
		}
	}
	
	return false;
};




function onclickUnorderedList(event)
{
	var toolbar = this.parentNode.parentNode.widgToolbarObject;
	var editor = toolbar.editor;
	
	var quoteDisableText = editor.iframeDocument.getElementById("quoteDisableText");
	
	editor.iframeDocument.execCommand("insertunorderedlist", false, null);
	if( quoteDisableText != null )
	{
		try
		{
			var ulTag = editor.iframeDocument.getElementsByTagName("li")[0];
			ulTag.removeChild(quoteDisableText);
			editor.iframeDocument.getElementsByTagName("body")[0].insertBefore(quoteDisableText,editor.iframeDocument.getElementsByTagName("ul")[0]);
		}
		catch (e) {}
		
	}

	editor.toolbar.setState("widgButtonOrdered", "off");

	if (editor.iframeDocument.queryCommandState("insertunorderedlist", false, null))
	{
		editor.toolbar.setState("widgButtonUnordered", "on");
		editor.toolbar.setState("widgSelectBlock", "");
	}
	else
	{
		editor.toolbar.setState("widgButtonUnordered", "off");
	}
	
	return false;
};




function onmousedownButton()
{
	return false;
};




function onmouseoverButton()
{
	window.status = "";
	Ext.get(this).addClass("hover");
	
	return true;
};




function onmouseoutButton()
{
	Ext.get(this).removeClass("hover");

	return true;
};




/******************************************************************************/
/* DOM FUNCTIONS */
/******************************************************************************/

/* Remove invalid elements, but keep their contents */
function acceptableChildren(theNode)
{
	var theChildren = theNode.childNodes;
	
	for (var i = 0; i < theChildren.length; i++)
	{
		if (!theChildren[i].nodeName.isAcceptedElementName())
		{
			if (!theChildren[i].nodeName.isInlineName())
			{
				if (theNode.nodeName.toLowerCase() == "p")
				{
					acceptableChildren(replaceNodeWithChildren(theNode).parentNode);
					
					return true;
				}
				
				changeNodeType(theChildren[i], "p");
			}
			else
			{
				replaceNodeWithChildren(theChildren[i]);
			}
				
			i = -1;
		}
	}
	
	for (var i = 0; i < theChildren.length; i++)
	{
		acceptableChildren(theChildren[i]);
	}
	
	return true;
};




/* Change the type of a node, e.g. h3 to p */
function changeNodeType(theNode, nodeType)
{
	var documentPointer = theNode.ownerDocument;
	
	if (typeof documentPointer != "undefined")
	{
		var theNewNode = documentPointer.createElement(nodeType);
		var theParent = theNode.parentNode;
		
		if (theParent != null)
		{
			for (var i = 0; i < theNode.childNodes.length; )
			{
				theNewNode.appendChild(theNode.childNodes[i]);
			}
			
			theParent.replaceChild(theNewNode, theNode);
		}
	}
	
	return true;
};




/* Get next element in the source code, traversing children and parent nodes */
function getNextElement(currElement, boolGetTextNodes)
{
	try
	{
		var nextElement = null;

		if (currElement.childNodes.length > 0)
		{
			nextElement = currElement.childNodes[0];
		}
		else if (currElement.nextSibling != null)
		{
			nextElement = currElement.nextSibling;
		}
		else
		{
			while (currElement.parentNode != null)
			{
				currElement = currElement.parentNode;

				if (currElement.nextSibling != null)
				{
					nextElement = currElement.nextSibling;

					break;
				}
			}
		}

		if (typeof boolGetTextNodes != "undefined" && boolGetTextNodes == false && nextElement != null && nextElement.nodeType == "3")
		{
			return getNextElement(nextElement, false);
		}

		return nextElement;
	}
	catch(error)
	{
		return null;
	}
};




/* Get previous element in the source code, traversing children and parent nodes */
function getPreviousElement(currElement, boolGetTextNodes)
{
	try
	{
		var previousElement = null;

		if (currElement.previousSibling != null)
		{
			previousElement = currElement.previousSibling;

			while (previousElement.childNodes.length > 0)
			{
				previousElement = previousElement.childNodes[previousElement.childNodes.length - 1];
			}
		}
		else if (currElement.parentNode != null)
		{
			previousElement = currElement.parentNode;
		}

		if (typeof boolGetTextNodes != "undefined" && boolGetTextNodes == false && previousElement != null && previousElement.nodeType == "3")
		{
			return getNextElement(previousElement, false);
		}

		return previousElement;
	}
	catch(error)
	{
		return null;
	}
};




/* Get next element in the source code that is on the same level or higher than the current */
function getNextHigherElement(currElement, boolGetTextNodes)
{
	try
	{
		var nextElement = null;

		if (currElement.nextSibling != null)
		{
			nextElement = currElement.nextSibling
		}
		else
		{
			while (currElement.parentNode != null)
			{
				currElement = currElement.parentNode;

				if (currElement.nextSibling != null)
				{
					nextElement = currElement.nextSibling;

					break;
				}
			}
		}

		if (typeof boolGetTextNodes != "undefined" && boolGetTextNodes == false && nextElement.nodeType == "3")
		{
			return getNextHigherElement(nextElement, false);
		}

		return nextElement;
	}
	catch(error)
	{
		return null;
	}
};



/* Determine whether an element only contains blank or whitespace text nodes */
function isEmptyElement(target, excludeVar)
{
	if (typeof excludeVar == "undefined")
	{
		excludeVar = false;
	}

	if (target.nodeType == 1 && !target.nodeName.isValidEmpty() && ((excludeVar == false && target.id != "selectionStart" && target.id != "selectionEnd") || excludeVar == true) && !target.innerHTML.match(/&nbsp;|\xA0/))
	{
		if (target.childNodes.length > 0)
		{
			for (var i = 0; i < target.childNodes.length; i++)
			{
				if (!isEmptyElement(target.childNodes[i], excludeVar))
				{
					return false;
				}
			}
			
			return true;
		}
		else
		{
			return true;
		}
	}
	else if (target.nodeType == 3 && (target.nodeValue == null || target.nodeValue == "" || target.nodeValue.match(/^\s+$/) != null))
	{
		return true;
	}
	
	return false;
};




/* Create HTML markers around the current selection */
function markSelectionBoundaries(windowRef)
{
	if (typeof windowRef.editorFocus == "undefined" && !isSafari || (typeof windowRef.editorFocus != "undefined" && windowRef.editorFocus === true))
	{
		deleteSelectionBoundaries(windowRef);
	}

	try
	{
		/* Mozilla/Safari selection handling */	
		if (typeof windowRef.getSelection == "function")
		{
			var selection = windowRef.getSelection();

			/* Mozilla text range handling */
			if (typeof selection.getRangeAt == "function" && selection.rangeCount > 0)
			{
				var textRange = selection.getRangeAt(0).cloneRange();
			}

			/* Safari text range handling */
			else if (typeof selection.baseNode != "undefined")
			{
				/* Create a range from the end nodes to see whether the baseNode is after the extentNode i.e. the selection is from right to left */
				var textRange = windowRef.document.createRange();

				textRange.setStart(selection.baseNode, selection.baseOffset);
				textRange.setEnd(selection.extentNode, selection.extentOffset);

				if (textRange.collapsed)
				{
					textRange.setEnd(selection.baseNode, selection.baseOffset);
					textRange.setStart(selection.extentNode, selection.extentOffset);
				}
			}

			/* If selection starts and ends inside the same text node */			
			if ((typeof selection.baseNode != "undefined" && selection.baseNode == selection.extentNode && selection.baseNode.nodeType == 3) || (typeof selection.anchorNode != "undefined" && selection.anchorNode == selection.focusNode && selection.anchorNode.nodeType == 3))
			{
				var textContent = textRange.extractContents();

				var selectionEnd = windowRef.document.createElement("var");
				selectionEnd.setAttribute("id", "selectionEnd");
				textRange.insertNode(selectionEnd);
				
				var selectionStart = windowRef.document.createElement("var");
				selectionStart.setAttribute("id", "selectionStart");
				selectionEnd.parentNode.insertBefore(selectionStart, selectionEnd);
				
				if (textContent != null)
				{
					selectionEnd.parentNode.insertBefore(textContent, selectionEnd);
				}
				
				var emptyNode = selectionStart.nextSibling;
				
				/* Remove text nodes with no content (not even whitespace) */
				while(emptyNode != null && emptyNode != selectionEnd && emptyNode.nodeType == 3 && emptyNode.data == "")
				{
					emptyNode = emptyNode.nextSibling;
					emptyNode.parentNode.removeChild(emptyNode.previousSibling);
				}
			}
			else
			{
				if (textRange.collapsed)
				{
					var newVar = windowRef.document.createElement("var");
					newVar.setAttribute("id", "selectionEnd");
					textRange.insertNode(newVar);

					var newVar = windowRef.document.createElement("var");
					newVar.setAttribute("id", "selectionStart");
					textRange.insertNode(newVar);
				}
				else
				{
					var newVar = windowRef.document.createElement("var");
					newVar.setAttribute("id", "selectionStart");
					var textRangeCopy = textRange.cloneRange();
					textRangeCopy.collapse(true);
					textRangeCopy.insertNode(newVar);

					var newVar = windowRef.document.createElement("var");
					newVar.setAttribute("id", "selectionEnd");
					var textRangeCopy = textRange.cloneRange();
					textRangeCopy.collapse(false);
					textRangeCopy.insertNode(newVar);
				}
			}
		}
		/* Internet Explorer selection handling */
		else if (typeof windowRef.document.selection != "undefined")
		{
			var selection = windowRef.document.selection;
			var textRange = selection.createRange();

			var startRange = selection.createRange();
			var endRange = selection.createRange();

			if (selection.type == "Control")
			{
				if (textRange.length == 1 && textRange.item(0).nodeName.toLowerCase() == "img")
				{
					var newVar = windowRef.document.createElement("var");
					newVar.setAttribute("id", "selectionStart");
					textRange.item(0).parentNode.insertBefore(newVar, textRange.item(0));

					var newVar = windowRef.document.createElement("var");
					newVar.setAttribute("id", "selectionEnd");
					Ext.get(newVar).insertAfter(textRange.item(0));
				}
			}
			else if (selection.type != "None")
			{
				/* Set range copies to start and end of selection, to determine parent nodes at either end */
				startRange.collapse(true);
				endRange.collapse(false);
				startRange.pasteHTML('<var id="selectionStart"></var>');
				endRange.pasteHTML('<var id="selectionEnd"></var>');
			}
			else
			{
				startRange.pasteHTML('<var id="selectionStart"></var><var id="selectionEnd"></var>');
			}
		}
		
		var selectionStart = windowRef.document.getElementById("selectionStart");
		var selectionEnd = windowRef.document.getElementById("selectionStart");

		/* Remove empty text nodes from between selection */		
		if (selectionStart != null && selectionEnd != null)
		{
			var nextElement = getNextHigherElement(selectionStart);
			
			while (nextElement.nodeType == 3 || nextElement.id != "selectionEnd")
			{
				if (nextElement.nodeType == 3 && nextElement.nodeValue == "")
				{
					var previousElement = nextElement;
					nextElement = getNextElement(nextElement);
					previousElement.parentNode.removeChild(previousElement);
				}
				else
				{
					nextElement = getNextElement(nextElement);
				}
			}
		}
	}
	catch (error)
	{
		var selectionStart = windowRef.document.getElementById("selectionStart");
		var selectionEnd = windowRef.document.getElementById("selectionEnd");
		
		if (selectionStart  == null && selectionEnd == null)
		{
			deleteSelectionBoundaries(windowRef);
			
			var newVar = windowRef.document.createElement("var");
			newVar.setAttribute("id", "selectionStart");
			windowRef.document.body.appendChild(newVar);
	
			newVar = windowRef.document.createElement("var");
			newVar.setAttribute("id", "selectionEnd");
			windowRef.document.body.appendChild(newVar);
		}

		return false;
	}
	
	return true;
};




/* Create a selection from the current HTML selection markers */
function selectSelectionBoundaries(windowRef)
{
	var varNodes = windowRef.document.getElementsByTagName("var");
	var selectionStart = null;
	var selectionEnd = null;

	for (var i = 0; i < varNodes.length; i++)
	{
		if (varNodes[i].id == "selectionStart")
		{
			selectionStart = varNodes[i];
		}
		
		if (varNodes[i].id == "selectionEnd")
		{
			selectionEnd = varNodes[i];
		}
	}
	
	if (selectionStart == null || selectionEnd == null)
	{
		return false;
	}
	
	/* FF & Safari */	
	if (typeof windowRef.getSelection == "function")
	{
		var selection = windowRef.getSelection();
		var textRange = windowRef.document.createRange();
		
		try
		{
			textRange.setStartAfter(selectionStart);
			textRange.setEndBefore(selectionEnd);
		}
		catch(error)
		{
		}
		
		/* Set Mozilla selection */
		if (typeof selection.removeAllRanges != "undefined")
		{
			selection.removeAllRanges();
			selection.addRange(textRange);
		}
		/* Safari */
		else if (typeof selection.setBaseAndExtent != "undefined")
		{
			selection.setBaseAndExtent(selectionStart, 0, selectionEnd, 0);
		}
	}
	else if (typeof windowRef.document.selection != "undefined")
	{
		var body = windowRef.document.getElementsByTagName("body")[0];
		var textRange = body.createTextRange();
		var endRange = body.createTextRange();

		/* IE needs *some* content to make a selection */
		if (selectionStart.nextSibling == selectionEnd)
		{
			try
			{
				selectionStart.innerHTML = "&nbsp;";
			}
			catch(error)
			{
			}
		}

		textRange.moveToElementText(selectionStart);
		endRange.moveToElementText(selectionEnd);
		textRange.setEndPoint("EndToStart", endRange);
		
		if (selectionStart.nextSibling == selectionEnd)
		{
			endRange.select();
		}
		else
		{
			textRange.select();
		}
		
		selectionStart.innerHTML = "";
	}
	
	return true;
};




/* Delete the content between HTML selection markers */
function deleteSelection(windowRef)
{
	var selectionStart = windowRef.document.getElementById("selectionStart");
	var selectionEnd = windowRef.document.getElementById("selectionEnd");
	
	var nextElement = getNextHigherElement(selectionStart);

	while (nextElement != null && nextElement.id != "selectionEnd")
	{
		// Safe to remove node if selectionEnd isn't a descendant
		if (!isDescendantNode(selectionEnd, nextElement))
		{
			var currElement = nextElement;
			nextElement = getNextHigherElement(nextElement);
			currElement.parentNode.removeChild(currElement);
		}
		else
		{
			nextElement = getNextElement(nextElement);
		}
	}
	
	if (nextElement != null)
	{
		Ext.get(selectionEnd).insertAfter(selectionStart);
	}
	
	return true;
};




/* Remove HTML selection markers */
function deleteSelectionBoundaries(windowRef)
{
	var varNodes = windowRef.document.getElementsByTagName("var");
	
	for (var i = 0; i < varNodes.length; i++)
	{
		if (varNodes[i].id == "selectionStart" || varNodes[i].id == "selectionEnd")
		{
			varNodes[i].parentNode.removeChild(varNodes[i]);

			i--;
		}
	}
	
	return true;
};




/* Remove ids from HTML selection markers (alternative to deleting them, so that the cursor doesn't disappear in FF) */
function nullifySelectionBoundaries(windowRef)
{
	var varNodes = windowRef.document.getElementsByTagName("var");
	
	for (var i = 0; i < varNodes.length; i++)
	{
		if (varNodes[i].id == "selectionStart" || varNodes[i].id == "selectionEnd")
		{
			varNodes[i].id = "";
		}
	}
	
	return true;
};




/* Get parent common to two elements */
function getCommonParent(element1, element2)
{
	startParent = element1.parentNode;
	
	while (startParent != null)
	{
		var endParent = element2.parentNode;

		while (endParent != null)
		{
			if (endParent == startParent)
			{
				break;
			}

			endParent = endParent.parentNode;
		}

		if (endParent == startParent)
		{
			break;
		}

		startParent = startParent.parentNode;
	}
	
	return startParent;
};




/* Wrap the current selection inside the specified inline tag type */
function insertInlineElement(elementName, editor, attributes)
{
	if (editor.iframeDocument.getElementById("selectionStart") == null)
	{
		markSelectionBoundaries(editor.iframeWindow)
	}
	
	editor.paragraphise();

	var selectionStart = editor.iframeDocument.getElementById("selectionStart");
	var selectionEnd = editor.iframeDocument.getElementById("selectionEnd");

	/* No selection made */
	if (selectionEnd == selectionStart.nextSibling)
	{
		var newInline = createElement(editor.iframeWindow, elementName, attributes);
		selectionStart.parentNode.insertBefore(newInline, selectionStart);
		newInline.appendChild(selectionStart);
		newInline.appendChild(selectionEnd);
	}
	else
	{
		var nextElement = getNextElement(selectionStart);
	
		/* Remove all fully selected elements that are the same as the to-be-inserted element */
		while (nextElement.id != "selectionEnd")
		{
			if (nextElement.nodeType != "3" && !isDescendantNode(selectionEnd, nextElement) && nextElement.nodeName.toLowerCase() == elementName)
			{
				currElement = nextElement;
				nextElement = getPreviousElement(nextElement);
	
				replaceNodeWithChildren(currElement);
			}
			else
			{					
				nextElement = getNextElement(nextElement);
			}
		}
	
		var nextElement = getNextElement(selectionStart);
	
		/* Replace any initial text nodes with an enclosing inline element */
		if (nextElement.nodeType == "3")
		{
			var newInline = createElement(editor.iframeWindow, elementName, attributes);
	
			while (nextElement.id != "selectionEnd" && isDescendantNode(nextElement, selectionStart.parentNode) && !isDescendantNode(selectionEnd, nextElement))
			{
				currElement = nextElement;
				nextElement = getNextElement(nextElement);
	
				newInline.appendChild(currElement);
			}
	
			newInline = selectionStart.parentNode.insertBefore(newInline, selectionStart);
			newInline.parentNode.insertBefore(selectionStart, newInline);
		}
	
		/* For elements that are selected but do not contain the end node, wrap in inline element */
		while (nextElement.id != "selectionEnd")
		{
			if (!isDescendantNode(selectionEnd, nextElement))
			{
				if (nextElement.nodeName.isBlockName())
				{
					nextElement = getNextElement(nextElement);
				}
	
				var newInline = createElement(editor.iframeWindow, elementName, attributes);
	
				nextElement.parentNode.insertBefore(newInline, nextElement);
	
				while (nextElement.id != "selectionEnd" && !nextElement.nodeName.isBlockName() && !isDescendantNode(selectionEnd, nextElement))
				{
					currElement = nextElement;
					nextElement = getNextHigherElement(nextElement);
	
					newInline.appendChild(currElement);
				}
			}
			else
			{
				nextElement = getNextElement(nextElement);
			}
		}
	
		var blockParent = selectionStart.parentNode;
	
		while (!blockParent.nodeName.isBlockName())
		{
			blockParent = blockParent.parentNode;
		}
	
		var parentFirstChild = getNextElement(blockParent);
	
		var nextElement = parentFirstChild;
	
		/* Clean up nested elements */
		while (nextElement != null && !nextElement.nodeName.isBlockName())
		{
			var currElement = nextElement;
	
			if (currElement.nodeName.toLowerCase() == elementName)
			{
				/* Detect if current element has parent that is the same as the inline element that was added */
				while (currElement.parentNode != null)
				{
					if (currElement.parentNode.nodeName.toLowerCase() == elementName)
					{
						currElement = nextElement;
						nextElement = getPreviousElement(nextElement);
						replaceNodeWithChildren(currElement);
	
						break;
					}
					else
					{
						currElement = currElement.parentNode;
					}
				}
			}
	
			nextElement = getNextElement(nextElement);
		}
	
		var nextElement = parentFirstChild;
	
		/* Clean up adjoining identical elements */
		while (nextElement != null && !nextElement.nodeName.isBlockName())
		{
			if (nextElement.nodeName.toLowerCase() == elementName && nextElement.nextSibling != null)
			{
				var nextHigher = nextElement.nextSibling;
	
				while ((nextHigher.id == "selectionStart" || nextHigher.id == "selectionEnd") && nextHigher.nextSibling != null)
				{
					nextHigher = nextHigher.nextSibling;
				}
	
				/* Detect if next element has next sibling that is the same as the inline element that was added, then merge */
				if (nextHigher.nodeName.toLowerCase() == elementName)
				{
					while (nextHigher.previousSibling != nextElement)
					{
						nextElement.appendChild(nextHigher.previousSibling);
					}
	
					nextHigher = nextElement.appendChild(nextHigher);
					replaceNodeWithChildren(nextHigher);
				}
				else
				{
					nextElement = getNextElement(nextElement);
				}
			}
			else
			{
				nextElement = getNextElement(nextElement);
			}
		}
	
		/* Refresh selection marker references */
		selectionStart = editor.iframeDocument.getElementById("selectionStart");
		selectionEnd = editor.iframeDocument.getElementById("selectionEnd");
	
		removeEmpties(getCommonParent(selectionStart, selectionEnd));
	}

	selectSelectionBoundaries(editor.iframeWindow);
	nullifySelectionBoundaries(editor.iframeWindow);
	
	return true;
};




/* Remove any of the specified inline tag type from the selection */
function removeInlineElement(elementName, editor)
{
	if (editor.iframeDocument.getElementById("selectionStart") == null)
	{
		markSelectionBoundaries(editor.iframeWindow)
	}
	
	editor.paragraphise();

	var selectionStart = editor.iframeDocument.getElementById("selectionStart");
	var selectionEnd = editor.iframeDocument.getElementById("selectionEnd");

	var nextElement = getNextElement(selectionStart);

	/* Remove all fully selected elements that are the same as the specified element */
	while (nextElement.id != "selectionEnd")
	{
		if (nextElement.nodeName.toLowerCase() == elementName)
		{
			var currElement = nextElement;
			nextElement = getPreviousElement(nextElement);

			replaceNodeWithChildren(currElement);
		}
		else
		{					
			nextElement = getNextElement(nextElement);
		}
	}

	/* Remove any immediately enclosing elements that are the same as the specified */
	if (selectionStart.parentNode.nodeName.toLowerCase() == elementName && selectionStart == selectionStart.parentNode.firstChild && selectionEnd.parentNode == selectionStart.parentNode && selectionEnd == selectionEnd.parentNode.lastChild)
	{
		replaceNodeWithChildren(selectionStart.parentNode);
	}

	var startParent = selectionStart.parentNode;

	var parentInline = getCommonParent(selectionStart, selectionEnd);

	/* If selection is inside an inline element, remove only the selected part */
	while (parentInline != null && !parentInline.nodeName.isBlockName())
	{
		if (parentInline.parentNode != null && parentInline.nodeName.toLowerCase() == elementName)
		{
			var startParentClone = parentInline.cloneNode(true);
			var nextElement = getNextElement(startParentClone);

			while (nextElement.id != "selectionStart")
			{
				nextElement = getNextElement(nextElement);
			}

			while (nextElement != null)
			{
				var currElement = nextElement;
				nextElement = getNextElement(nextElement);
				currElement.parentNode.removeChild(currElement);
			}

			var endParentClone = parentInline.cloneNode(true);
			var endParentCloneSelectionEnd = getNextElement(endParentClone);

			while (endParentCloneSelectionEnd.id != "selectionEnd")
			{
				endParentCloneSelectionEnd = getNextElement(endParentCloneSelectionEnd);
			}

			var nextElement = getNextElement(endParentClone);

			while (nextElement.id != "selectionEnd")
			{
				if (nextElement.nodeType == 3 || !isDescendantNode(endParentCloneSelectionEnd, nextElement))
				{
					var currElement = nextElement;
					nextElement = getNextHigherElement(nextElement);
					currElement.parentNode.removeChild(currElement);
				}
				else
				{
					nextElement = getNextElement(nextElement);
				}
			}

			nextElement.parentNode.removeChild(nextElement);

			parentInline.parentNode.insertBefore(startParentClone, parentInline);
			Ext.get(endParentClone).insertAfter(parentInline);

			var nextElement = getNextElement(parentInline);

			while (nextElement.id != "selectionStart")
			{
				if (nextElement.nodeType == 3 || !isDescendantNode(selectionStart, nextElement))
				{
					var currElement = nextElement;
					nextElement = getNextHigherElement(nextElement);
					currElement.parentNode.removeChild(currElement);
				}
				else
				{
					nextElement = getNextElement(nextElement);
				}
			}

			var nextElement = getNextHigherElement(selectionEnd);

			while (isDescendantNode(nextElement, parentInline))
			{
				var currElement = nextElement;
				nextElement = getNextHigherElement(nextElement);
				currElement.parentNode.removeChild(currElement);
			}

			replaceNodeWithChildren(parentInline);


			break;
		}

		parentInline = parentInline.parentNode;
	}

	removeEmpties(getCommonParent(selectionStart, selectionEnd));

	selectSelectionBoundaries(editor.iframeWindow);
	deleteSelectionBoundaries(editor.iframeWindow);
	
	return true;
};




/* Clean the HTML code of the content area */
cleanSource = function(html, preserveSelection)
{
	html = html.validateTags();

	/* Remove leading and trailing whitespace */
	html = html.replace(/^\s+/, "");
	html = html.replace(/\s+$/, "");
	/* Remove style attribute inside any tag */
//	html = html.replace(/ style="[^"]*"/g, "");
	/* Replace improper BRs */
	html = html.replace(/<br>/g, "<br />");
	/* Replace improper HRs */
	html = html.replace(/<hr>/g, "<hr />");
	/* Replace improper IMGs */
	html = html.replace(/(<img [^>]+[^\/])>/g, "$1 />");
	/* Replace opening bold tags with strong */
	html = html.replace(/<b(\s+|>)/g, "<strong$1");
	/* Replace closing bold tags with closing strong */
	html = html.replace(/<\/b(\s+|>)/g, "</strong$1");
	/* Replace opening italic tags with em */
	html = html.replace(/<i(\s+|>)/g, "<em$1");
	/* Replace closing italic tags with closing em */
	html = html.replace(/<\/i(\s+|>)/g, "</em$1");
	/* Remove BRs right before the end of blocks */
	html = html.replace(/<br \/>\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/g, "</$1");
	/* Remove &nbsp; at the start of blocks */
	html = html.replace(/<(h1|h2|h3|h4|h5|h6|li|p)([^>]*)>\s*(&nbsp;|\xA0)([^<])/g, "<$1$2>$4");
	/* Remove &nbsp; right before the end of blocks */
	html = html.replace(/([^>])(&nbsp;|\xA0|\s)*<\/(h1|h2|h3|h4|h5|h6|li|p)/g, "$1</$3");
	if (preserveSelection)
	{
		/* Preserve empty var tags (for selection) */
		html = html.replace(/(<var[^>]*>)\s*<\/var>/g, "$1-</var>");
	}
	/* Remove empty tags */
	html = html.replace(/(<[^\/]>|<[^\/][^>]*[^\/]>)\s*<\/[^>]*>/g, "");
	/* Remove contents of var tags (for selection) */
	html = html.replace(/(<var[^>]*>)[^<]*<\/var>/g, "$1</var>");
	/* Remove Ext-generated IDs */
	html = html.replace(/ id="ext-gen[^"]+"/g, "");
	/* Final cleanout for MS Word cruft */
	html = html.replace(/<\?xml[^>]*>/g, "");
	html = html.replace(/<[^ >]+:[^>]*>/g, "");
	html = html.replace(/<\/[^ >]+:[^>]*>/g, "");
	return html;
};




/* Determine whether one element is a child of another */
function isDescendantNode(descendant, ancestor)
{
	while (descendant.parentNode != null && descendant.parentNode.nodeName.toLowerCase() != "#document")
	{
		if (descendant.parentNode == ancestor)
		{
			return true;
		}
		else
		{
			descendant = descendant.parentNode;
		}
	}
	
	return false;
};




/* Replace a node with its children -- delete the item and move its children up one level in the hierarchy */
function replaceNodeWithChildren(theNode)
{
	var theChildren = new Array();
	var theParent = theNode.parentNode;
	var theIndex = 0;
	
	if (theParent != null)
	{
		/* Find the index of the element to be removed, as its first child will now take its place, and we can return this from the function */
		for (var i = 0; i < theParent.childNodes.length; i++)
		{
			if (theParent.childNodes[i] == theNode)
			{
				theIndex = i;

				break;
			}
		}
	
		for (var i = 0; i < theNode.childNodes.length; i++)
		{
			theChildren.push(theNode.childNodes[i].cloneNode(true));
		}
		
		for (var i = 0; i < theChildren.length; i++)
		{
			theParent.insertBefore(theChildren[i], theNode);
		}
		
		theParent.removeChild(theNode);
		
		return theParent.childNodes[theIndex];
	}
	
	return null;
};




/* Remove empty elements */
function removeEmpties(parentElement)
{
	/* Clean-up empty elements */
	var nextElement = getNextElement(parentElement);

	while (nextElement != null && isDescendantNode(nextElement, parentElement))
	{
		if (isEmptyElement(nextElement))
		{
			currElement = nextElement;
			nextElement = getNextHigherElement(nextElement);
			currElement.parentNode.removeChild(currElement);
		}
		else
		{
			nextElement = getNextElement(nextElement);
		}
	}

	return true;
};




/* Retrieve a cross-browser selection object */
function selectionObj(windowRef)
{
	this.selection = null;
	this.collapsed = false;
	this.textRange = null;

	try
	{
		/* Mozilla/Safari selection handling */	
		if (typeof windowRef.getSelection == "function")
		{
			this.selection = windowRef.getSelection();

			/* Mozilla text range handling */
			if (typeof this.selection.getRangeAt == "function" && this.selection.rangeCount > 0)
			{
				this.textRange = this.selection.getRangeAt(0);
			}

			/* Safari text range handling */
			else if (typeof this.selection.baseNode != "undefined")
			{
				/* Create a range from the end nodes to see whether the baseNode is after the extentNode i.e. the selection is from right to left */
				this.textRange = windowRef.document.createRange();

				this.textRange.setStart(this.selection.baseNode, this.selection.baseOffset);
				this.textRange.setEnd(this.selection.extentNode, this.selection.extentOffset);

				if (this.textRange.collapsed)
				{
					this.textRange.setEnd(this.selection.baseNode, this.selection.baseOffset);
					this.textRange.setStart(this.selection.extentNode, this.selection.extentOffset);
				}
			}
			else
			{
				return false;
			}

			if (this.selection.isCollapsed)
			{
				this.collapsed = true;
			}
		}

		/* Internet Explorer selection handling */
		else if (typeof windowRef.document.selection != "undefined")
		{
			this.selection = windowRef.document.selection;
			this.textRange = this.selection.createRange();

			if (this.selection.type == "None")
			{
				this.collapsed = true;
			}
		}
		else
		{
			return null;
		}

		return true;
	}
	catch (error)
	{
		return false;
	}
};




/* Check if a string is the nodeName of an accepted element */
String.prototype.isAcceptedElementName = function()
{
	var elementList = new Array("#text", "a", "blockquote", "br", "del", "em", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "img", "li", "ol", "p", "strong", "u", "ul", "var");
	var theName = this.toLowerCase();
	
	for (var i = 0; i < elementList.length; i++)
	{
		if (theName == elementList[i])
		{
			return true;
		}
	}
	
	return false;
};




/* Check if a string is the nodeName of a block element */
String.prototype.isBlockName = function()
{
	var blockList = new Array("body", "blockquote", "div", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "li", "ol", "p", "ul");
	var theName = this.toLowerCase();
	
	for (var i = 0; i < blockList.length; i++)
	{
		if (theName == blockList[i])
		{
			return true;
		}
	}
	
	return false;
};




/* Check if a string is the nodeName of an inline element */
String.prototype.isInlineName = function()
{
	var inlineList = new Array("#text", "a", "br", "del", "em", "font", "span", "strong", "u", "var");
	var theName = this.toLowerCase();
	
	for (var i = 0; i < inlineList.length; i++)
	{
		if (theName == inlineList[i])
		{
			return true;
		}
	}
	
	return false;
};




/* Check if a string is the nodeName of an element that is not allowed to have any children */
String.prototype.isValidEmpty = function()
{
	var emptyList = new Array("br", "hr", "img");
	var theName = this.toLowerCase();
	
	for (var i = 0; i < emptyList.length; i++)
	{
		if (theName == emptyList[i])
		{
			return true;
		}
	}
	
	return false;
};




/* Make tags valid by converting uppercase element and attribute names to lowercase and quoting attributes */
String.prototype.validateTags = function()
{
	var theString = this;
	
	/* Replace uppercase element names with lowercase */
	theString = theString.replace(/<[^> ]*/g, function(match){return match.toLowerCase();});
	
	/* Replace uppercase attribute names with lowercase */
	theString = theString.replace(/<[^>]*>/g, function(match)
		{
			match = match.replace(/ [^= "]+=/g, function(match2){return match2.toLowerCase();});

			return match;
		});
			
	/* Put quotes around unquoted attributes */
	theString = theString.replace(/<[^>]*>/g, function(match)
		{
			match = match.replace(/( [^=]+=)([^"][^ >]*)/g, "$1\"$2\"");
			
			return match;
		});
		
	/* Remove empty attributes */
	theString = theString.replace(/<[^>]*>/g, function(match)
		{
			match = match.replace(/ [^=]+=""/g, "");
			
			return match;
		});
		
	return theString;
};




function createElement(windowRef, elementName, attributes)
{
	var element = windowRef.document.createElement(elementName);
	
	if (typeof attributes != "undefined")
	{
		for (var att in attributes)
		{
			element.setAttribute(att, attributes[att]);
		}
	}
	
	return element;
};




function getPosition(theElement)
{
  var positionX = 0;
  var positionY = 0;

  while (theElement != null)
  {
    positionX += theElement.offsetLeft;
    positionY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }
  
  return [positionX, positionY];
};

var widgConfig = {

	/* Path to toolbar images */
	imagePath: "images/",

	/* Path to plugins */
	pluginsPath: "plugins/",

	/* Path to stylesheet for content inside editor */
	widgStylesheet: "css/widgContent.css",
	
	/* Automatically clean pasted content */
	autoClean: true,
	
	/* Swap shit-enter and ctrl-enter for line breaks and submission */
	shiftSubmit: false
	
};




var widgButtons = {
	/* Default button types */
	bold: {
		className: "widgButtonBold",
		title: "Bold",
		action: onclickBold,
		image: widgConfig.imagePath + "widgeditor_button_bold.gif"
	},
	
	italic: {
		className: "widgButtonItalic",
		title: "Italic",
		action: onclickItalic,
		image: widgConfig.imagePath + "widgeditor_button_italic.gif"
	},
	
	strikethrough: {
		className: "widgButtonStrikethrough",
		title: "Strikethrough",
		action: onclickStrikethrough,
		image: widgConfig.imagePath + "widgeditor_button_strikethrough.gif"
	},
	
	underline: {
		className: "widgButtonUnderline",
		title: "Underline",
		action: onclickUnderline,
		image: widgConfig.imagePath + "widgeditor_button_underline.gif"
	},
	
	unordered: {
		className: "widgButtonUnordered",
		title: "Unordered List",
		action: onclickUnorderedList,
		image: widgConfig.imagePath + "widgeditor_button_unordered.gif"
	},
	
	ordered: {
		className: "widgButtonOrdered",
		title: "Ordered List",
		action: onclickOrderedList,
		image: widgConfig.imagePath + "widgeditor_button_ordered.gif"
	}
};




/* Buttons to be included on toolbar. Consists of (class name, title/alt, event handler, image) */
widgConfig.toolbarButtons = [widgButtons.bold, widgButtons.italic, widgButtons.underline, widgButtons.strikethrough, "colour", "anchor", "emoticons", widgButtons.unordered, widgButtons.ordered, "image", "video"];

