﻿//variaveis globais
var isReady = false;

var Comment = {
    Save: function() {
        
        $("#frmComment").validate({
            rules: {
                loginNome: { required: true },
                loginEmail: { required: true, email: true },
                commentText: { required: true }
            },
            messages: {
                loginNome: "Digite seu nome",
                loginEmail: "Digite seu email",
                commentText: "Digite seu comentário"
            },
            submitHandler: function() { 
                if(isReady) return false; //verifica o estado do comentário
                
                $.post("/Comment/Save",
                {
                    themeId: $("input[name$='themeId']").val(),
                    commentText: $("textarea[name$='commentText']").val(),
                    name: $("input[name$='loginNome']").val(),
                    email: $("input[name$='loginEmail']").val(),
                    content: $("#content").html()
                },
                function(result)
                {
                    if(result == "Ok")
                    {
                        alert( "Comentário enviado com sucesso.");
                        $("textarea[name$='commentText']").val("");
                        $("input[name$='loginNome']").val("");
                        $("input[name$='loginEmail']").val("");
                        $("#content").html("");
                        $("#content").hide();
                        Comment.OrderBy($("input[name$='themeId']").val(), "Id");

                        $('#holder').jScrollPaneRemove();
                        $("#holder").jScrollPane();

                    }
                    else {
                        alert( result );
                    }
                        
                });
            }
        });        
    },
    ValidVote: function(commentId, option)
    {
        $.post("/Comment/VoteIsValid",
        {
            commentId: commentId,
            optionVote: option
        },
        function(result)
        {
            if(result == "agree" || result == "disagree")  {
                alert((result == "agree") ? "Você já concordou com este comentário. " : "Você já discordou com este comentário.");
                return;
            }
            //var confirmMsg = (option == "agree") ? confirm("Deseja concordar?") : confirm("Deseja discordar?");
            //if(confirmMsg) {    

            //}
            Comment.Vote(commentId, option);
        });
    
    },
    Vote: function(commentId, option)
    {
        $.post("/Comment/Vote",
        {
            commentId: commentId,
            optionVote: option
        },
        function(result)
        {
            if(option == "agree") $("span#agree_" + commentId).html(result);
            else if(option == "disagree") $("span#disagree_" + commentId).html(result);
        });
    },
    OrderBy: function(id, orderBy)
    {
        $.get("/Comment/ListParent", 
        { 
            themeId: id,
            page: 1,
            orderBy: orderBy
        }, 
        function(result) {
             $("#comentarios").html(result);   
             $('#holder').jScrollPane();
        });
    },
    showRespostas: function(id, page) {
    
	    var refDiv = $("#resposta_"+id)[0];
        if ( typeof refDiv.showResposta === 'undefined' ) refDiv.showResposta = "off";
        
        if (refDiv.showResposta === "off") { 
            refDiv.showResposta = "on";
            
            $("#resposta_"+id).show();
            $('#holder')[0].scrollTo('#resposta_' + id);
        } else {
            refDiv.showResposta = "off";
            $("#resposta_"+id).hide();
        }
    
    },
    showBox: function(id)
    {
	    var refDiv = $("#response-"+id)[0];
        if ( typeof refDiv.showForm === 'undefined' ) refDiv.showForm = "off";
        
        if (refDiv.showForm === "off") { 
            refDiv.showForm = "on";
            
            var htmlTextarea = '<div class="right_c">';
		    htmlTextarea += '<label for="loginNome" class="comentarioForm">Nome:</label><input type="text" class="required" name="responseNome_' + id + '" id="responseNome_' + id + '" />';
		    htmlTextarea += '<label for="loginEmail" class="comentarioForm">E-mail:</label><input type="text" class="required email" name="responseEmail_' + id + '" id="responseEmail_' + id + '" />';
		    htmlTextarea += '<br clear="all" /></div>';
		    htmlTextarea += '<textarea style="width: 467px;" class="required" id="responseText_' + id + '" name="responseText_' + id + '" rows="3"></textarea>';
		    htmlTextarea += '<br /><a href="javascript:;" onclick="Comment.Response(\'' + id + '\');"><img height="23" width="110" src="/Content/images/btn-responder.gif" alt="Responder"></a>';
		    htmlTextarea += '&nbsp;&nbsp;&nbsp;<label id="erro_form_' + id + '" style="display:none" class="error">Todos os campos são obrigatórios</label><br/><br/><br/>';
		    $("#response-" + id).html(htmlTextarea);
		    $('#holder').jScrollPaneRemove();
		    $('#holder').jScrollPane();
		    $("#responseText_" + id).charCounter(900, {
			    format: "<br/>%1 caracteres restantes"
		    });
            
            $("#response-"+id).show();
            $('#responseNome_' + id).focus();
            $('#holder')[0].scrollTo('#response-' + id);
        } else {
            refDiv.showForm = "off";
            $("#response-"+id).hide();
        }

    },
    Response: function(commentId)
    {
    
        if ( $("textarea[name$='responseText_" + commentId + "']").val() === ""
            || $("input[name$='responseNome_" + commentId + "']").val() === ""
            || $("input[name$='responseEmail_" + commentId + "']").val() === "" ) {
            
            $("#erro_form_" + commentId).show();
            return false;
        }
        $("#erro_form_" + commentId).hide();
    
        $.post("/Comment/ResponseComment", {
            themeId: $("input[name$='themeId']").val(),
            commentId: commentId,
            responseText: $("textarea[name$='responseText_" + commentId + "']").val(),
            name: $("input[name$='responseNome_" + commentId + "']").val(),
            email: $("input[name$='responseEmail_" + commentId + "']").val()
        },
        function(result) {

            var oldHtml = $("#resposta_" + commentId).html();
            var newHtml = '<div class="resposta"><p>' + $("input[name$='responseNome_" + commentId + "']").val() + '</p><p>'+ $("textarea[name$='responseText_" + commentId + "']").val() + '</p></div>';
            newHtml += oldHtml;
            $("#resposta_" + commentId).html(newHtml);
            $("#resposta_" + commentId).show();
            
            $("#response-" + commentId).html("");
            $("#response-" + commentId).hide();
        });
    },
    AddImage: function()
    {
     	    if(isReady) return false;  //verifica o estado do comentario
     	    
     	    
     	    var urlMatch = /^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\/\\\+&amp;%\$#_]*)?$/;
     	    if(urlMatch.test($("input[name$='photoUrl']").val()))
     	    {
 	               isReady =  true;
 	                $("#content").html("<div><img src='/Content/Images/ajax-loader.gif' /><br /> Carregando...</div>");
                    $("#content").show();
     	            $.post("/Comment/AddImage", {
                        url: $("input[name$='photoUrl']").val()
                    },
                    function(result) {
 	                    if(urlMatch.test(result)) { 
 	                            $("#video").hide();
 	                            Navigation.Show("#photo");
 	                            $("#content").html("<img  onclick=\"window.open('" + $("input[name$='photoUrl']").val() + "');\" src='" + result + "' />");
 	                            $("input[name$='photoUrl']").val("");
                        } else {
                            $("#content").hide();
                            alert(result);
                        }
                        isReady = false;
                    });
     	    } else {
     	        alert("Insira uma url válida!");
     	    }
    },
    AddVideo: function()
    {
          if(isReady) return false;
          var urlMatch = /^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\=\?\,\/\\\+&amp;%\$#_]*)?$/;
          if(urlMatch.test($("input[name$='videoUrl']").val()))
          {
                 $("#content").html("<div><img src='/Content/Images/ajax-loader.gif' /><br /> Carregando...</div>");
                 $("#content").show();
                 isReady = true;
                  $.post("/Comment/AddVideo", {
                        url: $("input[name$='videoUrl']").val()
                    },
                    function(result) {
 	                    if(result.indexOf("{") != -1) { 
 	                            var video = eval('(' + result + ')');
 	                            $("#content").html("<div style=\"background:url("+ video.thumbnail +") no-repeat; width: 120px; height: 110px; text-align: center; cursor:pointer;\" onclick=\"Content.showVideo('" + video.link + "', this);\"><div class=\"btVideo\" /></div></div>");
 	                            $("#content").show();
 	                            $("#video").hide();
 	                            $("input[name$='videoUrl']").val("");
                         } else {
                            $("#content").hide();
                            alert(result);
                        }
                        isReady = false;
                    });
          } else {
            alert("Insira uma url válida!");
          }
    }
};


var Content = {
    showDescription: function(element)
    {
        $("img").tooltip();
    },
    showVideo: function(url, element)
    {
        var div = $(element).parent();
		div.css('height','344px');
        div.html("<object width=\"425\" height=\"344\"><param name=\"movie\" value=\"" + url + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"" + url + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"425\" height=\"344\"></embed></object>");
    }
};


var Pool = {
    Vote: function()
    {
        var poolOptionId;
        var rdEnquete = $("input[name$='rdEnquete']");
        for(var i = 0; i < rdEnquete.length; i++)
            if(rdEnquete[i].checked) poolOptionId = rdEnquete[i].value;
        $.post("/Pool/Vote", { poolOptionId: poolOptionId }, function(result) {
            alert(result);
        });
    }
};

var Theme = {
    Suggest:function()
    {
    	jQuery.validator.messages.required = "";

        $("#formSuggest").validate({
            rules: { 
                themeSuggest: { required: true },
                name: { required: true},
                email: {required: true, email: true}
            },
            invalidHandler: function(e, validator) {
				    var message = "* Todos os campos são obrigatórios.";
				    $("#boxTemaError").html(message);
				    $("#boxTemaError").show();
		    },
            errorPlacement: function(error, element) { 
                $("#boxTemaError").show()   ;
            }, 
            submitHandler: function() { 
                $.post("/Theme/Suggest", {
                    themeSuggest: $("input[name$='themeSuggest']").val(),
                    name: $("input[name$='name']").val(),
                    email: $("input[name$='email']").val()
                },
                function(result) {
                    if(result == "Ok") {
                        $("#boxTemaError").hide();
                        $("input[name$='themeSuggest']").val("");
                        $("input[name$='name']").val("");
                        $("input[name$='email']").val("");
                        alert("Seu tema foi enviado com sucesso!");
                    }
                    else $("div#login").html(result);
                });
            }
        });
    },
    Change: function(id)
    {
        if(id != 0)
            window.location.href = "/Assunto/" + id;
    }
};



var Navigation = {
    Ajax: function(divDestination, controller, action, param) {
      if (action == "" || action == undefined || action == 'undefined' || action == null) action = "index";
      $.get("/" + controller + "/" + action, param,
      function(result)
      {
            $(divDestination).html(result);
            $("#holder").each(function()
            {
                $("#holder").jScrollPaneRemove();
                $("#holder").jScrollPane();
                $('#holder')[0].scrollTo(divDestination);
            });
      });
    },
    OpenMultimidia: function(mypage,myname,w,h,scroll,size)
    {
        var b_versao = parseInt(navigator.appVersion);
        var win = null; 
        if (b_versao >= 4) {
            LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
            TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
        }
        else {
            LeftPosition = 100;
            TopPosition = 100;
        }
        
        var settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable='+size+'';
        var win = window.open(mypage,myname,settings);
        if(win.window.focus){win.window.focus();}
    },
    Show: function(elementId)
    {
            var refDiv = $(elementId)[0];
            if(typeof refDiv.showForm === 'undefined') refDiv.showForm = "off";
            
           if( refDiv.showForm === "off") { 
                refDiv.showForm = "on";
                $(elementId).show();
            } else {
                  refDiv.showForm = "off";
                  $(elementId).hide();            
            }
    }/*,
    Swap: function(elementOpen, elementClose)
    {
             var refDiv = $(elementOpen)[0];
            if(typeof refDiv.showForm === 'undefined') refDiv.showForm = "off";
            
           if( refDiv.showForm === "off") { 
                refDiv.showForm = "on";
                $(elementId).show();
            } else {
                  refDiv.showForm = "off";
                  $(elementId).hide();            
            }
    }*/
 };