$(document).ready(function(){

    var serverpath = "http://www.phuckthis.net/";

    // Automatically set token to ajax calls
    $.ajaxSetup({data:{authenticity_token : AUTH_TOKEN}});

    $("#dlgPremiumNotice").dialog({
        autoOpen:false,
        buttons: { "Ok": function() { $(this).dialog("close"); } },
        closeOnEscape: true,
        modal: true,
        width: 460
    });


    $("#dlgWrongPassword").dialog({
        autoOpen:false,
        buttons: { "Ok": function() { $(this).dialog("close"); } },
        closeOnEscape: true,
        modal: true,
        width: 380
    });


    // Handle the new post link click event
    $("a#postnew").click(function(e){
       e.preventDefault();
       var postBody = $("textarea#ventpost").val();
       if (jQuery.trim(postBody) != ""){
         $.post(serverpath + "post/newpost" , {postbody : postBody} , function(resp){
            var newpost_guid = resp.post.guid;
            // Call page to render new post stub for inclusion into page
            $.post(serverpath + "post/new_post_stub" , {guid : newpost_guid} , function(generated_post_stub){
               $("ul#postlisting").prepend(generated_post_stub);
               $("ul#postlisting > li:first").slideDown("slow");
               $("textarea#ventpost").val("");
            } , "html");

            // Get the latest stats for the status box
            $.getJSON(serverpath + "useraccount/get_post_stats_for_user" , function(msg_stats){
                // Change last posted date
                $("span#spn_last_posted_date").html(msg_stats.last_msg_date);
                $("span#spn_user_post_count").html(msg_stats.msg_count);
            });

         } , "json");
       }
    }); // Close postnew handling


    // Handle the new comment post link event
    $("a.addcommentlnk").live("click" , function(e){
        e.preventDefault();        
        // Get the guid of the post
        var postguid = $(this).attr("id");
        postguid = postguid.substring(6);
        
        // Inject a new text area at the end of the comment listing for the particular post
        $.get(serverpath + "comment/input_comment_stub" , {id : postguid} , function(input_area_stub){
            $("ul#comlist" + postguid).append(input_area_stub);

            // Hide the add comment link for this particular post
            $("#addcom" + postguid).fadeOut('normal');

        } , "html");
    });


    // Handle the add comment button
    $(".btnaddcomment").live("click" , function(){
        // Find out the ID of the segment through the button that was clicked
        var guid = $(this).attr("id");
        guid = guid.substring(9);

        var commentbodyentered = $("#newcommentinput-" + guid).val();

        // Add the comment to the segment
        if (commentbodyentered != ""){
            $.post(serverpath + "comment/add_comment_to_post" , {id : guid , commentbody : commentbodyentered} , function(resp){
                // Add the comment to the list
                // Ask the comment to render a comment stub for us
                $.get(serverpath + "comment/new_comment_stub" , {id : resp.comment.guid} , function(new_stub){
                    // Remove the text area at the last
                    $("ul#comlist" + guid + " li:last").remove();
                    // Add the new stub in
                    $("ul#comlist" + guid).append(new_stub);

                } , "html");

                // Get and update the newest number of comments posted
                $.get(serverpath + "useraccount/get_comment_stats_for_user" , function(comment_count){                    
                    $('span#spn_user_comment_count').html(comment_count);
                });

                // Check if the comment was posted by a member
                $.get(serverpath + "comment/comment_poster_check" , {guid : resp.comment.guid } , function(comment_poster_resp){
                   if (comment_poster_resp == "1"){ // Member posted .. remove the countdown
                     // Remove the count down timer
                     $("div#cntdnt" + guid).remove();
                   }
                });

                // Show the add comment link again
                $("#addcom" + guid).fadeIn('normal');

               // $("ul#comlist" + guid).append(resp.comment.guid);
               
            } , "json");
        }
    });


    // Handle the cancel comment button
    $(".btncancelcomment").live("click" , function(){
        // Find out the ID of the segment through the button that was clicked
        var guid = $(this).attr("id");
        guid = guid.substring(12);

        // Hide the comment box
        $("ul#comlist" + guid + " li:last").remove();

        // Show the add comment link again
        $("#addcom" + guid).fadeIn('normal');

        
    });


    // Handle the logout link click
    $("#logout").live("click" , function(e){
       e.preventDefault();

       // Call the useraccount controller to remove the session
       $.get(serverpath + "useraccount/logout" , function(resp){

        if (resp == "OK"){
            // Render the logout stub
            $.get(serverpath + "useraccount/logout_stub" , function(logout_stub){
                $("div#loginpanel").html(logout_stub);
            } , "html");
        } // Close if

       } , "text");
    });

    // Handle the login button
    $("input#loginbutton").live("click", function(){
        // Get the login name and password
        var login_username = $("input#username").val();
        var login_password = $("input#password").val();

        // Authenticate with service
        $.post(serverpath + "useraccount/authuser" , {username : login_username , password : login_password} , function(resp){
            if (resp == "OK"){
               
                // Grab the user login stub to be displayed on the right side
                $.get(serverpath + "useraccount/login_stats_stub" , function(new_login_stub){
                    $("div#loginpanel").html(new_login_stub);
                } , "html");

            } // Close response = OK
            else{
                $("#dlgWrongPassword").dialog('open');
            }

        } , "text");
    });


    // Handle the add votes link
    $(".addagreevote").live("click" , function(e){
        e.preventDefault();

        // Parse the ID of the post
        var linkguid = $(this).attr("id");        
        guid = linkguid.substring(4);

        

        // Call the web service to increment the votes
        $.get(serverpath + "Post/add_agree_vote" , {guid : guid} , function(resp){
       
            if (resp != null){
            
                // Check resp 
                if (resp != "NOTAUTH"){

                    // Check to make sure the vote is not already submitted before
                    if (resp != "VOTED"){
                        // Refresh the count value of the agree votes of the post
                        var agreevoteslabel = "avotecnt" + guid;

                       // $("#avotecnt6d631c28-85c1-11de-8e6f-002332de4710").val()
                        $("#" + agreevoteslabel).html(resp);

                        // Change the image to a disabled image
                        $("#agreepostimg" + guid).attr("src" , "/images/thumbsup-disabled.png");

                         // Remove the add agree link from the DOM
                         $("#" + linkguid).attr('disabled' , true);
                         $("#" + linkguid).click(function(e) { e.preventDefault(); return false; });

                         // Remove the count down timer
                         $("div#cntdnt" + guid).remove();
                    }

                }
                else{  // User is not logged in or registered
                    $('#dlgPremiumNotice').dialog('open');
                }
            }

        });

    });



    // Bind the countdown timer for each of the post that has the countdown div
   // var newYear = new Date();
   // newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1);
   // $('div.entrycountdown').countdown({until: newYear});
   $('div.entrycountdown').each(function(i) {

      var expiredDateString = $(this).attr('expiredate');
      var expiredDate = Date.parse(expiredDateString);

      $(this).countdown({until:expiredDate , timezone: +8 , layout:'{dn} {dl}, {hn} {hl}, {mn} {ml}, {sn} {sl} till removal'});

   });



}); // Close jQuery javascript block
