var commentManager;

CommentManager = function() {
    this.name="Commnet Manager v. 0.5";
    this.lastCalled = null;
    this.Params = { };
    this.Inputs = new Array();
    this.mainform = $("#form");
    this.startup();
}

CommentManager.prototype = {
    startup: function(){
        var self = this;

	self.sending = null;

        $("a.ml").bind("click",function(){ self.showForm(this); return false;});
        self.commentsForm = $("#commentsForm");

        var iframe = document.createElement('iframe');
        iframe.src=""
        iframe.name="upl_frame"
        iframe.style.display="none";
        iframe.style.width = "0";
        iframe.style.height = "0";
        $(iframe).load(function(){self.onload(this)});
        self.mainform.append(iframe);

        self.fileForm = document.createElement('form');
	/*
        self.fileForm.method="post";
        self.fileForm.enctype="multipart/form-data"
        self.fileForm.action="/uploadt/";
        self.fileForm.target="upl_frame";*/

	$(self.fileForm).attr({"method": "post",
                               "encoding": "multipart/form-data",
                               "enctype": "multipart/form-data",
                               "action": "/uploadt/",
                               "target":"upl_frame"});

        $("#__pForm",self.commentsForm).after(self.fileForm);
        self.fileForm.appendChild(self.commentsForm.find("input[type=file]").parent().get(0));

        self.Params['parent_node'] = self.commentsForm.find("input[name='parent_node']").val();
        var but = self.commentsForm.find("a[name='submit']").removeAttr('onclick');
        but.bind("click",function(){ self.checkForm(); return false;});
        self.lastCalled = self.mainform.find("a.ml").get(0);
    },
    showForm: function(el){
        var self = this;
        if(self.lastCalled != el){
            self.commentsForm.find("span.mceEditor").remove();
            var form = this.commentsForm.find("textarea.mceEditor");
            form.removeAttr("id").removeAttr("style");
            self.commentsForm.remove();
            self.commentsForm.appendTo($(el).parent().parent());
            self.lastCalled = el;
            self.Params['parent_node'] = el.href.split("#")[1].split("_")[1];
            mcEsetup();
	    var submit = self.commentsForm.find("a[name='submit']").get(0);
	    submit.onclick = function(){ self.checkForm(); return false; };
	    //submit.unbind("click");
            //self.commentsForm.find("a[name='submit']").bind("click",function(){ self.checkForm(); return false;});
        }
    },
    checkForm: function(){
        var self = this;
        self.Params['module'] = 'Common';
        self.Params['do']     = 'add_topic';
        self.Params['content'] = tinyMCE.activeEditor.getContent();
        self.Params['topic_name'] = self.commentsForm.find("input[name='topic_name']").val();
        var timeInput = self.commentsForm.find("input[name='time']").get(0);
        if (timeInput)
            self.Params['time'] = timeInput.value;

        var errors = 0;

        if(self.Params['content'] == ''){
            alert('Не заполнены обязательные поля!');
            errors = 1;
        }

        if(errors==0){
            if(self.fileForm.file.value!=''){
                self.fileForm.submit();
            }else{
                self.Params['file'] = '';
                self.submitForm(self.Params);
            }
        }
    },
    onload: function(el){
        var self = this;
        var d = null;
        if (el.contentDocument) {
			d = el.contentDocument;
        } else if (el.contentWindow) {
			var d = el.contentWindow.document;
        }
		if(d.location.href == "about:blank") {
			return;
        }
        if(d){
            self.Params['file'] = eval(d.body.innerHTML);
            if(self.Params['file']!='-1'){
                self.fileForm.reset();
                self.submitForm(self.Params);
            }
        }
    },
    submitForm: function(params){
        var self = this;
        if(!self.sending){
            self.sending = 1;
            $.post('/get/',params,function(data){self.showAnswer(data)},"xml");
	    }
    },
    showAnswer: function(data){
        var self = this;
        var html_XML = data.getElementsByTagName('html')[0];
        if (html_XML){
            tinyMCE.activeEditor.setContent('');
            self.commentsForm.find("input[name='topic_name']").val('');
            if($(self.lastCalled).parent().parent().get(0) == self.mainform.get(0)){
                var parent = $("#commentsCont .comments:first");
                if(parent.length==0){
                    $("#commentsCont").append($("<ul class='comments'>").append(_getTextContent(html_XML)));
                }else{
                    parent.append(_getTextContent(html_XML))
                }
            }else{
                var parent = $(self.lastCalled).parent().parent().parent();
                var comments = parent.find(".comments:first");
                if(comments.length==0){
                      parent.append($("<ul class='comments'>").append(_getTextContent(html_XML)))
                }else{
                    comments.append(_getTextContent(html_XML))
                }
            }
            var a = self.mainform.find("a.ml").get(0);
            $(".nml").each(function(){
                            $(this).bind("click",function(){
                                                    self.showForm(this); return false;
                                                    });
                            $(this).removeClass(".nml");
                            });
            self.showForm(a);

        }
	self.sending = null;
    }
}

var inviter;

Inviter = function() {
    this.params = { };
    this.start();
}

Inviter.prototype = {
    start: function(){
        var self = this;
        self.invForm = $("#inviter");
        self.invForm.toggleClass("hidden");
        $("#inv-b").bind("click",function(){self.invForm.toggleClass("hidden"); return false;});
        self.invForm.bind("submit",function(){ self.sendForm(this); return false; });
    },
    sendForm: function(el){
        var self = this;
        if(el.invite_id.value>0){
            self.params = {module: 'Common',
                           invite_id: el.invite_id.value,
                           topic_id: el.topic_id.value};
            self.params['do'] = 'invite';
            $.post('/get/',self.params,function(data){self.showResponse(data)},"xml");
        }else{
            alert('Не выбран адресат приглашения!');
        }
    },
    showResponse: function(xml){
        var self = this;
        var response = xml.getElementsByTagName('response')[0];
        if(response){
            var value = response.getAttribute('value');
            switch(value){
                case 'error':
                        self.invForm.find("label").addClass("error");
                    break;
                case 'ok':
                        var invited = self.invForm.find("span.invited");
                        if(invited.length==0){
                            self.invForm.append("<span class='invited'>Приглашение выслано</span>");
                        }
                    break;
            }
            var select = self.invForm.find("select").get(0);
            select.removeChild(select.options[select.options.selectedIndex]);
            //alert(select.options.selectedIndex);
        }
    }
}

var _getTextContent = window._getTextContent = function(xmlElement) {
    if (xmlElement.text != undefined) return xmlElement.text;
    else if (xmlElement.textContent != undefined) return xmlElement.textContent;
    else if (xmlElement.firstChild != undefined) return xmlElement.firstChild.nodeValue;
}

