/* TAMTAM */

if(typeof(TamTam) == 'undefined') {
  TamTam = {}
 }

TamTam.VERSION = "0.1";
TamTam.NAME    = "TamTam";


/* BASE */

if(typeof(TamTam.Base) == 'undefined') {
  TamTam.Base = {}
 }

TamTam.Base.VERSION = "0.1";
TamTam.Base.NAME    = "TamTam.Base";

MochiKit.Base.update(TamTam.Base, {
  getRandom: function() {
               var s = "";

               for(var i = 0; i <9 ; i++)
                 s += ""+Math.round((Math.random()*9)+1);

               return s;
	     },

  constructActionURL: function(args) {
                           var argumentQueryArgument = MochiKit.Base.serializeJSON(args);
                           return encodeURIComponent(argumentQueryArgument);
		       },

  getBaseURL: function() {
                var baseURL = window.location.toString();
                var queryParamIndex = baseURL.indexOf('?');

                if (queryParamIndex != -1) {
                  baseURL = baseURL.substring(0, queryParamIndex);
                }

                if (baseURL.charAt(baseURL.length - 1) == '#') {
                  baseURL = baseURL.substring(0, baseURL.length-2);
                }

                if (baseURL.indexOf("#") != -1) {
                  baseURL = baseURL.substring(0, baseURL.indexOf("#"));
                }

                if (baseURL.charAt(baseURL.length - 1) != '../index.html') {
                  baseURL += '../index.html';
                }

                return baseURL;
              } 
});
	      

/* EMBED EDITOR */

if(typeof(TamTam.EmbedEditor) == "undefined") {
  TamTam.EmbedEditor = {}
}

TamTam.EmbedEditor.VERSION = "0.1";
TamTam.EmbedEditor.NAME    = "TamTam.EmbedEditor";

TamTam.EmbedEditor.selected_panel = null;
TamTam.EmbedEditor.saving_panel   = false;

MochiKit.Base.update(TamTam.EmbedEditor, {
  touch_document: function() {
                    if(TamTam.EmbedEditor.selected_panel != null) {
                      var url = TamTam.Base.getBaseURL()+"_embed/?method=touch&n_id="+TamTam.Base.getRandom();
                      var d = loadJSONDoc(url);
                      d.addCallback(function () {});
                      d.addErrback(function () {});
    
                      setTimeout(TamTam.EmbedEditor.touch_document, 3000.0);
                     }
		    },

  EventCopy: function() {
    var output =  document.forms["form_"+TamTam.EmbedEditor.selected_panel];

      if(document.selection) {
        alert(1);
      } if(output.text.selectionStart || output.text.selectionStart == '0') {
	var begin     = output.text.value.substr(0, output.text.selectionStart);
	var copytext  = output.text.value.substr(output.text.selectionStart, output.text.selectionEnd - output.text.selectionStart);

	var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
	if (!str) return false;

	str.data = copytext;

	var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
	if (!trans) return false;

	trans.addDataFlavor("text/unicode");
	trans.setTransferData("text/unicode",str,copytext.length * 2);

	var clipid = Components.interfaces.nsIClipboard;
	var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
	if (!clip) return false;

	clip.setData(trans,null,clipid.kGlobalClipboard);
      }
  },

  EventPaste: function() {
    var output =  document.forms["form_"+TamTam.EmbedEditor.selected_panel];

    output.text.focus();

    PastedText = output.text.createTextRange();

    PastedText.execCommand("Paste");
  },

  EditPanel: function(panel_name) {
               function _okEditPanel(data) {
                 var panel_name = TamTam.EmbedEditor.selected_panel;
                 var text  = data["text"];
                 var title = data["title"];


		 var url = TamTam.Base.getBaseURL();

                 var editor = DIV(null,
                   FORM({"action": "javascript:void(0)", "method": "GET", "name": "form_"+panel_name}, 
                     SPAN({"style": "font-size: 10pt;", "id": "editor_line_"+TamTam.EmbedEditor.selected_panel},
			  A({"href": "#", "class":"editorlink", "onclick": "javascript:TamTam.EmbedEditor.SavePanel()"}, createDOM("B", null, "Save changes")),
		       " | ",
                       A({"href": "#previewanchor", "class":"editorlink", "onclick": "javascript:TamTam.EmbedEditor.PreviewPanel()"}, "Preview"),
                       " | ",
                       A({"href": "javascript:void(0)", "class":"editorlink", "onclick": "javascript:TamTam.EmbedEditor.CancelEdit();"}, "Discard changes")
                     ),
		     DIV(null, 
			 /*			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.EventCopy()"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_copy.gif", "alt": "COPY"})),
			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.EventPaste()"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_paste.gif", "alt": "PASTE"})),

			   IMG({"src": "sys/htmlarea/images/ed_blank.gif"}), */


			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.Formatting.SurroundText(\"'''\", \"'''\")", "alt": "BOLD"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_format_bold.gif"})),
			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.Formatting.SurroundText(\"''\", \"''\")", "alt": "ITALIC"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_format_italic.gif"})),
			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.Formatting.SurroundText(\"__\", \"__\")", "alt": "UNDERLINE"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_format_underline.gif"})),
			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.Formatting.SurroundText(\"^\", \"^\")", "alt": "SUPERSCRIPT"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_format_sup.gif"})),
			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.Formatting.SurroundText(\",,\", \",,\")", "alt": "SUBSCRIPT"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_format_sub.gif"})),


                         IMG({"src": "sys/htmlarea/images/ed_blank.gif"}),
			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.Dialog.LinkDialog()"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_link.gif", "alt": "LINK"})),
                         IMG({"src": "sys/htmlarea/images/ed_blank.gif"}),
			 A({"href": "#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.Dialog.CharmapDialog()"},
			   IMG({"border": 0, "src": "sys/htmlarea/images/ed_charmap.gif", "alt": "INSERT SYMBOL"}))


 		     ),
   		     DIV({"id": "editor_insert_"+TamTam.EmbedEditor.selected_panel}),

                     INPUT({"class": "embededitortitle", "type": "text", "name": "title", "value": title} ),
			TEXTAREA({"class": "embededitortext", "wrap": "virtual", "rows": 20, "cols": 50, "name": "text"})),

		     FORM({"name":"formembedpreview", "method": "POST", "action": url+"?__preview__=1", "target":"embedpreview"}, 
			  INPUT({"type":"hidden", "name": "text", "value":""}),
                          INPUT({"type":"hidden", "name": "panel", "value":"Content"})
			  ),
  		     A({"name":"previewanchor"}),
   		     DIV({"style":"display: none;", "id":"embededitorpreview"},
			 createDOM("iframe", {"id":"embedpreview", "name":"embedpreview"}), BR(), A({"href":"#embedanchor", "onclick": "javascript:TamTam.EmbedEditor.PreviewOff()"}, "Switch preview off")
			) 
                    );

                 replaceChildNodes("editor_"+panel_name, editor);
                 hideElement("editor_options_"+panel_name);

		 // thank you internet explorer
                 var e = getElementsByTagAndClassName("textarea", "embededitortext")[0];
                 e.value = text;
               }



               var url = TamTam.Base.getBaseURL()+"_embed/panel/"+panel_name+"?method=get_data&n_id="+TamTam.Base.getRandom();

               var d = loadJSONDoc(url);

               d.addCallback(_okEditPanel);
               d.addErrback(function() { alert("Could not read data!"); });

               TamTam.EmbedEditor.selected_panel = panel_name;
 
               var loading_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Loading data...");

               replaceChildNodes("editor_options_"+panel_name, loading_data);
               setTimeout(TamTam.EmbedEditor.touch_document, 3000.0);
 
               return true;
	      },
   SavePanel: function(form) {
               var output =  document.forms["form_"+TamTam.EmbedEditor.selected_panel];
   
               if(TamTam.EmbedEditor.saving_panel) {
                 alert("You should never see this!");
                 return;
               }

               TamTam.EmbedEditor.saving_panel = true;

	       //               var url=TamTam.Base.getBaseURL()+"_embed/panel/"+TamTam.EmbedEditor.selected_panel+"?method=save_panel&args="+TamTam.Base.constructActionURL({"text": output.text.value, "title": output.title.value})+"&n_id="+TamTam.Base.getRandom();
               var url=TamTam.Base.getBaseURL()+"_embed/panel/"+TamTam.EmbedEditor.selected_panel+"?method=save_panel&n_id="+TamTam.Base.getRandom();

               var xreq = getXMLHttpRequest();
               xreq.open("POST", url, true); 

	       //               var s = "args="+TamTam.Base.constructActionURL({"text": output.text.value, "title": output.title.value});
               var s = MochiKit.Base.serializeJSON({"text": output.text.value, "title": output.title.value});

               var d = sendXMLHttpRequest(xreq, s);

               d.addCallback(function() {window.location = '';});
               d.addErrback(function() { alert("ERROR SAVING!"); });

               var saving_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Saving changes...");

               replaceChildNodes("editor_line_"+TamTam.EmbedEditor.selected_panel, saving_data);
               TamTam.EmbedEditor.selected_panel = null;
	   },

   PreviewOff: function(form) {
	       var elem = $("embededitorpreview");
	       elem.style.display = "none";
	   },



   PreviewPanel: function(form) {
	       var elem = $("embededitorpreview");
	       //	       if(elem.style.display == "none") {
		 var output =  document.forms["form_"+TamTam.EmbedEditor.selected_panel];

		 elem.style.display = "block";
		 document.forms["formembedpreview"].text.value = output.text.value;
		 document.forms["formembedpreview"].panel.value = TamTam.EmbedEditor.selected_panel;

		 document.forms["formembedpreview"].submit();
		 //      } else {
		 // elem.style.display = "none";
		 // }

	   },

  CancelEdit: function() {
                var url = TamTam.Base.getBaseURL()+"_embed/?method=unlock&n_id="+TamTam.Base.getRandom();
                var d = loadJSONDoc(url);

                d.addCallback(function () {window.location='';});
                d.addErrback(function () {window.location='';});
			 
  
                var saving_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Canceling changes...");
   
                replaceChildNodes("editor_line_"+TamTam.EmbedEditor.selected_panel, saving_data);
                TamTam.EmbedEditor.selected_panel = null;
	      },

  EditAttachments: function(panel_name) {
			 var editor = DIV(null,A({"name": "attach"}),
					  FORM({"action": "_embed/attachment/upload/?submit=Submit", "method": "POST", "name": "form_"+panel_name, "enctype":"multipart/form-data", "action-charset":"utf-8", "id":"attachments"},
		  		          INPUT({"type":"hidden", "name":"__charset__"}),
					       INPUT({"type":"hidden", "name":"__nevow_form__", "value":"attachments"}),
                     SPAN({"style": "font-size: 10pt; padding-bottom: 5px", "id": "editor_line_"+panel_name},
			  A({"href": "#attach", "class":"editorlink", "onclick": 'javascript:TamTam.EmbedEditor.UploadAttachment("'+panel_name+'")'}, createDOM("B", null, "Upload file")),
                       " | ",
			  A({"id": "attachmorelink", "href": "#attach", "class":"editorlink", "onclick": 'javascript:TamTam.EmbedEditor.ShowMoreAttachment()'}, "Attach more files"),
                       " | ",
                       A({"href": "#", "class":"editorlink", "onclick": "javascript:TamTam.EmbedEditor.CancelEdit();"}, "Cancel")
			  ),  BR(null),

		       DIV({"class": "uploadattachmentodd"},
		         "Name (optional):", BR(null), 
         	         INPUT({"name": "attname0", "type": "text"}), BR(null),
		         "Attachment:", BR(null),
		         INPUT({"class": "embedattachfile", "type": "file", "name": "file0"})
		       ),
		       DIV({"id" : "attachmore", "style": "display: none"},
  		         DIV({"class": "uploadattachmenteven"},
		           "Name (optional):", BR(null), 
         	           INPUT({"name": "attname1", "type": "text"}), BR(null),
		           "Attachment:", BR(null),
			     INPUT({"class": "embedattachfile", "type": "file", "name": "file1"})
			 ),

  		         DIV({"class": "uploadattachmentodd"},
		           "Name (optional):", BR(null), 
         	           INPUT({"name": "attname2", "type": "text"}), BR(null),
		           "Attachment:", BR(null),
			     INPUT({"class": "embedattachfile", "type": "file", "name": "file2"})
		         ),
  		         DIV({"class": "uploadattachmenteven"},
		           "Name (optional):", BR(null), 
         	           INPUT({"name": "attname3", "type": "text"}), BR(null),
		           "Attachment:", BR(null),
			     INPUT({"class": "embedattachfile", "type": "file", "name": "file3"})
			 ),

  		         DIV({"class": "uploadattachmentodd"},
		           "Name (optional):", BR(null), 
         	           INPUT({"name": "attname4", "type": "text"}), BR(null),
		           "Attachment:", BR(null),
			     INPUT({"class": "embedattachfile", "type": "file", "name": "file4"})
			 )
		       )
                      ));

                 replaceChildNodes("editor_options_"+panel_name, editor);
                 TamTam.EmbedEditor.selected_panel = panel_name;
 
               return true;
	    },

   UploadAttachment: function(name) {
   	       function _check_filename(file_name) {
                  if(file_name) {
                    if(file_name.value != "") {
                      if(file_name.value.search(/.+\..+/) == -1) {
                        alert("File name _must_ have extension !\neg. picture.jpg, sound.mp3 etc.");
                        return 1;
                      }
                    }
                  }
                  return 0;
               }

               var output =  document.forms["form_"+name];

               if(_check_filename(output.attname)) return;
               if(_check_filename(output.attname0)) return;
               if(_check_filename(output.attname1)) return;
               if(_check_filename(output.attname2)) return;
               if(_check_filename(output.attname3)) return;
	       
               var saving_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Uploading file...");

               replaceChildNodes("editor_line_"+name, saving_data);
   
	       output.submit();
	    },

  ShowMoreAttachment: function() {
         var el = $("attachmore");

         if(el.style.display == "none") {
             el.style.display = "block";
             replaceChildNodes($("attachmorelink"), "Attach one file");
         } else {
             el.style.display = "none";
             replaceChildNodes($("attachmorelink"), "Attach more files");
	 }
  },

  CancelInlineEdit: function(name) {
	 showElement($("inline_attachment_text_"+name));
         hideElement($("inline_attachment_form_"+name));
  },

  CancelInlineCreate: function(name) {
	 showElement($("inline_document_text_"+name));
         hideElement($("inline_document_form_"+name));
  },

  InlineAttachments: function(attachment_name) {
    	 var name = attachment_name.replace(/\./i, "_");
  	 var editor = DIV({"style": "padding: 10px; border: 1px solid #c0c0c0"},
				  FORM({"action": "_embed/attachment/uploadinline/", "method": "POST", "name": "form_"+name, "enctype":"multipart/form-data"},
                     SPAN({"style": "font-size: 10pt; padding-bottom: 5px", "id": "editor_line_"+name},
                       A({"href": "#", "class":"editorlink", "onclick": 'javascript:TamTam.EmbedEditor.UploadAttachment("'+name+'")'}, "Upload file"),
                       " | ",
                       A({"href": "javascript:void(0)", "class":"editorlink", "onclick": 'javascript:TamTam.EmbedEditor.CancelInlineEdit("'+name+'");'}, "Cancel")
			  ),  BR(null),
		       INPUT({"name": "attname", "type": "hidden", "value": attachment_name}),
                       INPUT({"class": "embedattachfile", "type": "file", "name": "file"})
                      ));

                 showElement($("inline_attachment_form_"+name));
		 replaceChildNodes("inline_attachment_form_"+name, editor); 
		 hideElement($("inline_attachment_text_"+name));

               return true;
	   },

   CreateNewDocument: function(document_name) {
               var url=TamTam.Base.getBaseURL()+"_embed/?method=new&args="+TamTam.Base.constructActionURL({"name": document_name})+"&n_id="+TamTam.Base.getRandom();

	       function _doc_created(data) {
                 var new_url = unescape(data["url"].replace(/\+/g,  " "));
		 window.location = new_url;
	       }

	       var d = loadJSONDoc(url);
               d.addCallback(_doc_created);

               var saving_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Creating document...");

               replaceChildNodes("editor_line_"+TamTam.EmbedEditor.selected_panel, saving_data);
               TamTam.EmbedEditor.selected_panel = null;
	   },


 InlineNewPage: function(text_id, page_name) {
  	 var editor = DIV({"style": "padding: 10px; border: 1px solid #c0c0c0"},
                       SPAN({"style": "font-size: 10pt; padding-bottom: 5px", "id": "editor_line_"+name},
                         A({"href": "#", "class":"editorlink", "onclick": 'javascript:TamTam.EmbedEditor.CreateNewDocument("'+page_name+'")'}, "Create new document"),
                       " | ",
                         A({"href": "#", "class":"editorlink", "onclick": 'javascript:TamTam.EmbedEditor.CancelInlineCreate("'+text_id+'");'}, "Cancel")
			  ),  BR(null),
			  "Do you want to create new page ", page_name, "?"
                      );

                 showElement($("inline_document_form_"+text_id));
		 replaceChildNodes("inline_document_form_"+text_id, editor); 
		 hideElement($("inline_document_text_"+text_id));

               return true;
	      }
  });

/* EMBED EDITOR FORMATTING*/

if(typeof(TamTam.EmbedEditor.Formatting) == "undefined") {
  TamTam.EmbedEditor.Formatting = {}
}

TamTam.EmbedEditor.Formatting.VERSION = "0.1";
TamTam.EmbedEditor.Formatting.NAME    = "TamTam.EmbedEditor.Formatting";

MochiKit.Base.update(TamTam.EmbedEditor.Formatting, {
 SurroundText: function(text1, text2) {
        var textarea =  document.forms["form_"+TamTam.EmbedEditor.selected_panel].text;
	// Can a text range be created?
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;
		caretPos.select();
	}
	// Mozilla text range wrap.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;

		if (textarea.setSelectionRange)
		{
			if (selection.length == 0)
				textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
			else
				textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
			textarea.focus();
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put them on the end, then.
	else
	{
		textarea.value += text1 + text2;
		textarea.focus(textarea.value.length - 1);
	}
   },

 ReplaceText: function(text) {
        var textarea =  document.forms["form_"+TamTam.EmbedEditor.selected_panel].text;

	// Attempt to create a text range (IE).
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		caretPos.select();
	}
	// Mozilla text range replace.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text + end;

		if (textarea.setSelectionRange)
		{
			textarea.focus();
			textarea.setSelectionRange(begin.length + text.length, begin.length + text.length);
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put it on the end.
	else
	{
		textarea.value += text;
		textarea.focus(textarea.value.length - 1);
	}
}



  });


/* EMBED EDITOR DIALOG */

if(typeof(TamTam.EmbedEditor.Dialog) == "undefined") {
  TamTam.EmbedEditor.Dialog = {}
}

TamTam.EmbedEditor.Dialog.VERSION = "0.1";
TamTam.EmbedEditor.Dialog.NAME    = "TamTam.EmbedEditor.Formatting";

MochiKit.Base.update(TamTam.EmbedEditor.Dialog, {
    // no need for this, MochiKit has its own function
  getPageCoors: function(element) {
    var coords = {x: 0, y: 0};
    while (element) {
      coords.x += element.offsetLeft;
      coords.y += element.offsetTop;
      element = element.offsetParent;
    }
    return coords;
 },

 CloseDialog: function() {
   var insert_name = "editor_insert_"+TamTam.EmbedEditor.selected_panel;

   replaceChildNodes($(insert_name));
 },

 EventLinkType: function(link) {
   var form = $(link);
   var value = form.linktype.options[form.linktype.selectedIndex].value;

   if(value == "document") {
      replaceChildNodes($("editor_place_"+TamTam.EmbedEditor.selected_panel), TamTam.EmbedEditor.Dialog.ShowLinkDocument);
   }

   if(value == "attachment") {
      replaceChildNodes($("editor_place_"+TamTam.EmbedEditor.selected_panel), TamTam.EmbedEditor.Dialog.ShowLinkAttachment);
   }

   if(value == "url") {
      replaceChildNodes($("editor_place_"+TamTam.EmbedEditor.selected_panel), TamTam.EmbedEditor.Dialog.ShowLinkURL);
   }

   if(value == "email") {
      replaceChildNodes($("editor_place_"+TamTam.EmbedEditor.selected_panel), TamTam.EmbedEditor.Dialog.ShowLinkEmail);
   }

 },

 EventLinkCreate: function(link) {
   var form        = $("form_link_type_"+TamTam.EmbedEditor.selected_panel);
   var doc_name    = form.link.value;
   var value       = form.linktype.options[form.linktype.selectedIndex].value;

   if(value == "document") 
     TamTam.EmbedEditor.Formatting.SurroundText("["+doc_name+" ", "]");

   if(value == "attachment") 
     TamTam.EmbedEditor.Formatting.SurroundText("[attachment:"+doc_name+" ", "]");

   if(value == "email") 
     TamTam.EmbedEditor.Formatting.SurroundText("[mailto:"+doc_name+" ", "]");

   if(value == "url") 
     TamTam.EmbedEditor.Formatting.SurroundText("["+doc_name+" ", "]");

   TamTam.EmbedEditor.Dialog.CloseDialog();
 },

 NotImplemented: function() {
			 alert("Feature not implemented yet!");
 },

 EventBrowseDocument: function() {
    var winref = TamTam.EmbedEditor.Window.BrowseWindow();
    winref.on_select_callback = function (value) {
      var form        = $("form_link_type_"+TamTam.EmbedEditor.selected_panel);
      form.link.value = value;
    }
 },

 ShowLinkDocument: function() {
        return SPAN({}, "Document name:", BR(),
           TABLE({"width": "100%", "border": 0},
	     TR({},
	      TD({},
	       INPUT({"type":"text", "style": "width: 100%", "name": "link"})
		 )
		),
	      TD({},
		 INPUT({"type":"submit", "style": "border: 1px solid black; float: right", "value": "Browse", "onclick": "TamTam.EmbedEditor.Dialog.EventBrowseDocument()"}))

	     )
	  );
 },

 ShowLinkURL: function() {
   return SPAN({}, "URL:", BR(),
	       INPUT({"type":"text", "value": "http://", "style": "width: 100%", "name": "link"})
	  );
 },

 ShowLinkEmail: function() {
   return SPAN({}, "E-mail:",
                INPUT({"type":"text", "style": "width: 100%", "name": "link"})
	  );
 },

 ShowLinkAttachment: function() {
   return SPAN({}, "Attachment name:", BR(),
           TABLE({"width": "100%", "border": 0},
	     TR({},
	      TD({},
	       INPUT({"type":"text", "style": "width: 100%", "name": "link"})
		 )
		),
	      TD({},
		 INPUT({"type":"submit", "style": "border: 1px solid black; float: right", "value": "Browse", "onclick": "TamTam.EmbedEditor.Dialog.EventBrowseDocument()"}))


	     )

	 );
 },

 LinkDialog: function() {
   var name        = "editor_line_"+TamTam.EmbedEditor.selected_panel;
   var insert_name = "editor_insert_"+TamTam.EmbedEditor.selected_panel;

   var x = TamTam.EmbedEditor.Dialog.getPageCoors($(name)).x+20;
   var y = TamTam.EmbedEditor.Dialog.getPageCoors($(name)).y+50;

   var d = DIV({"style": "position: absolute;  background-color: #ffcc99; border: 1px solid black; top: "+y+"px; left: "+x+"px; width: 400px;", "id": "dialog_link_"+TamTam.EmbedEditor.selected_panel},
           DIV({"style": "padding: 10px 10px 10px 10px"},
            FORM({"id": "form_link_type_"+TamTam.EmbedEditor.selected_panel, "onsubmit": "return false"},
	     TABLE({"width": "100%"},
	      TR({},
	       TD({},
                DIV({},
                 "Link type:", BR(),
		 SELECT({"name": "linktype", "onchange": "TamTam.EmbedEditor.Dialog.EventLinkType('"+"form_link_type_"+TamTam.EmbedEditor.selected_panel+"')"},
                       OPTION({"value": "document"}, "Document"),
                       OPTION({"value": "attachment"}, "Attachment"),
		       OPTION({"value": "url"}, "URL"),
                       OPTION({"value": "email"}, "E-Mail")))
		  )
		 ),

	       TR({},
		TD({}," ")),

 	       TR({},
		TD({}, 
              	  DIV({"id": "editor_place_"+TamTam.EmbedEditor.selected_panel})
		)
	       ),

	       TR({},
		  TD({"height": "20"}," ")),

	       TR({},
 	        TD({"align": "right"},
		   INPUT({"type": "button", "value": "Create link", "style": "border: 1px solid black","onclick": "TamTam.EmbedEditor.Dialog.EventLinkCreate()"}),"  ",
		  INPUT({"type": "button", "value": "Cancel", "onclick": "TamTam.EmbedEditor.Dialog.CloseDialog()", "style": "border: 1px solid black"})
		   )
		  )
   	       )
	     )
	    )
	   );


  replaceChildNodes($(insert_name), d);

  //  roundElement("dialog_link_"+TamTam.EmbedEditor.selected_panel, {"corners": "all", "border": true});

  replaceChildNodes($("editor_place_"+TamTam.EmbedEditor.selected_panel), TamTam.EmbedEditor.Dialog.ShowLinkDocument);
 },

 ShowCharmap: function(charmap_type) {
   function make_link(t) {
     if(t == "") return BR({"style": "clear: both"});
     var l = A({"href": "#embedanchor", "onclick": "TamTam.EmbedEditor.Formatting.ReplaceText('"+t+"')"})
     l.innerHTML = t;
     return DIV({"style": "float: left; border: 1px solid white; margin: 3px; padding: 3px"}, l);
   }

   if(charmap_type == "currency") {
     var elements = ["&euro;", "&cent;", "&#163;", "&#165;", "&#164;", "&#8362;"];
   }

   if(charmap_type == "german") {
     var elements = ["&#228;", "&#196;", "&#246;", "&#214;", "&#252;", "&#220;", "&#223;"];
   }

   if(charmap_type == "arrows") {
     var elements = ["&#8592;", "&#8593;", "&#8594;", "&#8595;", "&#8596;", "&#8597;", "&#8598;", "&#8599;", "&#8600;", "&#8601;"];
   }

   if(charmap_type == "math") {
     var elements = ["&#215;", "&#247;", "&#43;", "&#45;", "&#8486;", "&#8730;", "&#188;", "&#189;", "&#190;", "&#8531;", "", "&#8532;", "&#8539;", "&#8540;", "&#8541;", "&#8542;", "&#37;", "&#8240;", "&#185;", "&#178;", "&#179;"];
   }

   if(charmap_type == "special1") {
     var elements = ["&#9650;", "&#9658;", "&#9660;", "&#9668;", "&#9632;", "&#9633;", "&#9635;", "&#9636;", "&#9637;", "&#9638;", "", "&#9639;", "&#9640;", "&#9641;", "&#9642;", "&#9643;", "&#9674;", "&#9675;", "&#9679;", "&#9786;", "&#9787;", "", "&#9788;"];
   }

   if(charmap_type == "special2") {
     var elements = ["&#9792;", "&#9794;", "&#9824;", "&#9828;", "&#9827;", "&#9831;", "&#9829;", "&#9825;", "&#9830;", "&#9733;", "", "&#9734;", "&#8962;", "&#8470;", "&#9742;", "&#9743;", "&#9832;", "&#9756;", "&#9758;", "&#9833;", "&#9834;", "", "&#9835;", "&#9836;", "&#9837;", "&#8224;", "&#8225;"];
   }

   if(charmap_type == "special3") {
     var elements = ["&#160;", "&#34;", "&#38;", "&#60;", "&#62;", "&#167;", "&#171;", "&#187;", "&#169;", "&#174;", "", "&#8482;", "&#177;", "&#191;", "&#161;", "&#64;"];
   }

   if(charmap_type == "greek") {
     var elements = ["&#913;", "&#914;", "&#915;", "&#916;", "&#917;", "&#918;", "&#919;", "&#920;", "&#921;", "&#922;", "", "&#923;", "&#924;", "&#925;", "&#926;", "&#927;", "&#928;", "&#929;", "&#931;", "&#932;", "&#933;", "", "&#934;", "&#935;", "&#936;", "&#937;", "&#945;",	"&#946;", "&#947;", "&#948;", "&#949;", "&#950;", "", "&#951;", "&#952;", "&#953;", "&#954;", "&#955;", "&#956;", "&#957;", "&#958;", "&#959;", "&#960;", "", "&#961;", "&#962;", "&#963;", "&#964;", "&#965;", "&#966;", "&#967;", "&#968;", "&#969;"];
   }

   

   return map(make_link, elements);
 },

 EventCharmapType: function(link) {
   var form = $(link);
   var value = form.linktype.options[form.linktype.selectedIndex].value;

   replaceChildNodes($("editor_place_"+TamTam.EmbedEditor.selected_panel), TamTam.EmbedEditor.Dialog.ShowCharmap(value));
 },



 CharmapDialog: function() {
   var name        = "editor_line_"+TamTam.EmbedEditor.selected_panel;
   var insert_name = "editor_insert_"+TamTam.EmbedEditor.selected_panel;

   var x = TamTam.EmbedEditor.Dialog.getPageCoors($(name)).x+20;
   var y = TamTam.EmbedEditor.Dialog.getPageCoors($(name)).y+50;

   var d = DIV({"style": "position: absolute;  background-color: #ffcc99; border: 1px solid black; top: "+y+"px; left: "+x+"px; width: 400px;", "id": "dialog_charmap_"+TamTam.EmbedEditor.selected_panel},
           DIV({"style": "padding: 10px 10px 10px 10px"},
            FORM({"id": "form_charmap_"+TamTam.EmbedEditor.selected_panel, "onsubmit": "return false"},
	     TABLE({"width": "100%"},
	      TR({},
	       TD({},
                DIV({},
                 "Type:", BR(),
		 SELECT({"name": "linktype", "onchange": "TamTam.EmbedEditor.Dialog.EventCharmapType('"+"form_charmap_"+TamTam.EmbedEditor.selected_panel+"')"},
                       OPTION({"value": "currency"}, "Money signs"),
                       OPTION({"value": "greek"}, "Greek"),
                       OPTION({"value": "german"}, "German umlaut"),

                       OPTION({"value": "special1"}, "Special signs 1"),
                       OPTION({"value": "special2"}, "Special signs 2"),
                       OPTION({"value": "special3"}, "Special signs 3"),
                       OPTION({"value": "math"}, "Math signs"),
                       OPTION({"value": "arrows"}, "Arrows")))
		  )
		 ),

	       TR({},
		  TD({"height": "20"}," ")),

 	       TR({},
		TD({}, 
		   DIV({"id": "editor_place_"+TamTam.EmbedEditor.selected_panel})
		)
	       ),

	       TR({},
		  TD({"height": "20"}," ")),

	       TR({},
 	        TD({"align": "right"},
		  INPUT({"type": "button", "value": "Cancel", "onclick": "TamTam.EmbedEditor.Dialog.CloseDialog()", "style": "border: 1px solid black"})
		   )
		  )
   	       )
	     )
	    )
	   );


  replaceChildNodes($(insert_name), d);

  replaceChildNodes($("editor_place_"+TamTam.EmbedEditor.selected_panel), TamTam.EmbedEditor.Dialog.ShowCharmap("currency"));
 }

});


/* EMBED EDITOR WINDOW */

if(typeof(TamTam.EmbedEditor.Window) == "undefined") {
  TamTam.EmbedEditor.Window = {}
}

TamTam.EmbedEditor.Window.VERSION = "0.1";
TamTam.EmbedEditor.Window.NAME    = "TamTam.EmbedEditor.Window";

MochiKit.Base.update(TamTam.EmbedEditor.Window, {
 BrowseWindow: function() {
     winref = window.open("_embed/browse/index.html", "browse", "width=600,height=400,toolbar=0,resizable=1,location=0,status=0,menubar=0,directories=0");
     return winref;
   }
  });




/* COMMENTS */

if(typeof(TamTam.Comments) == "undefined") {
  TamTam.Comments = {}
}

TamTam.Comments.VERSION = "0.1";
TamTam.Comments.NAME    = "TamTam.Comments";

MochiKit.Base.update(TamTam.Comments, {
  PostComment: function(sw) {
			 var comm = $("comments");
			 var commpost = $("postcomment");

                         switch(sw) {
			 case 1:
			   commpost.style.display = "block";
			   comm.style.display     = "block";
			   break;
			 case 2:
			 case 4:
			   comm.style.display = "block";
			   break;
			 case 3:
			   commpost.style.display = "block";
			   break;
                         }
		       },
  SaveComment: function(frm) {
       	        var url = TamTam.Base.getBaseURL()+"_comment/?method=post&n_id="+TamTam.Base.getRandom()+"&args="+TamTam.Base.constructActionURL({"text": frm.text.value, "email":frm.email.value});
                var d = loadJSONDoc(url);

                d.addCallback(function () {window.location='';});
                d.addErrback(function () {window.location='';});
			 
  
                var saving_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Saving comment...");
   
                replaceChildNodes("postcomment", saving_data);
                return true;
  },
 
  DeleteComment: function(comment_id) {
       	        if(confirm("Do you want to delete this comment?") == true) {
          	        var url = TamTam.Base.getBaseURL()+"_comment/?method=delete&n_id="+TamTam.Base.getRandom()+"&args="+TamTam.Base.constructActionURL({"id": comment_id});
                        var d = loadJSONDoc(url);

                        d.addCallback(function () {window.location='';});
                        d.addErrback(function () {window.location='';});
			 
  
                        var saving_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Deleting comment...");
   
                        replaceChildNodes("comment_action_" + comment_id, saving_data);
                        return true;
                }
                return false;

  },

  EditComment: function(comment_id) {
               function _okEditComment(data) {
                 var text  = data["text"]; 
                 var email = data["email"];

                 var editor = DIV(null,
                   FORM({"action": "javascript:void(0)", "method": "GET", "name": "form_comment_"+comment_id}, 
                     SPAN({"style": "font-size: 10pt;", "id": "editor_line_"+comment_id},
                       A({"href": "#", "class":"editorlink", "onclick": "javascript:TamTam.Comments.SaveCommentChange('"+comment_id+"')"}, "Save changes"),
                       " | ",
                       A({"href": "#", "class":"editorlink", "onclick": "javascript:window.location='';"}, "Discard changes")
                     ),
                     INPUT({"class": "embededitortitle", "type": "text", "name": "email", "value": email} ),
                     TEXTAREA({"class": "embededitortext", "rows": 20, "cols": 50, "name": "text"}, text))
                    );

                 replaceChildNodes("comment_"+comment_id, editor);
		 /*                 hideElement("editor_options_"+panel_name); */
               }



               var url = TamTam.Base.getBaseURL()+"_comment/?method=get_data&n_id="+TamTam.Base.getRandom()+"&args="+TamTam.Base.constructActionURL({"id": comment_id});;

               var d = loadJSONDoc(url);

               d.addCallback(_okEditComment);
               d.addErrback(function() { alert("Could not read data!"); });

               var loading_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Loading data...");

               replaceChildNodes("comment_action_"+comment_id, loading_data);
               setTimeout(TamTam.EmbedEditor.touch_document, 3000.0);
 
               return true;
	      },

   SaveCommentChange: function(comment_id) {
               var output =  document.forms["form_comment_"+comment_id];
   

               var url=TamTam.Base.getBaseURL()+"_comment/?method=set_data&args="+TamTam.Base.constructActionURL({"id": comment_id, "text": output.text.value, "email": output.email.value})+"&n_id="+TamTam.Base.getRandom();

               var xreq = getXMLHttpRequest();
               xreq.open("POST", url, true); 

               var d = sendXMLHttpRequest(xreq);
               d.addCallback(function() {window.location = '';});

               var saving_data = SPAN({"style": "background-color: red; color: white; text-weight: bold"}, "Saving changes...");

               replaceChildNodes("comment_"+comment_id, saving_data);
	   }

  });



