var sen = {
  // Default settings
  _options: {
    'showPrint': true,
    'showEmail': true,
    'comment_item_type': 'article',
    'comment_limit': 10,
    'comment_offset': 0,
    'first_load': true
  },
  
  // Methods
  initComments: function() {
    $("#CommentForm").hide();
    $("#CommentPostLink").bind("click", function(){
      $("#CommentForm").slideToggle();
      return false;
    });
    
    $("#CommentForm form").bind("submit", function(){
      $("#CommentForm .error").remove();
      var error = false;
      
      if($("#CommentForm textarea").val() == ""){
        $("#CommentForm textarea").before('<div class="clear"></div><p class="error">Your comment cannot be blank.</p>');
        error = true;
      }
      
      if($("#recaptcha_response_field").val() == ""){
        $("#recaptcha_widget_div").before('<div class="clear"></div><p class="error">The text you entered did not match.</p>');
        error = true;
      }
      
      if(error == true){
        return false;
      }
      
      var data = $(this).serialize();
      $(this).slideUp("fast", function(){
        $("#CommentForm .loading").slideDown("fast");
        $.ajax({
          type: "post",
          cache: false,
          url: $(this).attr('action'),
          data: data,
          dataType: 'json',
          complete: function(){
            $("#CommentForm .loading").slideUp("fast", function(){
              $(this).hide();
              $("#CommentForm textarea").val('');
              $("#recaptcha_response_field").val('');
              $("#CommentForm form").slideDown("fast", function(){
                Recaptcha.reload();
              });
            });
          },
          success: function(msg){
            if(msg.success == true){
              $("#comments_list").prepend(sen.createComment(msg));
              // update comments count
              var _count = $("#actions span:first").html().replace(/[\sa-zA-Z]+/, '');
              _count = parseInt(_count) + 1;
              $("#actions span:first").html(_count+' Comments');
            }else{
              $(msg.errors).each(function(i, error){
                switch(error) {
                	case "comment_captcha":
                    $("#recaptcha_widget_div").before('<p class="error">The text you entered did not match.</p>');
                		break;
                	case "comment_content":
                    $("#CommentForm textarea").before('<p class="error">Your comment cannot be blank.</p>');
                		break;
                }
                Recaptcha.reload();
              });
            }
          },
          error: function(){
            $("#CommentForm").prepend('<p class="error">Sorry, your comment could not be posted. Please try again.</p>');
          }
        });
      });
      
      return false;
    });
  },
  
  loadComments: function(id, options) {
    var _settings = $.extend(this._options, options);
    $.ajax({
      type: "get",
      cache: false,
      url: '/comments/'+_settings.comment_item_type+'/'+id+'/'+_settings.comment_offset+'/'+_settings.comment_limit,
      dataType: 'json',
      success: function(msg){
        if(msg.count > 0){
          $(msg.comments).each(function(i, comment){
            $("#comments_list").append(sen.createComment(comment));
          });
        }else{
          if (_settings.first_load) {
            $("#comments_list").html('Be the first to comment!');
          }
        }
      }
    });
  },
  
  
  initWallPost: function() {
    
    $("#WallForm form").bind("submit", function(){
      $("#WallForm .error").remove();
      var error = false;
      
      if($("#WallForm textarea").val() == ""){
        $("#WallForm textarea").before('<div class="clear"></div><p class="error">Your comment cannot be blank.</p>');
        error = true;
      }
      
           
      if(error == true){
        return false;
      }
      
      var data = $(this).serialize();
      $(this).slideUp("fast", function(){
        $("#WallForm .loading").slideDown("fast");
        $.ajax({
          type: "post",
          cache: false,
          url: $(this).attr('action'),
          data: data,
          dataType: 'json',
          complete: function(){
            $("#WallForm .loading").slideUp("fast", function(){
              $(this).hide();
              
              $("#WallForm form").slideDown("fast", function(){
              });
            });
          },
          success: function(msg){
            $("#WallForm textarea").val('');
            if(msg.success == true){
              $("#comments_list").prepend(sen.createComment(msg));
            }else{
              $(msg.errors).each(function(i, error){
                switch(error) {
                	case "content":
                    $("#WallForm textarea").before('<p class="error">Your comment cannot be blank.</p>');
                		break;
                }
              });
            }
          },
          error: function(){
            $("#WallForm").prepend('<p class="error">Sorry, your comment could not be posted. Please try again.</p>');
          }
        });
      });
      
      return false;
    });
  },
  
  
  loadWallPosts: function(user_id,options) {
    var _settings = $.extend(this._options, options);
    $.ajax({
      type: "get",
      cache: false,
      url: '/wall_posts/'+user_id+'/'+_settings.comment_offset+'/'+_settings.comment_limit,
      dataType: 'json',
      error: function(){
        alert('Error loading JSON');
      },
      success: function(msg){
        if(msg.count > 0){
          $(msg.comments).each(function(i, comment){
            $("#comments_list").append(sen.createComment(comment));
          });
        }else{
          if (_settings.first_load) {
            $("#comments_list").html('Your first post!');
          }
        }
      }
    });
  },
  
  createComment: function(data) {
    
    var _dl = document.createElement('dl');
    var _a = document.createElement('a');
    var _img = document.createElement('img');
    var _username = document.createElement('p');
    var _posted = document.createElement('p');
    var _member = document.createElement('dd');
    var _content = document.createElement('dd');
    
    $(_dl).addClass('comment');
    $(_member).addClass('member');
    $(_username).addClass('username');
    $(_posted).addClass('posted');
    $(_content).addClass('content');
    
    $(_img).attr('src', data.thumbnail);
    $(_img).attr('alt', data.username);
    $(_a).append(_img);
    $(_a).attr('href', data.profile);
    $(_username).html(data.username);
    $(_posted).html(data.created);
    $(_member).append(_a).append(_username).append(_posted);
    $(_content).html(data.content);
    
    return $(_dl).append(_member).append(_content);
  },
  
  initRatings: function() {
    $(".rating a.loggin").bind('click', function(){
      var href = $(this).attr('href');
      $(this).parents('ul.rating').empty().addClass('loading');
      $(".newsStars .ArchiveRightHead").hide();
      $.post(href, {}, function(data, textStatus){
        if(textStatus == "success"){
          $(".newsStars").replaceWith(data);
          $("#links").hide();
          $("#non_links").show();
        }
      }, "html");
      
      return false;
    });
    
    
    $(".rating a.not_loggin").bind('click', function(){
      $('#rating_stars').hide();
      $('#rating_comment').show();
      var counter = 0;
      
      var timer = setInterval(showStars, 2000);
       

      function showStars() {
        if (counter ==0) { counter++; return; }
        $('#rating_comment').hide();
        $('#rating_stars').show();
        counter == 5? counter = 0 : counter++; 
       }
     
    });
    
  },
  
  addArticleActions: function(options) {
    var _settings = $.extend(this._options, options);
    if(_settings.showPrint) {
      $("#actions").append('<div class="button"><a href="#" class="print"><span>Print This Article</span></a></div>');
      $("#actions .print").bind("click", function(){
        window.print();
        return false;
      });
    }
    if(_settings.showEmail) {
      $("#actions").append('<div class="button"><a href="#" class="email"><span>Email to a Friend</span></a></div>');
      $("#actions .email").bind("click", function(){
        var _w = window.open('mailto:?subject=Send to a friend&content=test', "EmailWindow");
        _w.close();
        return false;
      });
    }
  },
  
  initArchiveCal: function(){
    $("#trigger_calendarfrom").bind("click", function(){
      $("#calendarfrom").datepicker("show");
      return false;
    });
    $("#calendarfrom").datepicker({
      dateFormat: 'yy-mm-dd'
    });
    $("#calendarto").datepicker({
      dateFormat: 'yy-mm-dd'
    });
    $("#trigger_calendarto").bind("click", function(){
      $("#calendarto").datepicker("show");
      return false;
    });
  },
  
  setDropdown: function(e) {
    try {
      MSDropDown.init('#country', 90, 20);
      MSDropDown.showIconWithTitle(false);
    }catch(e) {
      alert(e);
    }
  },
  
  autoClearLogin: function() {
    if ($("#ctl00_login1_txtUsername")) {
      $("#ctl00_login1_txtUsername").bind("focus", function(){
        if ($(this).val() == "Username") {
          $(this).val("");
        }
      });
    }
    if ($("#ctl00_login1_txtUsername")) {
      $("#signin_password").bind("focus", function(){
        if ($(this).val() == "Password") {
          $(this).val("");
        }
      });
    }
  },
  
  autoClearSearch: function() {
    if($("input.search_sen")) {
      $("input.search_sen").bind("click", function(){
        $(this).val("");
      });
    }
  },
  
  // Init called on page load
  init: function() {
    //this.setDropdown();
    //$("#source").dropdown();
    this.autoClearLogin();
    this.autoClearSearch();
  }
}

var RecaptchaOptions = {
  theme: 'clean'
}

$(document).ready(function() {
  sen.init();
});
