function bbcode(clickedLink, targetFieldId, field) {

    var targetField = $('#' + targetFieldId);
    var addLength = 0;
    var alwaysDouble = false;
    var endField = field;

    switch (field) {
        case 'smilie' :
            field = clickedLink;
            endField = '';
            break;
        case 'b' :
        case 'i' :
        case 'u' :
        case 's' :
        case 'wiki' :
        case 'quote' :
        case 'youtube' :
        case 'img' :
        case 'code' :
        case 'url' :
        case 'sup' :
        case 'sub' :
            break;
        case 'size' :
        case 'color' :
        case 'colour' :
        case 'font' :
            if ($(clickedLink).val() == '0') {
                return false;
            }
            else {
                field = field + '=' + $(clickedLink).val();
                alwaysDouble = true;
                $(clickedLink).val(0);
            }
            break;
        case 'close' :
            $('#' + targetFieldId + ' img.clicked').trigger('click');
            return false;
            break;
        default :
            field = '';
    }

    var range = targetField.getSelection();

    if (field) {
        // if we're just inserting a single field (like a smilie)
        if (!endField) {
            targetField.replaceSelection(' ' + field + ' ', true);
            addLength = 2 + field.length;
        }
        else {
            // else if the user has made a textarea selection
            if (range.length > 0 || alwaysDouble) {
                targetField.replaceSelection('[' + field + ']' + range.text + '[/' + endField + ']', true);
                addLength = 5 + endField.length + field.length;
            }
            else {
                // else, no selection, must be a toolbar button (start or end)
                if ($(clickedLink).hasClass('clicked')) {
                    addLength = 3 + endField.length;
                    $(clickedLink).removeClass('clicked');
                    targetField.replaceSelection('[/' + endField + ']', true);
                }
                else {
                    addLength = 2 + field.length;
                    $(clickedLink).addClass('clicked');
                    targetField.replaceSelection('[' + field + ']', true);
                }
            }
        }
    }

    if (range.length > 0) {
        targetField.setSelection(range.start, range.end + addLength);
    }
    else {
        targetField.setSelection(range.end + addLength);
    }
    targetField.focus();

    return false;
}

function isInt(x) {
    var y=parseInt(x);
    if (isNaN(y)) return false;
    return x==y && x.toString()==y.toString();
}

function scalePostImages() {
// Dimensions plugin required for this

    $('img.pi').load(function(){

        var width = $(this).width();
        var height = $(this).height();

        if (!isNaN(height) && height > 0) {
            var ratio = (height / width);
            var new_width = $(window).width() - 220;

            if (new_width > 0 && width > new_width) {
                var new_height = (new_width * ratio);

                $(this).parents('a').bind('dblclick', function() {
                    location.href = $(this).attr('href');
                }).click( function() {
                    return false;
                });

                $(this).height(new_height).width(new_width).attr('title', 'Click to enlarge image.').click(function() {
                    if ($(this).hasClass('pi')) {
                    $(this).removeClass('pi')
                        .css('width', width).css('height', height).attr('title', 'Click to reduce image.');
                    }
                    else {
                        var new_width = $(window).width() - 220 - ($(this).parents('td').width() - $(this).width());
                        var new_height = (new_width * ratio);

                        $(this).addClass('pi')
                            .css('width', new_width).css('height', new_height)
                            .attr('title', 'Click to enlarge image.');
                    }

                });
            }
        }
    });
}

function uploadDifferentFile(id) {
    $('#' + id).replaceWith('<input id="' + id + '" tabindex="' + $(this).attr('tabindex') + '" name="' + id + '" type="file" />');
}

/* once the DOM has loaded */
$(document).ready(function(){

    scalePostImages();

    // fix the drop down menus in ie6
    if ($.browser.msie && $.browser.version <= 6) {
        $('.navie li').bind("mouseenter mouseleave", function(e){
            $(this).toggleClass("over");
        });
    }

    // add an effect to torrents and forums search
    $('.header-search').each(function() {
        $(this).addClass('empty').val($(this).attr('title'));
    }).bind('focus', function(){
        if ($(this).val() == $(this).attr('title')) {
            $(this).removeClass('empty').val('');
        }
    }).bind('blur', function(){
        if ($(this).val() == '') {
            $(this).addClass('empty').val($(this).attr('title'));
        }
    });

    // if the user has js enabled
    if ($("#page_js_enabled").val() != 'no') {

      // make errors appear static in the viewport rather than static on the page
      $("#errors").css("position", "fixed");
      $("#messages").css("position", "fixed");

      /* ajax the forms */
      if ($("#page_js_enabled").val() != 'partial') {
          ajaxForms();
          /* mark the page as js enabled */
          $("#page_js_enabled").val('true');
      }

      /* if experimental ajax history is enabled kick off the javascript */
      if ($('#page_history').val() != 'disable') {
        $.historyInit(pageload);
      }

      /* set some defaults for ajax behaviour */
      $.ajaxSetup( {
        timeout: 30000
      } );

      $("#page_ajax_message").ajaxStart(function(){
        $(this).removeClass().html('<img src="' + STATICURL + 'img/ajax-loader.gif" /> Loading...').show();
        $.blockUI({ overlayCSS: { backgroundColor: 'transparent' }, message: null, fadeOut: 0 });
      }).ajaxSuccess(function(){
        $.unblockUI();
        $(this).hide();
      }).ajaxError(function(){
        $.unblockUI();
        $(this).addClass('error').html('<img src="' + STATICURL + 'img/ajax-loader.gif" /> Error retrieving data!').fadeOut(2500);
      });

    }
});

/* make the page form submit via ajax */
function ajaxForms() {
    $('#page_form').ajaxForm({ dataType: 'xml', beforeSubmit: ajaxSubmit });
}

function ajaxSubmit(formData, jqForm, options) {

    if ($('#page_history').val() != 'disable') {
        $.historyLoad('?' + $.param(formData));
        return false;
    }
}

/* all links with a class of g are made ajax'd */
function ajaxLinks() {
  if ($("#page_js_enabled").val() != 'no') {
      $('a.g').each(function(i){
        var link = this.href;
        var linkSplit = link.split('#',2);
        var linkQuery = linkSplit[0].split('?',2);

        if (linkSplit[0] && linkQuery[0]) {
          $(this).removeClass("g");
          if (linkQuery[1]) {
              this.href = '#';
          }
          $(this).bind('click', function(){
            var postString = $('#page_form').formSerialize();
            var queryString = '?' + postString;
            if (linkQuery[1]) {
                queryString = linkQuery[1].substr(0) + (postString == '' ? '' : '&') + postString;
            }

            if ($('#page_history').val() != 'disable') {
              $.historyLoad('?' + queryString);
            }
            else {
              $.post(linkQuery[0], queryString);
            }
            return false;
          });
        }
      });
    }
}

function ajaxTable() {
  if ($("#page_js_enabled").val() != 'no') {
      $('a.h').each(function(i){
        var link = this.href;
        var linkSplit = link.split('#',2);
        var linkQuery = linkSplit[0].split('?',2);

        if (linkSplit[0] && linkQuery[1]) {
          $(this).removeClass("h");
          this.href = '#';
          $(this).bind('click', function(){
            var queryString = linkQuery[1].substr(0);

            $.post(BASEURL + 'empty/', queryString + '&page_js_enabled=true');
            return false;
          });
        }
      });
    }
}

/* animate to the field */
function animateTo(target) {
    if (target == 'top') {
        target = $('body');
    }
    else {
        target = $('#' + target);
    }
    if (target.length) {
        var targetOffset = target.offset().top;
        $('html,body').animate({scrollTop: targetOffset}, 'fast');
    }
}

/* binds a click event to inline edit field buttons */
function ajaxInlineEdit() {
  $('.g_edit').each(function(i){
    var id = this.id;
    var idSplit = id.split("-",2);
    var id = idSplit[0];
    if (id) {
      $(this).bind('click', function(){
        $('#' + id + '-edit').hide();
        $('#' + id + '-span').hide();
        $('#' + id + '-save').show();
        $('#' + id + '-cancel').show();
        $('#' + id + '-input').show();
        return false;
      });
    }
  });

  $('.g_cancel').each(function(i){
    var id = this.id;
    var idSplit = id.split("-",2);
    var id = idSplit[0];
    if (id) {
      $(this).bind('click', function(){
        $('#' + id + '-edit').show();
        $('#' + id + '-span').show();
        $('#' + id + '-save').hide();
        $('#' + id + '-cancel').hide();
        $('#' + id + '-input').hide();
        return false;
      });
    }
  });
}

/* part of experimental ajax history */
function enableAjaxHistory() {
    $('#page_history').val('active');
}
function pageload(hash) {
    if(hash) {
        hash = hash.replace(/^\?/, '');
        $.post($('#page_form').attr('action'), hash);
	}
	else {
	    if ($('#page_history').val() == 'active') {
    	    $.post($('#page_form').attr('action'), 'site_start=true&page_js_enabled=true');
    	}
	}
}

/* tick and untick checkboxes */
function checkCheckboxes (cssid, mode) {
	var mode = mode || 'on';
	$('#' + cssid + ' input[type=checkbox]').each(function() {
		switch(mode) {
		case 'on':
			this.checked = true;
			break;
		case 'off':
			this.checked = false;
			break;
		case 'toggle':
			this.checked = !this.checked;
			break;
		}
	});
};