/** Comments related JS routines **/
/** Author : Mahbub **/

$(document).ready(function() {
    $("#quote_0").hide();
    $.blockUI.defaults = {
        message:  '<h4>Please wait...</h4>',
        css: {
            padding:        0,
            margin:         0,
            width:          '30%',
            top:            '40%',
            left:           '35%',
            textAlign:      'center',
            color:          '#000',
            border:         '3px solid #1783C6',
            padding:		'7px',
            '-moz-border-radius' : '7px',
            '-webkit-border-radius': '7px',
            backgroundColor:'#fff',
            cursor:         'wait'
        },
        overlayCSS:  {
            backgroundColor:'#FFF',
            opacity:        '0.6'
        },
        growlCSS: {
            width:    '350px',
            top:      '10px',
            left:     '',
            right:    '10px',
            border:   'none',
            padding:  '5px',
            opacity:  '0.6',
            color:    '#fff',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius':    '10px'
        },
        baseZ: 1000,
        centerX: true,
        centerY: true,
        allowBodyStretch: true,
        constrainTabKey: true,
        fadeIn:  200,
        fadeOut:  200,
        timeout: 0,
        showOverlay: true,
        focusInput: true,
        applyPlatformOpacityRules: true,
        onUnblock: null,
        quirksmodeOffsetHack: 4
    };

    update_notes();
});

function load_page(page_url, target_element_id) {
    $("#" + target_element_id).parent().prepend("<h3 id='loadingPageText'>loading</h3>");
    $.ajax({
        url: page_url,
        type: "post",
        success: function(res) {
            $("#" + target_element_id).html(res);
            $('#loadingPageText').remove();
        }
    });
}

function show_forum_comment() {
    if ($("#cannot_comment").size() > 0) {
        var url = document.location.href;
        var mainPath = url.replace(/http:\/\/[^\/]*(?:\/comments)?/im,"").replace(/\/([^\/]*).*/m, "$1");
        show_sign_up(mainPath);
    } else {
        $('#quote_0').show();
        $('#replyButton').hide();
    }
}

function show_add_comment() {
    if($("#cannot_comment").size()>0){
        var url = document.location.href;
        var mainPath = url.replace(/http:\/\/[^\/]*(?:\/comments|\/user\/[^\/]*\/watch)?/im,"").replace(/\/([^\/]*).*/m, "$1");
        show_sign_up(mainPath);
    }else{
        $("#comment_add_panel").slideToggle(300, function() {
            $(".comment_add").hide();
        });
    }
}

function show_add_critique(){
    $('h4#comments_title').html('Write a Critique:');
    $('input[name="comment_type"]').val('video_critique');
    show_add_comment();
}

function general_add_comment(div, is_update,username) {
	
    if($("#cannot_comment").size()>0){
        var url = document.location.href;
        var mainPath = url.replace(/http:\/\/[^\/]*(?:\/comments)?/im,"").replace(/\/([^\/]*).*/m, "$1");
        show_sign_up(mainPath);
    } else{
        $("#quote_0").show();
        var selected = div.split('quote_');
        $('#'+div).html(document.addform);
		
        //$('#comment_form [type=textarea]').attr('class', 'comment_textarea')
        $("#"+div).show('slow', function() {
            var parts = div.split('quote_');
            if(is_update) {
                location.href=location.href+"#comments_section";
                $('#comment_text').val(  htmlspecialchars_decode($('#hidden_'+ parts[1]).val(), 'ENT_QUOTES')  );
                $('#comment_id').val(parts[1]);
                $('#comment_parent_id').val(selected[1]);
            }else{
                location.href=location.href+"#comments_section";
                quotation=username+" wrote: "+htmlspecialchars_decode($('#hidden_'+ parts[1]).val(), 'ENT_QUOTES')+"\n " ;
                $('#comment_text').val(  quotation );
            }
			
            if(div == 'quote_0') {
                $("#comments_page").block({
                    message: ""
                });
            }
			
            $('form#comment_form').ajaxForm({
                beforeSubmit: block_comment,
                success: function(msg) {
                    posts_general_comment(msg);
                }
            });

        });
    }
}

function block_comment() {
    $("#comment_form").block({
        message: '<h3>Posting Comment..</h3>'
    });
    if($("#cannot_comment").size()>0){
        $.jGrowl($("#cannot_comment").val());
    } else {
        if ($.trim($("#comment_text").val()) == "") {
            alert("Please write some comments");
            $("#comment_text")[0].focus();
            $("#comment_form").unblock();
        } else {
            return true;
        }
    }
    return false;
}


function posts_general_comment(res) {
    if (res == "success") {
        $("#comment_form").val("");
        $("#quote_"+$("#comment_parent_id").val()).slideUp(300, function() {
            $(this).hide();
            $("#comments_page").block({
                message: '<h3>Successfully posted your comment</h3>'
            });
            document.location = document.location;
        /*setTimeout(function() {
				$("#comments_page").unblock();
				$("#comment_form").unblock();
				$("#comment_form")[0].reset();
				try {
					$("#comments_page").load($("#paging_url").val(), {
						type: "post"
					});
				} catch(e) {}
			}, 1000);*/
        });
    }else{
        cancel_post_comment();
        $("#comment_form").unblock();
        $.jGrowl(res);
    }
}

function cancel_general_post() {
    $("#quote_0").hide();
    $("#replyButton").show();
}

function delete_general_post(id) {
    if(confirm('Are you sure to delete this?')) {
        $("#comments_page").block({
            message: '<h3>Removing Comment..</h3>'
        });
        $.post("/forum/general/delete/" + id, "", function(res) {
			
            if (res.response=="success"){
                document.location = document.location;
            }else{
                show_flash_message("Didn't work;")
            }
				
        },"json");
    }
}


function update_general_post(id) {
    if(confirm('Are you sure to delete this?')) {
        $("#comments_page").parent().prepend("<h3>Removing Comment..</h3>");
		
        $.post("/forum/general/update/" + id, "", function(res) {
            if (res.response=="success"){
                location.href=location.href;
            }else{
                $("#comments_widget h3").hide();
                $.jGrowl('An error occur when deleting', {
                    sticky:true,
                    header: 'Comment Delete'
                });
            }
        },"json");
    }
}


function cancel_post_comment() {
    $("#comment_add_panel").slideUp(300, function() {
        $('[id^=quote_]').html('');
        $(this).hide();
        $("#comments_page").unblock();
        $(".comment_add").show();
        $("#comments_title").html('');
        $('input[name="comment_type"]').val('video');
    })
}

function updateCounter() {
    $.post('/comments/updateVideoCommentsCounter', {
        url_code: $('#comment_url').val()
    }, function(data) {
        $('#commentsCount').html(data + " Comments");
    });
}

function post_comment() {
    if($("#cannot_comment").size()>0){
        $.jGrowl($("#cannot_comment").val());
    }else{
        if ($.trim($("#comment_text").val()) == "") {
            $.jGrowl("Please write some comments");
            $("#comment_text")[0].focus();
        } else {
            $.ajax({
                url: "/comments/post",
                type: "post",
                data: $("#comment_form").serialize() + '&ajax=1',
                success: function(res) {
                    if (res == "success") {
                        /*This is for video critiques functionality*/
                        if($('#comment_form input[name="comment_type"]').val() == "video_critique") {
                            location.reload(true);
                            return;
                        } else if($('#comment_form input[name="comment_type"]').val() == "marketplace") {
                            $("#comment_text").val("");
                            $("#comment_form").unblock();

                            $("#comments_page").load($("#paging_url").val(), {
                                type: "post"
                            });
                        } else if(/^\/groups\/view\/.*$/im.test(location.pathname)) {
                            $("#add_new_comment").slideToggle();
                            $("#new_comment").slideToggle();
                            $("#comment_form").unblock();
                            $("textarea[name=comment_text]").val('');
                            getComments(1);
                        } else {
                            updateCounter();
                            $("#comment_form").val("");
                            $("#comment_add_panel").slideUp(300, function() {
                                $(this).hide();
                                $("#comments_page").block({
                                    message: '<h3>Successfully posted your comment</h3>'
                                });
                                setTimeout(function() {
                                    $("#comments_page").unblock();
                                    $("#comment_form").unblock();
                                    $("#comment_form")[0].reset();
                                    try {
                                        $("#comments_page").load($("#paging_url").val(), {
                                            type: "post"
                                        });
                                    } catch(e) {}
                                }, 1000);
                            })
                        }
                    } else {
                        cancel_post_comment();
                        $("#comment_form").unblock();
                        $.jGrowl(res);
                    }
                },
                beforeSend: function() {
                    $("#comment_form").block({
                        message: '<h3>Posting Comment..</h3>'
                    });
                }
            });
        }
        $(".comment_add").show();
    }
}
/*
* mainPath added to set the Sign Up Pop-Up's text.
*
* Still being used with two parameters with old functionality
*
* Fix by: Federico Piagentini
*/
function thumbs_up_down(rating, comment_id, mainPath) {
    if($("#cannot_comment").size()>0){
        var url = document.location.href;
        
        if (typeof mainPath == 'undefined'){
          mainPath = url.replace(/http:\/\/[^\/]*(?:\/comments)?/im,"").replace(/\/([^\/]*).*/m, "$1");
        }
        show_sign_up(mainPath);
    }else{
        comment_id = comment_id;
        $.ajax({
            url: "/comments/rate",
            type: "post",
            data: "rating=" + rating + "&comment_id=" + escape(comment_id),
            success: function(e) {
                if (e == "already_rated") {
                    $.jGrowl("Sorry, you cannot rate a comment more than once");
                } else {
                    update_up_downs(comment_id);
                }
            }
        });
    }
}
function update_up_downs(comment_id) {
    comment_id = comment_id;
    $.ajax({
        url: "/comments/updowns",
        type: "post",
        data: "comment_id=" + escape(comment_id),
        success: function(e) {
            $("#c" + comment_id + "l").fadeOut(300, function() {
                $(this).fadeIn(200).html(e)
            });
        }
    });
}
/******** START Notes related functions ***********/
function show_add_note() {
    if ($("#notes_add_panel").is(":visible")) {
        post_note();
    } else {
        $("#notes_add_panel").slideDown(300, function() {
            $(".cancel_note").show();
        });
    }
}
function post_note() {
    if ($.trim($("#note_text").val()) == "") {
        $.jGrowl("Please Write Some Notes!");
        $("#note_text")[0].focus();
    } else {
        $.ajax({
            type: "post",
            url: "/courses/notes/add",
            data: $("#note_form").serialize(),
            success: function(e) {
                if (e == "1") {
                    $.jGrowl("Successfully Added your note");
                    cancel_add_note();
                    update_notes();
                }
            }
        });
    }
}
function update_notes() {
    $.ajax({
        type: "post",
        url: "/courses/notes/get",
        data: $("#note_form").serialize(),
        success: function(e) {
            $("#notes_container").html(e);
        }
    });
}
function cancel_add_note() {
    $(".cancel_note").hide();
    $("#note_form")[0].reset();
    $("#notes_add_panel").slideUp(200);
}
function imposeMaxLength(Object, MaxLen) {
    return (Object.value.length <= MaxLen);
}

function show_actions(obj) {
    $(obj).find(".note_actions").css("display", "block");
}

function hide_actions(obj) {
    $(obj).find(".note_actions").css("display", "none");
}
function edit_note(obj, note_id) {
    obj = obj;
    $("#notes_container").find(".notes_note:hidden").show();
    $("#note_editor").remove();
    // Only one instance of editor
    note_text = $(obj).parents(".notes_note").find(".p_text").text();
    $(obj).parents(".notes_note").hide().after('<div id="note_editor"><textarea ' + ' rows="4" style="border:1px solid #CCC; width:290px; margin:5px 0 10px;" id="note_change">' + note_text + '</textarea><br>' + '<a href="javascript:;" onclick="save_note(\'' + note_id + '\');"> ' + '<img align="absbottom" src="' + site_url + 'images/save_button.gif" border="0"></a>&nbsp; ' + '<a href="javascript:;" onclick="cancel_edit_note(this);"><img align="absbottom" ' + ' src="' + site_url + 'images/post_cancel_button.gif" border="0"></a></div>' + '');

}
function delete_note(obj, note_id) {
    if(confirm("Are you sure to delete this note ?")){
        $.ajax({
            type: "post",
            url: "/courses/notes/delete",
            data: "note_id=" + note_id,
            success: function(e) {
                if (e == "error") {
                    $.jGrowl("Error Occurred while deleting your note. Pleas try again later");
                } else {
                    $.jGrowl("Your note has been deleted");
                    $(obj).parents(".notes_note").fadeOut(200);
                }
            }
        });
    }
}

function save_note(note_id) {
    if ($.trim($("#note_change").val()) == "") {
        $.jGrowl("Please Write Some Notes!");
        $("#note_change")[0].focus();
    }else{
        $.ajax({
            type: "post",
            url: "/courses/notes/save",
            data: "note_text=" + $("#note_change").val() + "&note_id=" + note_id + "&video_id=" + $("#video_id").val(),
            success: function(e) {
                if (e == "error") {
                    $.jGrowl("Error Occurred while saving your note. Pleas try again later");
                } else {
                    $.jGrowl("Successfully Edited your note");
                    $("#notes_container").html(e);
                }
            }
        });
    }
}

function cancel_edit_note(obj) {
    $("#note_editor").prev().show();
    $("#note_editor").remove();
}

/******** END Notes related functions ***********/

/******** START Topic related functions ***********/

function show_topic_edit_form(topic_url,obj){
    $this=$(obj);
    $.ajax({
        type : "post",
        url : topic_url,
        data : null,
        success :  function(e){
            $(".topic:hidden").show();
            $("#discussion_form_container").remove();
            $this.parent().before(e);
            $this.parent().hide();
        }
    });
}
function save_topic(){
    if($.trim($("#subject").val())==""){
        alert("Please put the subject of the topic");
        $("#subject")[0].focus();
        return false;
    }else if($.trim($("#topic_desc").val())==""){
        alert("Please put the description");
        $("#topic_desc")[0].focus();
        return false;
    }
    $.ajax({
        type : "post",
        url : $("#topic_edit_form").attr("action"),
        data : $("#topic_edit_form").serialize(),
        dataType : "json",
        success : function (e){
            if(e.status=="success"){
                $(".topic:hidden").find(".topic_title").html(e.html);
                $(".topic:hidden").show();
                $("#discussion_form_container").remove();
                $.jGrowl("Successfully Saved");
            }else{
                $.jGrowl("Nothing was changed");
            }
        }
    });
    return false;
}
function cancel_edit_topic(obj){
    $this=$(obj);
    $(".topic:hidden").show();
    $("#discussion_form_container").fadeOut(200,function(){
        $(this).remove();
    });
}

 
function delete_comment(comment_id) {
    $.ajax({
        url: "/comments/delete/"+comment_id,
        type: "get",
        success: function(res) {
            $("#comment_form").unblock();
            if (res == "success") {
                if(/^\/groups\/view\/.*$/im.test(location.pathname)) {
                    $("#comment_form").unblock();
                    getComments(1);
                } else {
                    $("#comments_page").block({
                        message: '<h3>Comment Removed Successfully.</h3>'
                    });
                    setTimeout(function() {
                        $("#comments_page").unblock();
                        try {
                            $("#comments_page").load($("#paging_url").val(), {
                                type: "post"
                            });
                        } catch(e) {}
                    }, 1000);
                }
            }else{
                $("#comments_page").block({
                    message: '<h3>Cannot Removed Comment.</h3>'
                });
                setTimeout(function() {
                    $("#comments_page").unblock();
                    try {
                        $("#comments_page").load($("#paging_url").val(), {
                            type: "post"
                        });
                    } catch(e) {}
                }, 1000);
            }
        },
        beforeSend: function() {
            $("#comment_form").block({
                message: '<h3>Deleting Comment..</h3>'
            });
        }
    });
}
 
 
 /******** END Topic related functions ***********/ 
