$(function() {
  if(window.console === undefined) console = { log: function(){} };

  fixOddEven();
  $('.fuzzytime').fuzzyDate();
  $('a').filter(function(i) {
    var t = $(this);
    if(t.attr('href')) {
      if(t.attr('href').indexOf('/users/loginlog') !== -1) return false;
      if(t.attr('href').indexOf('/users/login') !== -1) return true;
      if(t.attr('href').indexOf('/users/quickregister') !== -1) return true;
    } 
  }).facebox();
  
  
  $('.fav-list').click(function() {
    var el = $(this);
    $.postJSON(PG.url('/lists/jsonfav'), {listid: el.attr('rel')}, {
      success: function(response) {
        $('.fav-list').text(response.label).remove();
      }
    });
  });
  $('.fav-list-small').click(function() {
    var el = $(this), f = arguments.callee;
    $.postJSON(PG.url('/lists/jsonfav'), {listid: el.idFragment()}, {
      success: function(response) {
        el.append('<br/>Added!').removeClass('.fav-list-small bold link').unbind('click', f);
      }
    });
  });
  $('.user-fav').click(function() {
    var el = $(this); f = arguments.callee;
    $.postJSON(PG.url('/users/jsonfav'), {userid: el.idFragment()}, {
      success: function(response) {
        el.text('Added to favorites').removeClass('.user-fav bold link').unbind('click', f);
      }
    });
  });
  $('.fav-item').click(function() {
    var el = $(this), f = arguments.callee;
    $.postJSON(PG.url('/lists/jsonfavitem'), {itemid: el.idFragment()}, {
      success: function(response) {
        el.append('Added!').removeClass('.fav-item').unbind('click', f);
      }
    });
  });
  $('.fav-author').click(function() {
    var el = $(this), f = arguments.callee;
    $.postJSON(PG.url('/users/jsonfav'), {userid: el.idFragment()}, {
      success: function(response) {
        el.append('Added!').removeClass('.fav-author').unbind('click', f);
      }
    });
  });
  $('.fav-list-remove').click(function() {
    var el = $(this), row = el.parents('tr'), lid = row.idFragment();
    $.postJSON(PG.url('/lists/jsonfavremove'), {listid: lid}, {
      success: function(r) {
        row.remove();
        fixOddEven();
      }
    });
  });
  $('.fav-item-remove').click(function() {
    var el = $(this), row = el.parents('tr'), id = row.idFragment();
    $.postJSON(PG.url('/lists/jsonfavitemremove'), {itemid: id}, {
      success: function(r) {
        row.remove();
        fixOddEven();
      }
    });
  });
  $('.fav-author-remove').click(function() {
    var el = $(this), row = el.parents('tr'), id = row.idFragment();
    $.postJSON(PG.url('/users/jsonfavremove'), {userid: id}, {
      success: function(r) {
        row.remove();
        fixOddEven();
      }
    });
  });
  $('.subscription-add').click(function() {
    var el = $(this); f = arguments.callee;
    $.postJSON(PG.url('/subscriptions/jsonadd'), {userid: el.idFragment()}, {
      success: function(response) {
        el.text('Added to subscription list').removeClass('.subscription-add bold link')
                                             .unbind('click', f);
      }
    });
  });
  $('.subscription-remove').click(function() {
    var el = $(this), row = el.parents('tr'), id = row.idFragment();
    $.postJSON(PG.url('/subscriptions/jsondel'), {userid: id}, {
      success: function(r) {
        PG.reload();
      }
    });
  });
});

fixOddEven = function() {
  $('.oddeven').removeClass('oddeven').filter(':even').next('.oddeven-child').andSelf().addClass('odd');
  $('.oddeven-child').removeClass('oddeven-child');
};

if(typeof(Favofinder) == "undefined") {
  Favofinder = {};
}

Favofinder.addUserToFav = function(id) {
  $.postJSON(PG.url('/users/jsonfav'), {userid: id}, {
    success: function(response) {
      $('#add-user-to-favorite-' + id).html(response.label);
    }
  });
};

PG.defaultErrorCallback = function(data) {
  if(typeof data.status !== 'undefined') {
    if(data.status === 403) {
      PG.error('Please log in first.');
    }
  };
};

Favofinder.registerPopup = function() {
  $.get('/users/quickregister', function(data) { $.facebox(data) })
};

Favofinder.loginPopup = function(enableReload) {
  var url = '/users/login/noreload';
  if(enableReload) url = '/users/login';

  $.get(url, function(data) { $.facebox(data) })
};

/**
 * Gets executed after Favofinder.registerPopup has successfully created an account
 */
Favofinder.afterRegisterPopup = function() {
  Favofinder.reloadTop();
};

/**
 * Gets executed after Favofinder.loginPopup has successfully created an account
 */
Favofinder.afterLoginPopup = function() {
  Favofinder.reloadTop();
};

Favofinder.deleteGroup = function(groupname) {
  var msg = "Do you really want to delete the group " + groupname + "? ";
  msg += "This operation cannot be undone.";
  
  if(!confirm(msg)) return;
  
  $.getJSON(PG.url("/groups/jsondelete/" + groupname), function(json) {
    if(json.exception) return alert(json.exception);
    
    PG.reload();
  });
};

Favofinder.makeUlOddEven = function(ul) {
  var odd = true;
  $('>li', $(ul)).each(function() {
    if(odd) $(this).addClass('odd');
    else $(this).removeClass('odd');
    
    odd = !odd;
  });
};

/**
 * Reloads the top menu. Useful when you login using ajax.
 */
Favofinder.reloadTop = function() {
  $('#l_pagetop').load('/layout/topmenu');
};

/**
 * Comment paging
 */
$(function() {
  $('.comments-paging').live('click', function(e) {
    var t = $(e.target); // object beeing clicked
    if(t.is('a.paginglink')) {
      var url = t.attr('href').split('#');
      if(url.length == 0) return false;
      $.getJSON(url[0], function(r) {
        t.parents('.commentswrapper').replaceWith(r.result);
      });
      return false; // prevent default action
    }
  });
});

/*
 *
 * Textarea Maxlength Setter JQuery Plugin
 * Version 1.0
 *
 * Copyright (c) 2008 Viral Patel
 * website : http://viralpatel.net/blogs
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
*/
jQuery.fn.maxlength = function(){
    $("textarea[maxlength]").keypress(function(event){
        var key = event.which;
        //all keys including return.
        if(key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = $(this).val().length;
            if(length >= maxLength) {
                event.preventDefault();
            }
        }
    });
}

