
/* - ++resource++monopol.theme.javascripts/monopol-commenting.js - */
function init_commenting (selector) {
    /* init
    Damit das Ganze auch ohne Javascript lesbar ist und funktioniert, machen wir den schönen Zauber per JS Initialisierung */
    // Kommentare einklappen
    jq(selector + ' ' + '.article_comment.open').removeClass('open').addClass('closed').find('a.comments-open-link img').attr('src', portal_url+'/twister-closed.gif');
    jq(selector + ' ' + '.comment_comments').removeClass('open').addClass('closed');
    // Subkommentare einklappen
    jq(selector + ' ' + '.comment_comment').removeClass('open').addClass('closed').find('a.comments-open-link img').attr('src', portal_url+'/twister-closed.gif');

    // formatierungselemente einblenden
    jq(selector + ' ' + 'div.button_line .left_buttons').show();
    // send buttons gegen links austauschen (input validation)
    jq(selector + ' ' + 'body').addClass('js_enabled');
    /* end init */


    /* article actions
    Artikel kommentieren, bewerten, ..
    Kommentar kommentieren, bewerten, .. */

    jq("a.open-comments").click(function() {
        jq('.article-actions-form').hide();
        jq('.comment-actions-form').hide();
        jq('#article-kommentieren-form').show();
    });

    // initial alle Forms (Artikel und Kommentare) schliessen
    jq(selector + ' ' + '.article-actions-form').hide();
    jq(selector + ' ' + '.comment-actions-form').hide();

    // show form
    jq(selector + ' ' + 'div.article-actions > a.article-form-action').click( function() {
        jq('.article-actions-form').hide();
        jq('.comment-actions-form').hide();
        jq('#'+this.id+'-form').show();
    });
    //hide form
    jq(selector + ' ' + '.comment_cancel, .rate_cancel, .blame_cancel').click( function() {
        jq('.article-actions-form').hide();
        jq('.comment-actions-form').hide();
    });
    jq(selector + ' ' + '.action_cancel').click( function() {
        jq('.article-actions-form').hide();
        jq('.comment-actions-form').hide();
    });


    /* comments actions*/
    // show form
    jq(selector + ' ' + '.comment-actions > a').click( function() {
        jq('.article-actions-form').hide();
        jq('.comment-actions-form').hide();
        //jq('.comment-actions-form').hide();

        // OBSOLETE
        // description einblenden
        // var comment_id = this.id.split('-')[2];
        // openlink = 'comments-open-link-' + comment_id;
        // jq('#'+openlink).click()
        jq('#'+this.id+'-form').show();
    });


    // show sub-comments (click auf twister)
    jq(selector + ' ' + 'a.comments-open-link').click( function() {
        var self = '#'+this.id.replace('comments-open-link-','comment-');
        var classname = jq(self)[0].className;
        if (classname.indexOf('open')==-1 ) {
            // andere schliessen
            // jq('.article_comment.open').removeClass('open').addClass('closed').find('a.comments-open-link img').attr('src', 'twister-closed.gif');
            // jq('.comment_comments').removeClass('open').addClass('closed')
            // sich selbst als open markieren
            jq(self).removeClass('closed').addClass('open').find('a.comments-open-link img').attr('src', portal_url+'/twister-open.gif');
            // comments als open markieren
            jq('#'+this.id.replace('open-link-','')).removeClass('closed').addClass('open')
        } else {
            // sich selbst als closed markieren
            jq(self).removeClass('open').addClass('closed').find('a.comments-open-link img').attr('src', portal_url+'/twister-closed.gif').end();
            // comments als closed markieren
            jq('#'+this.id.replace('open-link-','')).removeClass('open').addClass('closed')
        }

    });



    // format comment text

    // Zeige javascript actions
    jq(selector + ' ' + '.comment_action, .comment_action_cite, .comment_action_link').show();


    function applyTag(obj, tag)
    {
        wrapText(obj, '<'+tag+'>', '</'+tag+'>');

    };

    function wrapText(obj, beginTag, endTag)
    {
    	if(typeof obj.selectionStart == 'number')
    	{
    		// Mozilla, Opera, and other browsers
    		var start = obj.selectionStart;
    		var end   = obj.selectionEnd;

    		obj.value = obj.value.substring(0, start) + beginTag + obj.value.substring(start, end) + endTag + obj.value.substring(end, obj.value.length);
    	}
    	else if(document.selection)
    	{
    		// Internet Explorer

    		// make sure it's the textarea's selection
    		obj.focus();
    		var range = document.selection.createRange();
    		if(range.parentElement() != obj) return false;

    	    if(typeof range.text == 'string')
    	        document.selection.createRange().text = beginTag + range.text + endTag;
    	}
    	else
    		obj.value = obj.value; // += text;

    };

    function makeLink(obj)
    {
        var s= '';
        s = wrapTextA(obj, '<a href="', '">', '</a>');

    };

    function wrapTextA(obj, stra, strb, strc)
    {
    	if(typeof obj.selectionStart == 'number')
    	{
    		// Mozilla, Opera, and other browsers
    		var start = obj.selectionStart;
    		var end   = obj.selectionEnd;

    		obj.value = obj.value.substring(0, start) + stra + obj.value.substring(start, end) + strb + obj.value.substring(start, end) + strc + obj.value.substring(end, obj.value.length);
    	}
    	else if(document.selection)
    	{
    		// Internet Explorer

    		// make sure it's the textarea's selection
    		obj.focus();
    		var range = document.selection.createRange();
    		if(range.parentElement() != obj) return false;

    	    if(typeof range.text == 'string')
    	        document.selection.createRange().text = stra + range.text + strb + range.text + strc;
    	}
    	else
    		obj.value = obj.value; // += text;

    };

    function insertText(obj, text)
    {
    	if(typeof obj.selectionStart == 'number')
    	{
    		// Mozilla, Opera, and other browsers
    		var start = obj.selectionStart;
    		obj.value = obj.value.substring(0, start) + text + obj.value.substring(start, obj.value.length);
    	}
    	else if(document.selection)
    	{
    		// Internet Explorer

    		// make sure it's the textarea's selection
    		obj.focus();
    		var range = document.selection.createRange();
    		if(range.parentElement() != obj) return false;

    	    if(typeof range.text == 'string')
    	        document.selection.createRange().text = text;
    	}
    	else
    		obj.value = obj.value; // += text;

    };

    function getUserSelection(obj) {
        var userSelection;
        if (window.getSelection) {
         userSelection = window.getSelection();
        }
        else if (document.selection) { // should come last; Opera!
         userSelection = document.selection.createRange();
        }

        var selectedText = userSelection;
        if (userSelection.text) {
            selectedText = userSelection.text;
        } else {
            selectedText = userSelection;
        }

        return selectedText;

    };

    jq(selector + ' ' + '.comment_text').keypress(function (e) {
        // console.log(e.which)
        if (e.which==13) {
            insertText(this, '<br>');
        }
    })

    jq(selector + ' ' + '.comment_action').click( function() {
        // bold etc
        var id = this.id;
        var idl = id.split('_');
        var cl = jq(this).attr('class');
        if (cl.indexOf('blogentry')>-1) {
            ta = "body"
        } else {
            ta = idl[0]+'_'+'text'+'_'+idl[2];
        }
        applyTag(document.getElementById(ta), idl[1]);
    })

    jq(selector + ' ' + '.comment_action_cite').click( function() {
        id = this.id;
        idl = id.split('_');
        ta = idl[0]+'_'+'text'+'_'+idl[2];
        var main_text = document.getElementById('main_text');
        var text = getUserSelection(main_text);
        // Am Anfang der Textarea einfuegen //jq('#'+ta).val('<cite>' + text + '</cite>' + jq('#'+ta).val());
        insertText(document.getElementById(ta), '<cite>' + text + '</cite>');
    })

    jq(selector + ' ' + '.comment_action_break').click( function() {
        id = this.id;
        var idl = id.split('_');
        var cl = jq(this).attr('class');
        if (cl.indexOf('blogentry')>-1) {
            ta = "body"
        } else {
            ta = idl[0]+'_'+'text'+'_'+idl[2];
        }
        insertText(document.getElementById(ta), '<br>');
    })

    jq(selector + ' ' + '.comment_action_link').click( function() {
        id = this.id;
        var idl = id.split('_');
        var cl = jq(this).attr('class');
        if (cl.indexOf('blogentry')>-1) {
            ta = "body"
        } else {
            ta = idl[0]+'_'+'text'+'_'+idl[2];
        }
        makeLink(document.getElementById(ta));
    })

    // activate sending comments with ajax
    jq(selector + ' ' + '.comment_send').addClass('comment_send_js').removeClass('comment_send');
    jq(selector + ' ' + '.comment_send_js').click(function(event) {
        event.preventDefault();
        // see helper.py
        id = this.id;
        var idl = id.split('_');
        artikel_id = idl[2];
        if (idl[0]=='subcomment') {
            comment_id = idl[3];
            my_id = comment_id;
            typename = idl[4];
        } else {
            comment_id = '0'
            my_id = artikel_id;
            typename = idl[3];
        }
        // titleid = '#comment_title'+'_' + my_id;
        textid = '#comment_text'+'_' + my_id;
        // comment_title = jq(titleid).val();
        comment_text = jq(textid).val();
        comment_text = encodeURIComponent(comment_text);

        var args = 'artikel_id='+artikel_id+'&comment_id='+comment_id+'&comment_text='+comment_text+ '&typename='+typename;

        jq.ajax({
            url: portal_url+'/add_comment',
            type: 'POST',
            data: args,
            timeout: 5000,
            error: function(request){
                msg = request.responseText;
                jq('.form_message').text(msg); //text('Bitte Text.');
                setTimeout(function() {
                    jq('.form_message').text('');
                    jq('.form_message').css('display', 'none');
                }, 7000);
            },
            success: function(html){
                jq('#comments').before(html).remove(); // replacing #comments with new #comments
                // formular schliessen
                jq('.comment_cancel').click();
                // bind again to new content
                jq('#comment_message').text('Danke! Neuer Kommentar wurde erstellt.')
                jq('#comment_message-'+comment_id).text('Danke! Neuer Kommentar wurde erstellt.')
                jq('#comment_message-'+comment_id).show()
                init_commenting('#comments');
                setTimeout(function() {
                    jq('#comment_message').text('');
                    jq('.form_message').css('display', 'none');
                    jq('#comment_message-'+comment_id).hide()
                }, 5000);
            }
        });
    })


    // speak to
    // TODO offer box with autocomplete input field
    // jq('.comment_action_speakto').click( function() {
    //     jq('select.comment_speaktoselection').show();
    // });
    // jq('select.comment_speaktoselection').change(function () {
    //       var str = "";
    //       jq("#" + this.id +" option:selected").each(function () {
    //             str += jq(this).text(); // + " ";
    //           });
    //       id = this.id;
    //       idl = id.split('_');
    //       ta = idl[0]+'_'+'text'+'_'+idl[2];
    //       str = ' <span class="user-author">'+ str +'</span>'
    //       insertText(document.getElementById(ta), str);
    //     })
    // //     .change();

    jq(selector + ' ' + '.comment_action_speakto').click( function() {
        id = this.id;
        idl = id.split('_');
        ta = idl[0]+'_'+'text'+'_'+idl[2];
        insertText(document.getElementById(ta), '<span class="user-author">@'+idl[3]+'</span>:<br>');
    })

    // activate rating with ajax
    jq(selector + ' ' + '.rate_send').addClass('rate_send_js').removeClass('rate_send');
    jq(selector + ' ' + '.rate_send_js').click(function(event) {
        event.preventDefault();
        // see helper.py
        id = this.id;
        idl = id.split('_');
        var artikel_id = idl[2];
        var is_comment = false;
        var comment_id = 0;
        if (idl[0]=='subrate') {
            is_comment = true;
            comment_id = idl[3];
            my_id = comment_id;
            typename = idl[4];
        } else {
            is_comment = false;
            comment_id = '0'
            my_id = artikel_id;
            typename = idl[3];
        }

        value = jq(this).parent().siblings('.scale').find('input')[0].value;

        var args = 'artikel_id='+artikel_id+'&comment_id='+comment_id+'&value='+value+ '&typename='+typename;

        jq.ajax({
            url: portal_url+'/rate',
            type: 'POST',
            data: args,
            timeout: 5000,
            error: function(){
                jq('.form_message').text('Problem mit dem Rating.');
            },
            success: function(html){
                if (html=='') {
                    jq('.form_message').text('Bewertung ist nur einmal möglich.');
                    //jq('#comment_message-'+comment_id).text('Bewertung ist nur einmal möglich.');
                    setTimeout(function() {
                        jq('.form_message').text('');
                    }, 4000);
                } else {
                    if (1==1) {
                        // Neues Ergebnis im Artikel-Header
                        if (comment_id=='0') {
                            jq('#score').html(html);
                        } else {
                            jq('#score-'+comment_id).html(html);
                        }

                    }
                    // Rating-Form schliessen
                    jq('.form_message').text('Danke! Bewertung wurde vermerkt.');                    
                    //jq('#comment_message-'+comment_id).text('Danke! Bewertung wurde vermerkt.');  
                    setTimeout(function() {
                        jq('.form_message').text('');
                        jq('.rate_cancel').click();
                    }, 4000);
                }
            }
        });
    })

    // activate sending blaming with ajax
    jq(selector + ' ' + '.blame_send').addClass('blame_send_js').removeClass('blame_send');
    jq(selector + ' ' + '.blame_send_js').click(function(event) {
        event.preventDefault();
        // see helper.py
        id = this.id;
        var idl = id.split('-');
        comment_id = idl[1];
        var message = jq('#comment_blame-'+comment_id).val();

        var args = 'comment_id='+comment_id+'&message='+message;

        jq.ajax({
            url: portal_url+'/comment_blame',
            type: 'POST',
            data: args,
            timeout: 20000,
            error: function(){
                jq('.form_message').text('Es ist ein Fehler beim Senden der Mail aufgetreten.');
                setTimeout(function() {
                    jq('.form_message').text('');
                }, 4000);
            },
            success: function(html){
                jq('.form_message').text('Danke! Ihr Einwand wurde gemeldet.');
                setTimeout(function() {
                    jq('.form_message').text('');
                    jq('.blame_cancel').click();
                }, 4000);
            }
        });
    })
    jq('textarea.comment_blame').focus(function() {
    jq(this).val('')
    })


    // activate sending recommendation with ajax
    jq(selector + ' ' + '.recommend_send').addClass('recommend_send_js').removeClass('recommend_send');
    jq(selector + ' ' + '.recommend_send_js').click(function(event) {
        event.preventDefault();
        // see helper.py
        id = this.id;
        idl = id.split('_');
        artikel_id = idl[1];
        recipient = jq('#recommend_recipient').val();
        sender = jq('#recommend_sender').val();
        message = jq('#recommend_message').val();

        var args = 'artikel_id='+artikel_id+'&recipient='+recipient+'&sender='+sender+'&message='+message;

        jq.ajax({
            url: portal_url+'/recommend_article',
            type: 'POST',
            data: args,
            timeout: 20000,
            error: function(){
                jq('.form_message').text('Es ist ein Fehler beim Senden der Mail aufgetreten.');
                setTimeout(function() {
                    jq('.form_message').text('');
                }, 4000);
            },
            success: function(html){
                jq('.form_message').text('Ihre Empfehlung wurde versandt.');
                setTimeout(function() {
                    jq('.form_message').text('');
                    jq('.recommend_cancel').click();
                }, 4000);
            }
        });
    })

}

jq(document).ready(function() {

    init_commenting('body');

    // ersten Kommentar ausklappen
    jq('.article_comment a.comments-open-link:first').click()

    // Lokales: Kommentare ausklappen
    // jq('#lokales .article_comment a.comments-open-link').click()
    // jq('#lokales .article_comment a.comments-open-link:first').click()

})

