
var PROCESS_ADD_COMMENT_REQUEST_MESSAGE;
var SHOW_ACTION;
var HIDE_ACTION;
var HIDDEN_STATUS;
var SHOWN_STATUS;
var EXPAND;
var COLLAPSE;
var CANCEL;
var SUBMIT;

function Expand(action, ctrl){
    if (action){
        ctrl.attr("style", "padding: 5px; height: auto; visibility: visible;");
        ctrl.next().children("img").attr("src", "comments_images/collapse.gif");
        ctrl.next().children("span").html(COLLAPSE);
        ctrl.next().children("span").unbind().bind("click", function(e){ Expand(false, ctrl);});
    }
    else{
        ctrl.attr("style", "padding: 0px; height: 0px; visibility: hidden;");
        ctrl.next().children("img").attr("src", "comments_images/expand.gif");
        ctrl.next().children("span").html(EXPAND);
        ctrl.next().children("span").unbind().bind("click", function(e){ Expand(true, ctrl);});
    }
    $.localScroll(); 
}


function HideCommentPopup(){    
    $("#AddCommentPopupID").css({"display": "none"});    
}


function ShowCommentPopup(reply, rootid, commentid, moduleid, moduletype, authorid){           
    var popup = CreateAddCommentPopup(reply, rootid, commentid, moduleid, moduletype, authorid);    
    if (!reply){
        $("#AddCommentPopupIDMain").remove();               
        $("[popupholder='true']").after(popup);                  
    }
    else{      
        var placeid = "#c_content_" + commentid;        
        $(placeid).children(".commentPost").remove();
        $(placeid).children(":last").after(popup);        
    }
    $('#CommentsBodyID').focus();
    setMaxLength();
    $.localScroll();       
}

function CreateAddCommentPopup(reply, rootid, commentid, moduleid, moduletype, authorid) {  
    var popup = "";
    var txtid = "";
   if (!reply) {
       txtid = "CommentsBodyID";
       popup = "<div class='commentPost' id='AddCommentPopupIDMain'>" + 
             "<div>" + 
                "<textarea mLength='500' rows='4' cols='60' id='CommentsBodyID' /> " +                                                         
              "</div>" +
               "<div style='padding: 5px 0px;' class='MainCommentResultArea'>" + 
                    "<input class='btn_smblu2' type='button' id='MainCommentOKID' value='" + SUBMIT + "' onclick=\"PostCommentToService('" +  moduleid + "','" +  moduletype + "','" +  txtid + "');\"/>" +
                    "<input class='cancel2' id='MainCancelID' type='button' value='" + CANCEL + "' onclick='$(\"#AddCommentPopupIDMain\").remove();'/>" +
                "</div>" +                           
       "</div>";
       }
       else{
        txtid = "CommentsBodyID_" + commentid;
        var placeid = "#c_content" + commentid;                
        popup = "<div class='commentPost' >" + 
             "<div>" + 
                "<textarea mLength='500' rows='4' cols='55' id='" + txtid + "' /> " +                                                         
              "</div>" +
               "<div style='padding: 5px 0px;' id='CommentResult_" + commentid + "' >" + 
                    "<input class='btn_smblu2' type='button' id='CommentOKID' value='" + SUBMIT + "' onclick=\"PostReplyCommentToService('" + rootid + "','" + commentid + "','" +  moduletype +  "','" + txtid + "');\"/>" +
                    "<input class='cancel2' id='CancelID' type='button' value='" + CANCEL + "' onclick='$(this).parent().parent().remove();'/>" +
                "</div>" +                
       "</div>";     
       }
       return popup;
   }       


function centerPopup(){  
 //request data for centering  
 var windowWidth = document.documentElement.clientWidth;  
 var windowHeight = document.documentElement.clientHeight;  
 var popupHeight = $("#AddCommentPopupID").height();  
 var popupWidth = $("#AddCommentPopupID").width();  
 //centering  
$("#AddCommentPopupID").css({  
 "position": "absolute",  
 "top": windowHeight/2-popupHeight/2,  
 "left": windowWidth/2-popupWidth/2   
 }); 
 };  
 
function PostCommentToService( moduleid, moduletype, txtid){    
    var txtID = "#" + txtid;         
    var body = document.getElementById(txtid).value;//jQuery(txtID).text();    
    var url = "/WebServices/Comments/CommentService.asmx/AddComment";
    var data = "Moduleid=" + moduleid + "&Moduletype=" + moduletype + "&Body=" + encodeURIComponent(body);
    //start the animated gif
    $('.MainCommentResultArea').empty().append("<div style='padding: 5px 0px;'><img border='0' align='absmiddle' title='' alt='' src='comments_images/ldr_snake_mgt.gif'/><span style='padding-left: 10px;'>" + PROCESS_ADD_COMMENT_REQUEST_MESSAGE + "</span></div>");
    var arg = {};
    arg.reply = false;
    arg.moduleid = moduleid;
    arg.moduletype = moduletype;    
    arg.txtid = txtid;    
    jQuery(this).ServiceInvoke(url, data, "ADD_COMMENT", $('.MainCommentResultArea'), arg);    
}
 
function PostReplyCommentToService(rootid, commentid, moduletype, txtid){
    var txtID = "#" + txtid;      
    var body = document.getElementById(txtid).value;//jQuery(txtID).text();      
    var url = "/WebServices/Comments/CommentService.asmx/AddReplyComment";
    var data = "Moduletype=" + moduletype + "&Body=" + encodeURIComponent(body) + "&rootid=" + rootid;
    var resultid = "#CommentResult_" + commentid;
    $(resultid).empty().append("<div style='padding: 5px 0px;'><img border='0' align='absmiddle' title='' alt='' src='comments_images/ldr_snake_mgt.gif'/><span style='padding-left: 10px;'>" + PROCESS_ADD_COMMENT_REQUEST_MESSAGE + "</span></div>");
    arg = {};
    arg.reply = true;    
    arg.moduletype= moduletype;    
    arg.txtid = txtid;
    arg.rootid = rootid;
    arg.commentid = commentid;
    jQuery(this).ServiceInvoke(url, data, "ADD_COMMENT", $(resultid), arg);    
}

 
function RateComment(markarea, moduletype, commentid, mark ){    
    var url = "/WebServices/Comments/CommentService.asmx/RateComment";
    var data = "Moduletype=" + moduletype + "&Commentid=" + commentid + "&Mark=" + mark;
    var existmark = $(markarea).html();    
    var total = parseInt(existmark) + parseInt(mark);
    //before start the Ajax reguest, start the animated gif
    var elementshtml = $(markarea).parent(".c_rate").siblings(".c_rate_action").html();
    $(markarea).parent(".c_rate").siblings(".c_rate_action").empty();
    $(markarea).parent(".c_rate").siblings(".c_rate_action").html("<a href='#'><img border='0' align='absmiddle' title='' alt='' src='comments_images/ldr_snake_mgt.gif'/></a>");    
    arg = {};
    arg.total = total;
    arg.elementshtml = elementshtml;
    arg.markarea = markarea;        
    arg.moduletype = moduletype;
    arg.commentid = commentid;
    arg.mark = mark;
    jQuery(this).ServiceInvoke(url, data, "RATE", markarea, arg);    
    $.localScroll(); 
    
}
 
function DeleteComment(moduletype,rootid, commentid, child) {
    var url = "/WebServices/Comments/CommentService.asmx/DeleteComment";
    var data = "Moduletype=" + moduletype + "&Commentid=" + commentid;
    var selector = "";     
    if (child == "0"){       
        selector = ".CommentsContext[rootid='" + rootid + "']";
    }
    else
    {        
       selector = ".CommentsContext[commentid='" + commentid + "']";     
    }
    var areas = $(selector);           
    jQuery(this).ServiceInvoke(url, data, "DELETE", areas);
    $.localScroll(); 
    
}

function ChangeDisplayedStatus(moduletype, ishidden, commentid, elem)
{
    var url = "/WebServices/Comments/CommentService.asmx/ChangeStatus";
    var data = "Moduletype=" + moduletype + "&Commentid=" + commentid + "&Ishidden=" + ishidden;    
    jQuery(this).ServiceInvoke(url, data, "STATUS", elem, ishidden);    
    $.localScroll(); 
    
}

(function($){
    $.fn.ServiceInvoke = function(uri, data, type, container, arg){        
         $.ajax({                        
                        url: uri,
                        data: data,
                        type: "POST",
                        contentType: "application/x-www-form-urlencoded",
                        dataType: "xml",
                                                                   
                    success: function(res){                      
                    var error = null;
                    $(res).find("Error").each(function(){error = $(this).text(); });
                        if (error == 0){
                            //RATE
                            if (type && type=='RATE'){                           
                               if (arg.total == 0){
                                    $(container).html("0");
                                    $(container).attr("class", "gray");
                               }
                               else {                                
                                    $(container).html(arg.total);
                                    if (arg.total > 0)
                                        $(container).attr("class", "green");
                                    else 
                                        $(container).attr("class", "red");
                               }
                                $(container).parent(".c_rate").siblings(".c_rate_action").empty();
                                $(container).parent(".c_rate").siblings(".c_rate_action").html("<a href='#'><img height='16' border='0' align='absmiddle' width='18' title='+1' alt='+1' src='comments_images/ico_vot_yes_inactive.gif'/></a>&nbsp;<a href='#'><img height='16' border='0' align='absmiddle' width='18' title='-1' alt='-1' src='comments_images/ico_vot_no_inactive.gif'/></a>");                            
                            }                        
                            //CHANGE STATUS
                            if (type && type=='STATUS'){                            
                                var authorid = jQuery("#CommentVisitorUserID").attr("value");                                
                                var commentid = container.parents(".CommentsContext").attr("commentid");
                                var moduleid = container.parents(".CommentsContext").attr("moduleid");
                                var mtype = jQuery("#ModuleTypeCommenting").attr("value");
                                //is hidden
                                if(arg){                                
                                     container.html(SHOWN_STATUS);
                                     container.next().html(HIDE_ACTION);                                 
                                     container.next().unbind().bind("click", function(e){ChangeDisplayedStatus(mtype, false,  commentid, container);});
                                     container.attr("class", "green");                                                                  
                                }
                                else{                                
                                    container.html(HIDDEN_STATUS);
                                     container.next().html(SHOW_ACTION);
                                     container.next().unbind().bind("click", function(e){ChangeDisplayedStatus(mtype, true,  commentid, container);});
                                     container.attr("class", "red");                                                                  
                                }
                                UpdateMessageNumber(res);                            
                            }
                            //ADD COMMENT
                            if (type && type=='ADD_COMMENT'){                                                        
                                 $(res).find("WrappedResources").find("Pair").each(function() {
                                      var marker = $(this);                                      
                                      container.empty().append(marker.children('Value').text());                                      
                                  });
                                                                  
                                UpdateMessageNumber(res); 
                                document.getElementById(arg.txtid).disabled = "true";
                                $("#NoCommentsAreaID").attr("style", "display:none");
                            }
                            //DELETE
                            if (type && type=='DELETE'){                        
                                container.empty();
                                UpdateMessageNumber(res);                        
                            }
                        }
                        //ERROR
                        else{
                                //reset the buttons in adding comment
                                if (type && type=='ADD_COMMENT'){ 
                                    if (!arg.reply){
                                        container.empty().append("<input class='btn_smblu2' type='button' id='MainCommentOKID' value='Submit' onclick=\"PostCommentToService('" +  arg.moduleid + "','" +  arg.moduletype + "','" +  arg.txtid + "');\"/>" +
                                                                 "<input class='cancel2' id='MainCancelID' type='button' value='Cancel' onclick='$(\"#AddCommentPopupIDMain\").remove();'/>");
                                    }
                                    else{
                                        container.empty().append("<input class='btn_smblu2' type='button' id='CommentOKID' value='Submit' onclick=\"PostReplyCommentToService('" + arg.rootid + "','" + arg.commentid + "','" +  arg.moduletype + "','" + arg.txtid + "');\"/>" +
                                                                  "<input class='cancel2' id='CancelID' type='button' value='Cancel' onclick='$(this).parent().parent().remove();'/>");
                                    }                                    
                                }
                                //reset the buttons in rating comment
                                if (type && type=='RATE'){
                                    var commentid = arg.commentid;
                                    var markarea = arg.markarea;
                                    var itemshtml = "<a rateenabled=\"1\" href=\"#\" ><img height=\"16\" border=\"0\" align=\"absmiddle\" width=\"18\" src=\"comments_images/ico_vot_yes.gif\" alt=\"+1\" title=\"+1\" /></a> <a rateenabled=\"1\" href=\"#\" ><img height=\"16\" border=\"0\" align=\"absmiddle\" width=\"18\" src=\"comments_images/ico_vot_no.gif\" alt=\"-1\" title=\"-1\" /></a>";                                    
                                    $(arg.markarea).parent(".c_rate").siblings(".c_rate_action").empty().html(itemshtml); 
                                    $(arg.markarea).parent(".c_rate").siblings(".c_rate_action").children(":first").bind("click", function(e){ RateComment(arg.markarea, arg.moduletype, arg.commentid, 1 ); });
                                    $(arg.markarea).parent(".c_rate").siblings(".c_rate_action").children(":last").bind("click", function(e){ RateComment(arg.markarea, arg.moduletype, arg.commentid, -1 ); });
                                    $(arg.markarea).parent(".c_rate").siblings(".c_rate_action").children(":first").bind("mouseover", function(e){ $(this).children("img").attr("src", "comments_images/ico_vot_yes_over.gif"); });
                                    $(arg.markarea).parent(".c_rate").siblings(".c_rate_action").children(":first").bind("mouseout", function(e){ $(this).children("img").attr("src", "comments_images/ico_vot_yes.gif"); });
                                    $(arg.markarea).parent(".c_rate").siblings(".c_rate_action").children(":last").bind("mouseover", function(e){$(this).children("img").attr("src", "comments_images/ico_vot_no_over.gif");}); 
                                    $(arg.markarea).parent(".c_rate").siblings(".c_rate_action").children(":last").bind("mouseout", function(e){$(this).children("img").attr("src", "comments_images/ico_vot_no.gif");}); 
                                }
                                                            
                                $(res).find("WrappedResources").find("Pair").each(function() {
                                      var marker = $(this); 
                                      if (marker.children('Key').text() == "SPAM_MESSAGE"){
                                            //container.parent().remove(); 
                                            $("#InfoPopUp").attr("style", "display:block");                             
                                            LayoutInfoPopUp(marker.children('Value').text());
                                      }  
                                      else{
                                            $("#ErrorPopUp").attr("style", "display:block");
                                            $("#ErrorPopUpMsg").html(marker.children('Value').text()); 
                                            LayoutErrorPopUp();
                                      }                                         
                                  });      
                        }                    
                    },                                                        
                    error:  function(xhr) {                          
                        alert('network error comment');                                     
                        return;
                    }
            });
        }        
    })(jQuery); 

function UpdateMessageNumber(xml){
    $(xml).find("TotalMessages").each(function(){        
        var total = $(this).text();        
        if (total != -1)
            $("span [countholder='true']").html(total);
    });
}

function Comments_Init(){                
        var moduletype = jQuery("#ModuleTypeCommenting").attr("value");
        //authorid is basically visitorid. The one that reads the comments not the one that has written the comment
        var authorid = jQuery("#CommentVisitorUserID").attr("value");
        var addcommentsright = (jQuery("#AddCommentsRightID").attr("value") == 'False')?false:true;         
        if (addcommentsright){
            
            var themoduleid = $("#AddCommentLinkID").attr("startmoduleid");
            $("#AddCommentLinkID").bind("click", function(e){ShowCommentPopup(false, null, null, themoduleid, moduletype, authorid);})                                                           
            jQuery('.CommentsContext').each(function(){
                var rootid = $(this).attr("rootid");
                var commentid = $(this).attr("commentid");
                var moduleid = $(this).attr("moduleid");
                $(this).find(".xReplyComment").bind("click", function(e){ ShowCommentPopup(true, rootid, commentid, moduleid, moduletype, authorid); })
                var rate_action = $(this).find(".c_rate_action");
                var markarea = $(rate_action).siblings(".c_rate").children(":first");  
                if ($(rate_action).children(":first").attr("RateEnabled") == 1 && $(rate_action).children(":last").attr("RateEnabled")){
                    $(rate_action).children(":first").bind("click", function(e){ RateComment(markarea, moduletype, commentid, 1 ); });
                    $(rate_action).children(":last").bind("click", function(e){ RateComment(markarea, moduletype, commentid, -1 ); });
                    $(rate_action).children(":first").bind("mouseover", function(e){ $(rate_action).children("img").attr("src", "comments_images/ico_vot_yes_over.gif"); });
                    $(rate_action).children(":first").bind("mouseout", function(e){ $(rate_action).children("img").attr("src", "comments_images/ico_vot_yes.gif"); });
                    $(rate_action).children(":last").bind("mouseover", function(e){$(rate_action).children("img").attr("src", "comments_images/ico_vot_no_over.gif");}); 
                    $(rate_action).children(":last").bind("mouseout", function(e){$(rate_action).children("img").attr("src", "comments_images/ico_vot_no.gif");}); 
                }
                else{
                    $(rate_action).children(":first").attr("style", "cursor:default");
                    $(rate_action).children(":last").attr("style", "cursor:default");
                }                
                
            });            
        }                  
                               
            jQuery('.xpandClpse').each(function(){
                    var txt = $(this).prev();
                    if ($(this).children("span[expand]").attr("expand") == "true")
                        $(this).children("span[expand]").bind("click", function(e){ Expand(true, txt); });
                    else    
                        $(this).children("span[expand]").bind("click", function(e){ Expand(false, txt); });
                });
        
             jQuery('.CommentsContext').each(function(){
                var rootid = $(this).attr("rootid");
                var commentid = $(this).attr("commentid");
                var moduleid = $(this).attr("moduleid");                
                
                var status = $(this).find(".c_status");
                var lmgreen = $(status).children(".green");
                var lmred = $(status).children(".red");
                $(status).children(".green").next().bind("click", function(e){ ChangeDisplayedStatus(moduletype, false,  commentid, lmgreen); });
                $(status).children(".red").next().bind("click", function(e){ ChangeDisplayedStatus(moduletype, true,  commentid, lmred);});
                
             });
                            
       //delete action
       //if (addcommentsright){
            
             jQuery('.CommentsContext').each(function(){
                var rootid = $(this).attr("rootid");
                var commentid = $(this).attr("commentid");
                var moduleid = $(this).attr("moduleid");
                var ownerid = $(this).attr("authorid");
                if (!ownerid)
                    ownerid = '00000000-0000-0000-0000-000000000000';
                
                var status = $(this).find(".c_status");
                var child =  $(status).children(":last").attr("ischild");                                                 
                if (addcommentsright || (ownerid == authorid)){                    
                    $(status).children(":last").bind("click", function(e){DeleteComment(moduletype, rootid, commentid, child); })
                }
                
             });       
        //}
}

jQuery(document).ready(function() {    
    try{Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Comments_Init);}catch(e){}
        
    Comments_Init();
});

