$(document).ready(function(){
  
  // Binds the comment form
  function bindCommentForm(){
    $('#comment').innerLabel('Post a comment.');

    // Handle submission of comment
    $('#submit-comment').submit(function(){
      var comment = $.trim($('#comment').val());
      var errors = new Array();
      // Begin comment validation
      if(comment == "") {
        errors.push('Please enter a comment');
      }
      errors = contentCheck(comment, errors);
      
      
      if(errors.length > 0) {
        $('.message-container').show();
        $().fyiMessage('init', {
          type: 'error',
          errors: errors,
          attach: $('.message-container')
        });
      } else {
        $.ajax({
          url: '/professional/FYIndOutToolbar.php',
          type: 'post',
          data: {
            rid: $('#rid').val(),
            comment: comment          
          },
          dataType: 'json',
          success:  function(json) {
            function displayComment(markup) {
              $('.comment-count-span').animate({
                opacity: 0
              }, function(){
                var count = parseInt($(this).text());
                count++;
                $(this).text(count).animate({
                  opacity: 1
                }, function(){
                  if(jQuery.browser.msie)$(this).get(0).style.removeAttribute('filter');
                });
              });
              $('#comment').val("");
              if($('#comment-list').children().length > 2) {
                $('#comment-list').children('li:last').slideUp('normal', function(){
                  $(this).remove();
                });
              }
              $('#comment-list').prepend(markup).children('li:first').andSelf().slideDown('normal',function(){
                $('#comment-box > .corner').each(function(){
                  $(this).css('display', 'inline');
                  $(this).css('display', 'block');
                });
              });
            }        
            
            if(json.loggedIn) {
              if ($('#no-comments').length > 0) {
                $('#no-comments').slideUp('normal', function() {
                  $(this).replaceWith('<ul class="hidden" id="comment-list"><\/ul>');
                  displayComment(json.markup);
                });
              } else {
                displayComment(json.markup);
              }
            } else {
              showLogin();
            }
          }
        });
      }
      return false;
    });
  }
  
  // Helpful vote 'yes'
  $('#yes:not(".voted")').click(function(){
    var selector = $(this);
    $.ajax({
      url: '/professional/ajax/collateral-vote.php',
      type: 'post',
      data: {
        Type: 'research',
        Answer: 'yes',
        Id: $(this).attr('rid')
      },
      success: function(response) {
        if (response == 'false') {
          showLogin();
        } else {
          $('#no').animate({opacity: 0}, function(){
            $(this).animate({width: 0}, function(){
              $('#count').animate({
                opacity: 0
              }, function() {
                var count = parseInt($(this).text());              
                count++;
                $(this).text(count).animate({
                  opacity: 1
                },function(){
                  if(jQuery.browser.msie)$(this).get(0).style.removeAttribute('filter');
                });
              });
              $(this).remove();
              selector.addClass('voted').unbind('click');
            });
          });
        }
      }
    });
  });

  // Helpful vote 'no'
  $('#no:not(".voted")').click(function(){
    var selector = $(this);
    $.ajax({
      url: '/professional/ajax/collateral-vote.php',
      type: 'post',
      data: {
        Type: 'research',
        Answer: 'no',
        Id: $(this).attr('rid')
      },
      success: function(response) {
        if (response == 'false') {
          showLogin();
        } else {
          $('#yes').animate({opacity: 0}, function(){
            $(this).animate({width: 0}, function(){
              $(this).remove();
              selector.addClass('voted').unbind('click');
            });
          });
        }
      }
    });
  });

  if(jQuery.browser.msie) {
    $('#close').live('mouseover', function(){
      $(this).css('background', 'url(/Images/theme/solutions/remove.png) no-repeat right center');
    }).live('mouseout',function(){
      $(this).css('background', 'url(/Images/delete-remove.png) no-repeat right center');
    });
  }

    
  $('#show-comments').click(function(){
  
    $('.login-container').slideUp();  
    $().fyiMessage('removeAll');

    if($('.comments').is(':visible')) {
      $('.comments, .message-container').slideUp();
    } else {
      $('.comments').slideDown();
    }
  });
  
  
  
  // Login window labels
  $('#UserId').innerLabel('Username');
  $('#Password').innerLabel('Password');

  function showLogin() {
    $('.comments, .message-container').slideUp();
    if ($('.login-container').is(':visible')) {
      $('.login-container').slideUp();
    } else {
      $('.login-container').slideDown();
    }
  }

  // Show and hide login window
  $('.login-link').click(showLogin);

  $('#loginform').submit(function(){
    $.ajax({
      url: '/professional/Login.php',
      type: 'post',
      data: {
        ajaxUsername: $('#UserId').val(),
        ajaxPassword: $('#Password').val(),
        remember: $('#remember_me').is(':checked')
      },
      dataType: 'json',
      success: function(json) {
        if(json.authenticated) {

          $('#comment-form').html('<form id="submit-comment"><textarea id="comment"><\/textarea><div class="buttons"><input type="hidden" id="rid" value="' + json.id + '" \/><input type="image" src="\/Images\/green-post.png" \/><\/div><\/form>');
          bindCommentForm();
          $('.login-container').slideUp('normal', function(){
            $('#login-li').fadeOut('normal', function(){
              $(this).html(json.display);
              $('#login-li').fadeIn('normal', function(){
                if(jQuery.browser.msie)$(this).get(0).style.removeAttribute('filter');            
              });
            });          
          });
        } else {
          $('.login-container').animate({
            "right": "+=10px"
          }, 'fast', function(){
            $(this).animate({
              "right": "-=20px"
            }, 'fast', function(){            
              $(this).animate({
                "right": "+=20px"
              }, 'fast', function(){            
                $(this).animate({
                  "right": "-=10px"
                }, 'fast', function(){            
                  $().fyiMessage({
                    type: 'warning',
                    text: 'Invalid username / password combination',
                    attach: $('#loginbox')
                  });
                })            
              })            
            })
          })
          
        }
      }
    });
    return false;
  });
  bindCommentForm();
  
  // Handles ajax add to folder links  
  $('#add-to-folder').click(function(){
    var link = $(this);
    link.fyiAddToResearchFolder('init', {
      id: link.attr('rel'),
      loginFunction: showLogin
    });
   });
});
