//Tipsy jQuery plugin
(function(c){function a(d){if(d.attr("title")||typeof(d.attr("original-title"))!="string"){d.attr("original-title",d.attr("title")||"").removeAttr("title")}}function b(e,d){this.$element=c(e);this.options=d;this.enabled=true;a(this.$element)}b.prototype={show:function(){var g=this.getTitle();if(g&&this.enabled){var f=this.tip();f.find(".tipsy-inner")[this.options.html?"html":"text"](g);f[0].className="tipsy";f.remove().css({top:0,left:0,visibility:"hidden",display:"block"}).appendTo(document.body);var j=c.extend({},this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight});var d=f[0].offsetWidth,i=f[0].offsetHeight;var h=(typeof this.options.gravity=="function")?this.options.gravity.call(this.$element[0]):this.options.gravity;var e;switch(h.charAt(0)){case"n":e={top:j.top+j.height+this.options.offset,left:j.left+j.width/2-d/2};break;case"s":e={top:j.top-i-this.options.offset,left:j.left+j.width/2-d/2};break;case"e":e={top:j.top+j.height/2-i/2,left:j.left-d-this.options.offset};break;case"w":e={top:j.top+j.height/2-i/2,left:j.left+j.width+this.options.offset};break}if(h.length==2){if(h.charAt(1)=="w"){e.left=j.left+j.width/2-15}else{e.left=j.left+j.width/2-d+15}}f.css(e).addClass("tipsy-"+h);if(this.options.fade){f.stop().css({opacity:0,display:"block",visibility:"visible"}).animate({opacity:this.options.opacity})}else{f.css({visibility:"visible",opacity:this.options.opacity})}}},change:function(){var d=this.options.fade;this.options.fade=false;this.show();this.options.fade=d},tooltipActive:function(){return(this.hoverState=="in")},hide:function(){if(this.options.fade){this.tip().stop().fadeOut(function(){c(this).remove()})}else{this.tip().remove()}},getTitle:function(){var f,d=this.$element,e=this.options;a(d);var f,e=this.options;if(typeof e.title=="string"){f=d.attr(e.title=="title"?"original-title":e.title)}else{if(typeof e.title=="function"){f=e.title.call(d[0])}}f=(""+f).replace(/(^\s*|\s*$)/,"");return f||e.fallback},tip:function(){if(!this.$tip){this.$tip=c('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"/></div>')}return this.$tip},validate:function(){if(!this.$element[0].parentNode){this.hide()}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled}};c.fn.tipsy=function(h){if(h===true){return this.data("tipsy")}else{if(typeof h=="string"){return this.data("tipsy")[h]()}}h=c.extend({},c.fn.tipsy.defaults,h);function g(k){var l=c.data(k,"tipsy");if(!l){l=new b(k,c.fn.tipsy.elementOptions(k,h));c.data(k,"tipsy",l)}return l}function j(){var k=g(this);k.hoverState="in";if(h.delayIn==0){k.show()}else{setTimeout(function(){if(k.hoverState=="in"){k.show()}},h.delayIn)}}function f(){var k=g(this);k.hoverState="out";if(h.delayOut==0){k.hide()}else{setTimeout(function(){if(k.hoverState=="out"){k.hide()}},h.delayOut)}}if(!h.live){this.each(function(){g(this)})}if(h.trigger!="manual"){var d=h.live?"live":"bind",i=h.trigger=="hover"?"mouseenter":"focus",e=h.trigger=="hover"?"mouseleave":"blur";this[d](i,j)[d](e,f)}return this};c.fn.tipsy.defaults={delayIn:0,delayOut:0,fade:false,fallback:"",gravity:"n",html:false,live:false,offset:0,opacity:0.8,title:"title",trigger:"hover"};c.fn.tipsy.elementOptions=function(e,d){return c.metadata?c.extend({},d,c(e).metadata()):d};c.fn.tipsy.autoNS=function(){return c(this).offset().top>(c(document).scrollTop()+c(window).height()/2)?"s":"n"};c.fn.tipsy.autoWE=function(){return c(this).offset().left>(c(document).scrollLeft()+c(window).width()/2)?"e":"w"}})(jQuery);
//LazyLoad jQuery plugin
(function(a){a.fn.lazyload=function(b){var c={threshold:0,failurelimit:0,event:"scroll",effect:"show",container:window};if(b){a.extend(c,b)}var d=this;if("scroll"==c.event){a(c.container).bind("scroll",function(g){var e=0;d.each(function(){if(a.abovethetop(this,c)||a.leftofbegin(this,c)){}else{if(!a.belowthefold(this,c)&&!a.rightoffold(this,c)){a(this).trigger("appear")}else{if(e++>c.failurelimit){return false}}}});var f=a.grep(d,function(h){return !h.loaded});d=a(f)})}this.each(function(){var e=this;if("scroll"!=c.event||undefined==a(e).attr("src")||c.placeholder==a(e).attr("src")||(a.abovethetop(e,c)||a.leftofbegin(e,c)||a.belowthefold(e,c)||a.rightoffold(e,c))){if(c.placeholder){a(e).attr("src",c.placeholder)}else{a(e).removeAttr("src")}e.loaded=false}else{e.loaded=true}a(e).one("appear",function(){if(!this.loaded){a("<img />").bind("load",function(){a(e).hide().attr("src",a(e).attr("original"))[c.effect](c.effectspeed);e.loaded=true}).attr("src",a(e).attr("original"))}});if("scroll"!=c.event){a(e).bind(c.event,function(f){if(!e.loaded){a(e).trigger("appear")}})}});a(c.container).trigger(c.event);return this};a.belowthefold=function(c,d){if(d.container===undefined||d.container===window){var b=a(window).height()+a(window).scrollTop()}else{var b=a(d.container).offset().top+a(d.container).height()}return b<=a(c).offset().top-d.threshold};a.rightoffold=function(c,d){if(d.container===undefined||d.container===window){var b=a(window).width()+a(window).scrollLeft()}else{var b=a(d.container).offset().left+a(d.container).width()}return b<=a(c).offset().left-d.threshold};a.abovethetop=function(c,d){if(d.container===undefined||d.container===window){var b=a(window).scrollTop()}else{var b=a(d.container).offset().top}return b>=a(c).offset().top+d.threshold+a(c).height()};a.leftofbegin=function(c,d){if(d.container===undefined||d.container===window){var b=a(window).scrollLeft()}else{var b=a(d.container).offset().left}return b>=a(c).offset().left+d.threshold+a(c).width()};a.extend(a.expr[":"],{"below-the-fold":"$.belowthefold(a, {threshold : 0, container: window})","above-the-fold":"!$.belowthefold(a, {threshold : 0, container: window})","right-of-fold":"$.rightoffold(a, {threshold : 0, container: window})","left-of-fold":"!$.rightoffold(a, {threshold : 0, container: window})"})})(jQuery);


/***** lazy load userbars start *****/
$(document).ready(function() {
  $("img.ub").lazyload({
    placeholder : "/images/empty_ub.png",
    effect : "fadeIn",
    threshold : 200
  });
});
/***** lazy load userbars end *****/

/***** menu start *****/
var t = null;
//wordt opgeroepen als je met je muis over een ander main menu item gaat
function showSubmenu(section) {
  clearTimeout(t);
  $(".submenu").hide();
  $("#submenu_"+section).show();
}
//wordt opgeroepen wanneer je met je muis van het main -of submenu gaat
function showDefaultSubmenu() {
  t = setTimeout("restoreSubmenu()", 100);
}
function restoreSubmenu() {
  var classname = $("#main_menu li .current").parent().attr('class');
  if(classname != undefined) {
    var section = classname.split("_")[2];
    $(".submenu").hide();
    $("#submenu_"+section).show();
  }
}
/***** menu end *****/

/***** search start *****/
//wordt opgeroepen wanneer men op de search tabs klikt en wanneer de pagina laadt
function changeSearchMode(section) {
  $('#search_userbars').removeClass('active');
  $('#search_members').removeClass('active');
  $('#search_forum').removeClass('active');

  if(section == 'userbars') {
    $('#search_userbars').addClass('active');
    $('#search_form').attr('action', search_userbars);
    $('#search_query').attr('name', 'search');
  }
  else if(section == 'members') {
    $('#search_members').addClass('active');
    $('#search_form').attr('action', search_members);
    $('#search_query').attr('name', 'search');
  }
  else if(section == 'forum') {
    $('#search_forum').addClass('active');
    $('#search_form').attr('action', search_forum);
    $('#search_query').attr('name', 'keywords');
  }
}
function submitSearchForm() {
  if(trim($('#search_query').val()).length > 1) {
    document.search_form.submit();
  }
  else {
    alert('Please enter a valid search term');
  }
}
function submitAdvancedSearch() {
  var search = trim($('#advanced_search_form #search').val());
  if(search.length > 1) {
    search = search.replace(/ /g, '+');
    var url = search_userbars+'?search='+search;
    var mode = trim($('#advanced_search_form #mode').val());
    if(mode != '') {
      url += '&mode=' + mode;
    }
    var type = trim($('#advanced_search_form #type').val());
    if(type != '') {
      url += '&type=' + type;
    }
    var category = trim($('#advanced_search_form #category').val());
    if(category != '') {
      category = category.replace(/ /g, '+');
      url += '&category=' + category;
    }
    var showroom = trim($('#advanced_search_form #showroom').val());
    if(showroom != '') {
      url += '&showroom=' + showroom;
    }
    window.location = url;
  }
  else {
    alert('Please enter a valid search term');
  }
}
function submitMemberSearch() {
  var search = trim($('#member_search_form #search').val());
  if(search.length > 1) {
    document.member_search_form.submit();
  }
  else {
    alert('Please enter a valid search term');
  }
}
function showHideAdvancedSearch() {
  if($('.collapse_button').hasClass('min')) {
    $('.collapse_button').removeClass('min');
    $('.collapse_button').addClass('plus');
    $('.box.advanced_search_wrapper').css('border-bottom', '0px');
    //$('.content.advanced_search_wrapper').hide();
    $('.content.advanced_search_wrapper').slideUp(500);
  }
  else {
    $('.collapse_button').removeClass('plus');
    $('.collapse_button').addClass('min');
    $('.box.advanced_search_wrapper').css('border-bottom', '1px solid #ccc');
    //$('.content.advanced_search_wrapper').show();
    $('.content.advanced_search_wrapper').slideDown(500);
  }
}
$(document).ready(function() {
  $("#twitter_badge").tipsy({gravity: 'e'});
});
/***** search end *****/

/***** timestamp to local date start *****/
$(document).ready(function() {
  refreshTimestamps();
});
function refreshTimestamps() {
  //we gaan elke datum label vervangen met de locale tijd
  $(".nice_date").each(function(i){
    var current_text = $(this).text();
    var timestamp = this.title;
    var new_text = humanDate(timestamp);
    if(new_text != current_text) {
      $(this).text(new_text);
    }
  });
}
//http://ejohn.org/blog/javascript-pretty-date/
//http://www.zachleat.com/web/2008/03/23/yet-another-pretty-date-javascript/
function humanDate(date_str){
  var time_formats = [
    [2, '1 second ago'],
    [60, 'seconds ago', 1],
    [90, '1 minute ago'], // 60*1.5
    [3600, 'minutes ago', 60], // 60*60, 60
    [5400, '1 hour ago'], // 60*60*1.5
    [86400, 'hours ago', 3600], // 60*60*24, 60*60
    [129600, '1 day ago'], // 60*60*24*1.5
    [604800, 'days ago', 86400], // 60*60*24*7, 60*60*24
    [907200, '1 week ago'], // 60*60*24*7*1.5
    [2628000, 'weeks ago', 604800], // 60*60*24*(365/12), 60*60*24*7
    [3942000, '1 month ago'], // 60*60*24*(365/12)*1.5
    [31536000, 'months ago', 2628000], // 60*60*24*365, 60*60*24*(365/12)
    [47304000, '1 year ago'], // 60*60*24*365*1.5
    [3153600000, 'years ago', 31536000], // 60*60*24*365*100, 60*60*24*365
  ];

  var time = ('' + date_str).replace(/-/g,"/");
  var dt = new Date();
  var dt_utc =  new Date(time);
  var seconds = ((dt - dt_utc + (dt.getTimezoneOffset() * 60000)) / 1000);

  if(seconds < 0) {
    return '';
  }

  if(seconds >= 907200) { //1 week ago
    var month_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

    var dt_loc = new Date(dt_utc.getTime() - (dt.getTimezoneOffset() * 60000));
    var curr_day = dt_loc.getDate();
    var sup = "";
    if(curr_day == 1 || curr_day == 21 || curr_day == 31) {
      sup = "st";
    }
    else if(curr_day == 2 || curr_day == 22) {
      sup = "nd";
    }
    else if(curr_day == 3 || curr_day == 23) {
      sup = "rd";
    }
    else {
      sup = "th";
    }

    var curr_month = dt_loc.getMonth();
    var curr_year = dt_loc.getFullYear();

    return "on " + month_names[curr_month] + " " + curr_day + "" + sup + ", " + curr_year;
  }

  var i = 0;
  var format;
  while(format = time_formats[i++]) {
    if(seconds < format[0]) {
      if(format.length == 2) {
        return format[1];
      }
      else {
        return Math.floor(seconds / format[2]) + ' ' + format[1];
      }
    }
  }

  return '';
};
/***** timestamp to local date end *****/

/***** userbars list start *****/
function addUserbarEvents() {
  $('.rating_bar .overlay').mousemove(function(event) {
    var userbar_id = $(event.target).parent().attr('id').split('_')[2];

    //als deze userbar al gerate is niets doen
    if(ub_info[userbar_id]['rated']) return;

    var pos = $('#rating_bar_'+userbar_id+' .overlay').offset();
    var width = $('#rating_bar_'+userbar_id+' .overlay').width();
    var x = Math.ceil(event.pageX - pos.left);

    //1 - 17 = 1 star
    //18 - 34 = 2 star
    //35 - 51 = 3 star
    //52 - 68 = 4 star
    //69 - 84 = 5 star
    var w = 0;
    if(x <= 17) {
      w = 17;
    }
    else if(x <= 34) {
      w = 34;
    }
    else if(x <= 51) {
      w = 51;
    }
    else if(x <= 68) {
      w = 68;
    }
    else if(x <= 84) {
      w = 84;
    }

    $('#rating_bar_'+userbar_id+' .hover').width(w);
  });
  $('.rating_bar .overlay').mouseout(function(event) {
    var userbar_id = $(event.target).parent().attr('id').split('_')[2];

    //als deze userbar al gerate is niets doen
    if(ub_info[userbar_id]['rated']) return;

    $('#rating_bar_'+userbar_id+' .hover').width(0);
  });

  $('.rating_bar .overlay').click(function(event) {
    var userbar_id = $(event.target).parent().attr('id').split('_')[2];

    //als deze userbar al gerate is niets doen
    if(ub_info[userbar_id]['rated']) return;

    var width = $('#rating_bar_'+userbar_id+' .hover').width();
    var ratings = new Array();
    ratings[17] = 1;
    ratings[34] = 2;
    ratings[51] = 3;
    ratings[68] = 4;
    ratings[84] = 5;

    addRating(userbar_id, ratings[width]);
  });

  $('.ub_box .ub').each(function(index) {
    var userbar_id = this.id.split('_')[1];
    $(this).bind('contextmenu', function(e) { return false; });

    var parent_tag = ($(this).parent().get(0).tagName).toLowerCase();
    if(parent_tag == 'a') {
      $(this).bind('mouseover', function(e) {
        $('#ub_box_top_' + userbar_id).addClass('hover');
      });
      $(this).bind('mouseout', function(e) {
        $('#ub_box_top_' + userbar_id).removeClass('hover');
      });
    }

    //aan de hand van score de sterretjes tekenen
    if(ub_info[userbar_id]['rated']) {
      $('#rating_bar_'+userbar_id+' .hover').width(parseFloat(ub_info[userbar_id]['score']) * 17);
    }
    else {
      $('#rating_bar_'+userbar_id+' .current').width(parseFloat(ub_info[userbar_id]['score']) * 17);
      $('#rating_bar_'+userbar_id+' .overlay').addClass('pointer');
    }

    //de tooltips voor de rating sterretjes zetten
    $('#rating_bar_'+userbar_id+' .overlay').attr('title', 'rating ' + ub_info[userbar_id]['score'] + '&nbsp;&nbsp;|&nbsp;&nbsp;' + ub_info[userbar_id]['votes'] + ' vote' + (parseFloat(ub_info[userbar_id]['votes']) > 1 ? 's' : ''));
    $('#rating_bar_'+userbar_id+' .overlay').tipsy({fade: false, offset: 8, live: true, html: true});
  });

  $('.ub_box_bottom .icons .download').each(function(index) {
    $(this).attr('title', 'download userbar');
    $(this).tipsy({offset: 8});
    $(this).bind('click', function(event) {
      var userbar_id = $(event.target).parent().attr('id').split('_')[1];

      $.getJSON(ajax_gateway, { p2: 'downloadUserbar', p3: userbar_id }, function(json) {
        if(json.link != '') {
          if(json.downloads != '') {
            $('#button_row_'+userbar_id+' .downloads').html(json.downloads + ' download' + (json.downloads != 1 ? 's' : ''));
          }
          window.location = json.link;
        }
        else {
          alert("Error while downloading userbar")
        }
      });
      return false;
    });
  });
  $('.ub_box_bottom .icons .heart').each(function(index) {
    $(this).attr('title', 'add to favorites');
    $(this).tipsy({offset: 8});
    $(this).bind('click', function(event) {
      addToFavorites($(this), $(event.target).parent().attr('id').split('_')[1]);
      return false;
    });
  });
  $('.ub_box_bottom .icons .heart_active').each(function(index) {
    $(this).attr('title', 'remove from favorites');
    $(this).tipsy({offset: 8});
    $(this).bind('click', function(event) {
      removeFromFavorites($(this), $(event.target).parent().attr('id').split('_')[1]);
      return false;
    });
  });
  $('.ub_box_bottom .icons .animator').each(function(index) {
    $(this).attr('title', 'add to animation');
    $(this).tipsy({offset: 8});
    $(this).bind('click', function(event) {
      addToAnimator($(this), $(event.target).parent().attr('id').split('_')[1]);
      return false;
    });
  });
  $('.ub_box_bottom .icons .animator_active').each(function(index) {
    $(this).attr('title', 'remove from animation');
    $(this).tipsy({offset: 8});
    $(this).bind('click', function(event) {
      removeFromAnimator($(this), $(event.target).parent().attr('id').split('_')[1]);
      return false;
    });
  });
  $('.ub_box_bottom .icons .report').each(function(index) {
    //todo
    $(this).attr('title', 'report userbar');
    $(this).tipsy({offset: 8});
  });
  $('.ub_box_top .quality').each(function(index) {
    $(this).attr('title', 'quality tag');
    $(this).tipsy({offset: 5, gravity: 'w'});
  });
  $('.ub_box_bottom .icons .edit').each(function(index) {
    $(this).attr('title', 'edit userbar');
    $(this).tipsy({offset: 8});
  });
  $('.admin_actions .add_quality_tag').each(function(index) {
    $(this).attr('title', 'add quality tag');
    $(this).tipsy({offset: 8, gravity: 'w'});
    $(this).bind('click', function(event) {
      var userbar_id = $(this).attr('id').split('_')[3];
      $(this).hide();

      $.getJSON(ajax_gateway, { p2: 'addQualityTag', p3: userbar_id }, function(json) {
        if(json.success) {
          //refresh page
          location.reload();
        }
        else {
          alert("something went wrong while adding the quality tag");
        }
      });
      return false;
    });
  });
  $('.admin_actions .remove_quality_tag').each(function(index) {
    $(this).attr('title', 'remove quality tag');
    $(this).tipsy({offset: 8, gravity: 'w'});
    $(this).bind('click', function(event) {
      var userbar_id = $(this).attr('id').split('_')[3];
      $(this).hide();

      $.getJSON(ajax_gateway, { p2: 'removeQualityTag', p3: userbar_id }, function(json) {
        if(json.success) {
          //refresh page
          location.reload();
        }
        else {
          alert("something went wrong while removing the quality tag");
        }
      });
      return false;
    });
  });
  $('.admin_actions .delete_userbar').each(function(index) {
    $(this).attr('title', 'delete userbar');
    $(this).tipsy({offset: 8, gravity: 'w'});
    $(this).bind('click', function(event) {

      //als we op de userbar pagina zitten moeten we redirecten naar homepage, anders page refresh
      var query_url = location.pathname;
      var return_url = window.location;
      if(query_url.indexOf('/userbar/', 0) != -1) {
        var return_url = 'http://'+location.hostname;
      }

      var userbar_id = $(this).attr('id').split('_')[2];
      return deleteUserbar(userbar_id, return_url);
    });
  });
}

//wordt opgeroepen wanneer een member of admin een userbar delete
function deleteUserbar(userbar_id, return_link) {
  if(confirm('Are you sure you want to delete this userbar?')) {
    $('.edit_userbars .delete_userbar').hide();

    $.getJSON(ajax_gateway, { p2: 'deleteUserbar', p3: userbar_id }, function(json) {
      if(json.success) {
        window.location = return_link;
      }
      else {
        alert("something went wrong while deleting the userbar");
      }
    });
  }
  return false;
}

//wordt opgeroepen voor het open -of toeklappen van de filter en sort dropdowns
function toggle(item) {
  $('#' + item).toggle();
  return false;
}

//wordt opgeroepen wanneer het filter -of sort form gesubmit wordt
function submitListForm(type, key) {
  if(type == 'filter') {
    $('#filter_form_key').val(key);
    $('#filter_form').submit();
  }
  else if(type == 'sort') {
    $('#sort_form_key').val(key);
    $('#sort_form').submit();
  }
}
function addRating(userbar_id, rating) {
  $('#rating_bar_'+userbar_id+' .overlay').html('processing...');
  $('#rating_bar_'+userbar_id+' .overlay').removeClass('pointer');
  $('#rating_bar_'+userbar_id+' .current').hide();
  $('#rating_bar_'+userbar_id+' .hover').hide();
  $('#rating_bar_'+userbar_id).addClass('hide');
  $.getJSON(ajax_gateway, { p2: 'addRating', p3: userbar_id, p4: rating }, function(json) {
    if(json.success) {
      $('#rating_bar_'+userbar_id+' .overlay').html('');
      ub_info[userbar_id]['rated'] = true;
      ub_info[userbar_id]['score'] = json.score;
      ub_info[userbar_id]['votes'] = json.votes;
      $('#rating_bar_'+userbar_id+' .hover').width(parseFloat(ub_info[userbar_id]['score']) * 17);
      $('#rating_bar_'+userbar_id+' .hover').show();
      $('#rating_bar_'+userbar_id+' .score').html(ub_info[userbar_id]['score']);
      $('#rating_bar_'+userbar_id).removeClass('hide');
      $('#rating_bar_'+userbar_id+' .overlay').attr('title', 'rating ' + ub_info[userbar_id]['score'] + '&nbsp;&nbsp;|&nbsp;&nbsp;' + ub_info[userbar_id]['votes'] + ' vote' + (parseFloat(ub_info[userbar_id]['votes']) > 1 ? 's' : ''));
      if($('#rating_bar_'+userbar_id+' .overlay').tipsy('tooltipActive')) {
        $('#rating_bar_'+userbar_id+' .overlay').tipsy('show');
      }
    }
    else {
      $('#rating_bar_'+userbar_id+' .overlay').html('');
      ub_info[userbar_id]['rated'] = true;
      $('#rating_bar_'+userbar_id+' .hover').width(parseFloat(ub_info[userbar_id]['score']) * 17);
      $('#rating_bar_'+userbar_id+' .hover').show();
      $('#rating_bar_'+userbar_id).removeClass('hide');
      alert(json.message);
    }
  });
}
function addToFavorites(current_object, userbar_id) {
  if(!logged_in) {
    alert("You have to be logged in to add a userbar to your favorites")
    return false;
  }
  $.getJSON(ajax_gateway, { p2: 'addToFavorites', p3: userbar_id }, function(json) {
    if(json.success) {
      current_object.removeClass();
      current_object.addClass('heart_active');
      current_object.attr('title', 'remove from favorites');
      if(current_object.tipsy('tooltipActive')) {
        current_object.tipsy('show');
      }
      $('#button_row_'+userbar_id+' .favorites').html(json.favorites);
      $('#nr_favorites').html(json.my_favorites);
      current_object.unbind('click');
      current_object.bind('click', function(event) {
        removeFromFavorites(current_object, userbar_id);
        return false;
      });
    }
    else {
      alert(json.message);
    }
  });
}
function removeFromFavorites(current_object, userbar_id) {
  if(!logged_in) {
    alert("You have to be logged in to remove a userbar from your favorites")
    return false;
  }
  $.getJSON(ajax_gateway, { p2: 'removeFromFavorites', p3: userbar_id }, function(json) {
    if(json.success) {
      current_object.removeClass();
      current_object.addClass('heart');
      current_object.attr('title', 'add to favorites');
      if(current_object.tipsy('tooltipActive')) {
        current_object.tipsy('show');
      }
      $('#button_row_'+userbar_id+' .favorites').html(json.favorites);
      $('#nr_favorites').html(json.my_favorites);
      current_object.unbind('click');
      current_object.bind('click', function(event) {
        addToFavorites(current_object, userbar_id);
        return false;
      });
      //als we op de my favorites pagina zitten moeten we een page reload doen
      var query_url = location.pathname;
      if(query_url.indexOf('favorites', 0) != -1) {
        location.reload();
      }
    }
    else {
      alert(json.message);
    }
  });
}
function addToAnimator(current_object, userbar_id) {
  $.getJSON(ajax_gateway, { p2: 'addToAnimator', p3: userbar_id }, function(json) {
    if(json.success) {
      current_object.removeClass();
      current_object.addClass('animator_active');
      current_object.attr('title', 'remove from animation');
      if(current_object.tipsy('tooltipActive')) {
        current_object.tipsy('show');
      }
      current_object.unbind('click');
      current_object.bind('click', function(event) {
        removeFromAnimator(current_object, userbar_id);
        return false;
      });
      setAnimatorNumber(json.number);
    }
    else {
      setAnimatorNumber(json.number);
      alert(json.message);
    }
  });
}
function removeFromAnimator(current_object, userbar_id) {
  $.getJSON(ajax_gateway, { p2: 'removeFromAnimator', p3: userbar_id }, function(json) {
    if(json.success) {
      current_object.removeClass();
      current_object.addClass('animator');
      current_object.attr('title', 'add to animation');
      if(current_object.tipsy('tooltipActive')) {
        current_object.tipsy('show');
      }
      current_object.unbind('click');
      current_object.bind('click', function(event) {
        addToAnimator(current_object, userbar_id);
        return false;
      });
      setAnimatorNumber(json.number);
    }
    else {
      setAnimatorNumber(json.number);
      alert(json.message);
    }
  });
}
function setAnimatorNumber(number) {
  if(number > 0) {
    $('#animator_badge').html(number);
    $('#animator_badge').show();
  }
  else {
    $('#animator_badge').html(number);
    $('#animator_badge').hide();
  }
}
/***** userbars list end *****/

/***** userbar page start *****/
function commentBlur() {
  var value = $('#comment_message').val();
  if(value == '') {
    $('#comment_message').val('Your comment here...');
  }
}
function commentActive() {
  var value = $('#comment_message').val();
  if(value == 'Your comment here...') {
    $('#comment_message').val('');
  }
}
function commentCounter() {
  var value = $('#comment_message').val();
  var textlength = value.length;
  if(textlength > max_comment_characters) {
    $('#comment_message').val(value.substring(0, max_comment_characters));
    $('.comment_controls .info').html('0 characters left');
    alert("Your message has reached the maximum number of characters");
  }
  else {
    var characters_left = max_comment_characters - textlength;
    $('.comment_controls .info').html(characters_left + ' character' + (characters_left > 1 ? 's' : '') + ' left');
  }
}
//wordt opgeroepen wanneer een moderator of admin een comment delete
function deleteComment(comment_id) {
  if(confirm('Are you sure you want to delete this comment?')) {
    $.getJSON(ajax_gateway, { p2: 'deleteComment', p3: comment_id }, function(json) {
      if(json.success) {
        location.reload();
      }
      else {
        alert("something went wrong while deleting the comment");
      }
    });
  }
  return false;
}
/***** userbar page end *****/

/***** chatbox start *****/
function chatBlur() {
  var value = $('#chat_message').val();
  if(value == '') {
    $('#chat_message').val('Your message here...');
  }
}
function chatActive() {
  var value = $('#chat_message').val();
  if(value == 'Your message here...') {
    $('#chat_message').val('');
  }
}
function chatCounter() {
  var value = $('#chat_message').val();
  var textlength = value.length;
  if(textlength > max_chat_characters) {
    $('#chat_message').val(value.substring(0, max_chat_characters));
    $('.shoutbox_controls .info').html('0 characters left');
    alert("Your message has reached the maximum number of characters");
  }
  else {
    var characters_left = max_chat_characters - textlength;
    $('.shoutbox_controls .info').html(characters_left + ' character' + (characters_left > 1 ? 's' : '') + ' left');
  }
}
function submitChatMessage() {
  //todo form even verberken (processing tonen)
  var message = $('#chat_message').val();
  $.getJSON(ajax_gateway, { p2: 'addChatMessage', message: message }, function(json) {
    if(json.success) {
      $('#chat_message').val('Your message here...');
      $('.shoutbox_controls .info').html(max_chat_characters + ' characters left');
      showEventMessage(json.event);
    }
    else {
      alert(json.message);
    }
  });
  return false;
}
function showEventMessage(data) {
  if(data['type'] == 'chat') {
    var html = "<li id='chat_msg_"+data['id']+"'>";
    html += "<div class='date nice_date' title='"+data['timestamp']+"'></div>";
    html += "<div><a href='"+data['author_link']+"'>"+data['author']+"</a></div>";
    html += "<div class='message'>"+data['message']+"</div>";
    html += "</li>";

    $('.shoutbox').prepend(html);
    $('#chat_msg_'+data['id']).hide();
    $('#chat_msg_'+data['id']).animate({ height: 'toggle', opacity: 'toggle' }, 500);
    refreshTimestamps();
  }
}
function readMessages() {
  $.ajax({
    url: ajax_gateway,
    type: 'GET',
    dataType: 'json',
    async: true,
    cache: false,
    data: ({ p2: 'getEventMessages', last_timestamp: last_timestamp, last_chat_id: last_chat_id, last_activity_id: last_activity_id }),
    success: function(data) {
      if(data.timestamp > last_timestamp) {
        last_timestamp = data.timestamp;
      }
      if($.isArray(data.events)) {
        $.each(data.events, function(index, value) {
          if(value['type'] == 'chat' && value['id'] > last_chat_id) {
            last_chat_id = value['id'];
          }
          else if(value['type'] == 'activity' && value['id'] > last_activity_id) {
            last_activity_id = value['id'];
          }
          if(value['type'] == 'chat' && value['author_id'] == member_id) {
            //we moeten niets doen want het bericht wordt er op een andere manier getoond
          }
          else {
            showEventMessage(value);
          }
        });
      }
      //setTimeout('readMessages()', 1000);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      setTimeout('readMessages()', 15000);
    }
  });
}
//wordt opgeroepen wanneer een moderator of admin een shoutbox reactie delete
function deleteChatMessage(message_id) {
  if(confirm('Are you sure you want to delete this shoutbox message?')) {
    $.getJSON(ajax_gateway, { p2: 'deleteChatMessage', p3: message_id }, function(json) {
      if(json.success) {
        location.reload();
      }
      else {
        alert("something went wrong while deleting the shoutbox message");
      }
    });
  }
  return false;
}
/***** chatbox end *****/

/***** homepage scroller start *****/
function showNext(type) {
  var items = scroller[type];
  var current = scroller_active[type];
  for(i=0; i<items.length; i++) {
    if(items[i] == current) {
      var position = i;
      break;
    }
  }
  if(position != undefined) {
    var new_tab = items[0];
    if(position < (items.length-1)) {
      new_tab = items[(position+1)];
    }
    $('#hpt_'+current).hide();
    $('#hpc_'+current).hide();
    $('#hpt_'+new_tab).fadeIn(300);
    //$('#hpt_'+new_tab).show();
    $('#hpc_'+new_tab).fadeIn(300);
    //$('#hpc_'+new_tab).show();
    scroller_active[type] = new_tab;
  }
}
function showPrevious(type) {
  var items = scroller[type];
  var current = scroller_active[type];
  for(i=(items.length-1); i>=0; i--) {
    if(items[i] == current) {
      var position = i;
      break;
    }
  }
  if(position != undefined) {
    var new_tab = items[(items.length-1)];
    if((position-1) >= 0) {
      new_tab = items[(position-1)];
    }
    $('#hpt_'+current).hide();
    $('#hpc_'+current).hide();
    $('#hpt_'+new_tab).fadeIn(300);
    //$('#hpt_'+new_tab).show();
    $('#hpc_'+new_tab).fadeIn(300);
    //$('#hpc_'+new_tab).show();
    scroller_active[type] = new_tab;
  }
}
/***** homepage scroller end *****/

/***** userbar animator start *****/
function disableAnimatorContextMenu() {
  $('.animator_list_wrapper img').each(function(index) {
    $(this).bind('contextmenu', function(e) { return false; });
  });
  $('.animator_result img').each(function(index) {
    $(this).bind('contextmenu', function(e) { return false; });
  });
}
function attachAnimatorTooltips() {
  $('.ub_down').each(function(index) {
    $(this).attr('title', 'move down');
    $(this).tipsy({offset: 8});
  });
  $('.ub_up').each(function(index) {
    $(this).attr('title', 'move up');
    $(this).tipsy({offset: 8});
  });
  $('.delete_ub').each(function(index) {
    $(this).attr('title', 'delete userbar');
    $(this).tipsy({offset: 8, gravity: 'w'});
  });
}
function startAnimator() {
  userbars = getAnimatorUserbars();
  if(userbars.length == 0) {
    alert("You have no userbars selected");
  }
  else if(userbars.length == 1) {
    alert("You should at lease select 2 userbars");
  }
  else {
    var effect = $('#effect').val();
    var pause = $('#pause').val();

    $('.start_animator').hide();
    $('.animator_result_wrapper').hide();
    $('.animator_loading').show();
    $('.animator_bb_code_button').show();
    $('.bb_code_wrapper').hide();

    $.getJSON(ajax_gateway, { p2: 'animateUserbar', p3: effect, p4: pause }, function(json) {
      if(json.success) {
        var img = new Image();
        img.onload = function () {
          $('.animator_loading').hide();
          $('.start_animator').show();

          $('.animator_result_userbar').attr('src', json.userbar_src);
          $('.animator_result_userbar').attr('id', json.userbar_id);
          $('.animator_download_link').attr('href', json.download_link);
          $('.animator_result_wrapper').show();
        };
        img.onerror = function () {
          alert('Error while loading animated userbar');
        };
        img.src = json.userbar_src;
      }
      else {
        $('.animator_loading').hide();
        $('.start_animator').show();
        alert(json.message);
      }
    });
  }
}
var base_hotlink_html = '';
function getAnimatedUserbarHotlink() {
  //we gaan de eerste versie van de bb-code html bijhouden
  //later gaan we daar telkens de %hotlink% vervangen door een echte link
  if(base_hotlink_html == '') {
    base_hotlink_html = $('.bb_code_wrapper').html();
  }

  $('.animator_bb_code_button').hide();
  $('.animator_bb_loading').show();
  var userbar_id = $('.animator_result_userbar').attr('id');

  $.getJSON(ajax_gateway, { p2: 'getAnimatedUserbarHotlink', p3: userbar_id }, function(json) {
    if(json.success) {
      var hotlink = json.hotlink;
      var replace_string = "%hotlink%";
      var new_html = base_hotlink_html.replace(/%hotlink%/g, hotlink);
      $('.bb_code_wrapper').html(new_html);

      $('.animator_bb_loading').hide();
      $('.bb_code_wrapper').show();
    }
    else {
      $('.animator_bb_loading').hide();
      alert(json.message);
    }
  });
}
function getAnimatorUserbars() {
  var userbars = new Array();
  $('.animator_list img').each(function(index) {
    var userbar_id = $(this).attr('id').split('_')[1];
    userbars.push(userbar_id);
  });
  return userbars;
}
function moveUp(index) {
  $('.ub_up').each(function(index) {
    $(this).tipsy('hide');
  });
  getAnimatorList('moveUp', index);
}
function moveDown(index) {
  $('.ub_down').each(function(index) {
    $(this).tipsy('hide');
  });
  getAnimatorList('moveDown', index);
}
function deleteAnimator(index) {
  $('.delete_ub').each(function(index) {
    $(this).tipsy('hide');
  });
  getAnimatorList('delete', index);
}
function getAnimatorList(task, index) {
  $.getJSON(ajax_gateway, { p2: 'getAnimatorList', p3: task, p4: index }, function(json) {
    if(json.success) {
      $('.animator_list_wrapper').html(json.html);
      setAnimatorNumber(json.number);
      attachAnimatorTooltips();
    }
    else {
      alert(json.message);
    }
  });
}
function showExamples() {
  $('.animator_none').attr('src', 'images/animator_none.gif');
  $('.animator_fade').attr('src', 'images/animator_fade.gif');
  $('.animator_scroll').attr('src', 'images/animator_scroll.gif');
  $('.animator_examples').show();
  var targetOffset = $('.animator_examples').offset().top;
  $('html,body').animate({scrollTop: targetOffset}, 500);
}
/***** userbar animator end *****/

/***** top members list start *****/
function getTopMembersList(period) {
  $('.top_members_info').html('loading...');

  $.get(ajax_gateway, { p2: 'getTopMembersList', p3: period }, function(data) {
    $('.top_members_wrapper').html(data);
  });

  return false;
}
/***** top members list end *****/

/***** showroom suppary start *****/
function swapShowroomSummary(type) {
  $('.header .nav a').removeClass('highlight');
  $('#'+type).addClass('highlight');

  if(type == 'showroom_profile') {
    $('.showroom_summary .stats').hide();
    $('.showroom_summary .important_numbers').show();
    $('.showroom_summary .profile').show();
  }
  else if(type == 'showroom_stats') {
    $('.showroom_summary .important_numbers').hide();
    $('.showroom_summary .profile').hide();
    $('.showroom_summary .stats').show();
  }
  return false;
}
/***** showroom suppary end *****/

/***** usefull functions *****/
function goTo(link) {
  window.location = link;
}
function trim(value) {
  value = value.replace(/^\s+/,'');
  value = value.replace(/\s+$/,'');
  return value;
}
function disableEnterKey(e) {
  var key;
  if(window.event) {
    key = window.event.keyCode; //IE
  }
  else {
    key = e.which; //firefox
  }
  if(key == 13) {
    return false;
  }
  else {
    return true;
  }
}
/***** end usefull functions *****/

/***** adsense show/hide *****/
$(document).ready(function() {
  checkShowHideAdesense();
});
$(window).resize(function() {
  checkShowHideAdesense();
});
function checkShowHideAdesense() {
  if($('.show_ads .ad').length != 0) {
    $('.show_ads .ad').hide();
    var w = $("#middle_column .show_ads").width();
    if(w > 468) {
      $('.show_ads .ad').show();
    }
  };
}
/***** adsense show/hide end *****/
