

String.prototype.stripHtml = function() { val = this; val = val.replace(/<[^>]+>/gim, ""); val = val.replace(/<\/[^>]+>/gim, ""); val = val.replace(/&nbsp;/gim, ""); return val; }
String.prototype.ltrim = function() { return this.replace(/^\s+/,""); }
String.prototype.rtrim = function() { return this.replace(/\s+$/,""); }
String.prototype.trim = function() { return this.replace(/^\s*([\S\s]*?)\s*$/, '$1'); }




/* checkbox */
jQuery.fn.checkbox = function(opt){
   jQuery(":checkbox", this)

       // Hide each native checkbox
       .hide()

       // Iterate through checkboxes and do all the magical stuff
       .each(function (){

           jQuery("<img>")

               // Set image attributes
               .attr({src: this.checked ? opt.checked : opt.unchecked, alt: "" })

               //
               .click(function() {
                   jQuery(this).checkboxToggle(opt);
               })

               // Attach image
               .insertBefore(this);
       });
}

jQuery.fn.cssCheckboxToggle = function(){
   jQuery(this).each(function(){
      var label = jQuery(this);
      label.toggleClass("checked");
      var check = jQuery(":checkbox[@name='"+label.attr("for")+"']")[0];
      check.checked = !check.checked;
   });
}

jQuery.fn.cssCheckboxCheck = function(){
   jQuery(this).each(function(){
      var label = jQuery(this);
      label.addClass("checked");
      var check = jQuery(":checkbox[@name='"+label.attr("for")+"']")[0];
      check.checked = true;
   });
}

jQuery.fn.cssCheckboxUncheck = function(){
   jQuery(this).each(function(){
      var label = jQuery(this);
      label.removeClass("checked");
      var check = jQuery(":checkbox[@name='"+label.attr("for")+"']")[0];
      check.checked = false;
   });
}

jQuery.fn.cssCheckbox = function(){
   jQuery(":checkbox", this)

       // Hide native checkboxes
       .hide()

       // Find related labels and add all the fancy stuff
       .each(function(){

           var check = this;
           var jlabel = jQuery("label[@for='"+jQuery(check).attr("name")+"']");

           // Initial state check
           if (check.checked) {
               jlabel.addClass("checked");
           }

           jlabel
               // Label hover state
               .hover(
                   function() { jQuery(this).addClass("over"); },
                   function() { jQuery(this).removeClass("over"); }
               )

               // Label click state
               .click(function(){
                   jQuery(this).cssCheckboxToggle();
               });
       });
}

jQuery.fn.extend({
    everyTime: function(interval, label, fn, times, belay) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times, belay);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.extend({
    timer: {
        guid: 1,
        global: {},
        regex: /^([0-9]+)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseInt(result[1], 10);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times, belay) {
            var counter = 0;
            
            if (jQuery.isFunction(label)) {
                if (!times) 
                    times = fn;
                fn = label;
                label = interval;
            }
            
            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
                return;

            if (times && times.constructor != Number) {
                belay = !!times;
                times = 0;
            }
            
            times = times || 0;
            belay = belay || false;
            
            if (!element.$timers) 
                element.$timers = {};
            
            if (!element.$timers[label])
                element.$timers[label] = {};
            
            fn.$timerID = fn.$timerID || this.guid++;
            
            var handler = function() {
                if (belay && this.inProgress) 
                    return;
                this.inProgress = true;
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
                this.inProgress = false;
            };
            
            handler.$timerID = fn.$timerID;
            
            if (!element.$timers[label][fn.$timerID]) 
                element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
            
            if ( !this.global[label] )
                this.global[label] = [];
            this.global[label].push( element );
            
        },
        remove: function(element, label, fn) {
            var timers = element.$timers, ret;
            
            if ( timers ) {
                
                if (!label) {
                    for ( label in timers )
                        this.remove(element, label, fn);
                } else if ( timers[label] ) {
                    if ( fn ) {
                        if ( fn.$timerID ) {
                            window.clearInterval(timers[label][fn.$timerID]);
                            delete timers[label][fn.$timerID];
                        }
                    } else {
                        for ( var fn in timers[label] ) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }
                    
                    for ( ret in timers[label] ) break;
                    if ( !ret ) {
                        ret = null;
                        delete timers[label];
                    }
                }
                
                for ( ret in timers ) break;
                if ( !ret ) 
                    element.$timers = null;
            }
        }
    }
});

if (jQuery.browser.msie)
    jQuery(window).one("unload", function() {
        var global = jQuery.timer.global;
        for ( var label in global ) {
            var els = global[label], i = els.length;
            while ( --i )
                jQuery.timer.remove(els[i], label);
        }
    });



/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object    settings    hash with options, described below.
 *                                scrollbarWidth    -    The width of the generated scrollbar in pixels
 *                                scrollbarMargin    -    The amount of space to leave on the side of the scrollbar in pixels
 *                                wheelSpeed        -    The speed the pane will scroll in response to the mouse wheel in pixels
 *                                showArrows        -    Whether to display arrows for the user to scroll with
 *                                arrowSize        -    The height of the arrow buttons if showArrows=true
 *                                animateTo        -    Whether to animate when calling scrollTo and scrollBy
 *                                dragMinHeight    -    The minimum height to allow the drag bar to be
 *                                dragMaxHeight    -    The maximum height to allow the drag bar to be
 *                                animateInterval    -    The interval in milliseconds to update an animating scrollPane (default 100)
 *                                animateStep        -    The amount to divide the remaining scroll distance by when animating (default 3)
 *                                maintainPosition-    Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *                                scrollbarOnLeft    -    Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */
jQuery.jScrollPane = {
    active : []
};
jQuery.fn.jScrollPane = function(settings)
{
    settings = jQuery.extend(
        {
            scrollbarWidth : 10,
            scrollbarMargin : 5,
            wheelSpeed : 18,
            showArrows : false,
            arrowSize : 0,
            animateTo : true,
            dragMinHeight : 1,
            dragMaxHeight : 99999,
            animateInterval : 100,
            animateStep: 3,
            maintainPosition: true,
            scrollbarOnLeft: false
        }, settings
    );
    return this.each(
        function()
        {
            var $this = jQuery(this);
            
            if (jQuery(this).parent().is('.jScrollPaneContainer')) {
                var currentScrollPosition = settings.maintainPosition ? $this.offset().top - jQuery(this).parent().offset().top : 0; //{relativeTo:jQuery(this).parent()[0]}
                
                //Debug.dump([$this.offset().top, jQuery(this).parent().offset().top], currentScrollPosition);
                var $c = jQuery(this).parent();
                var paneWidth = $c.innerWidth();
                var paneHeight = $c.outerHeight();
                var trackHeight = paneHeight;
                if ($c.unmousewheel) {
                    $c.unmousewheel();
                }
                jQuery('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown', $c).remove();
                $this.css({'top':0});
            } else {
                var currentScrollPosition = 0;
                this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
                this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
                var paneWidth = $this.innerWidth();
                var paneHeight = $this.innerHeight();
                var trackHeight = paneHeight;
                $this.wrap(
                    jQuery('<div></div>').attr(
                        {'class':'jScrollPaneContainer'}
                    ).css(
                        {
                            'height':paneHeight+'px', 
                            'width':paneWidth+'px',
                            'overflow': 'hidden'
                        }
                    )
                );
                // deal with text size changes (if the jquery.em plugin is included)
                // and re-initialise the scrollPane so the track maintains the
                // correct size
                jQuery(document).bind(
                    'emchange', 
                    function(e, cur, prev)
                    {
                        $this.jScrollPane(settings);
                    }
                );
            }
            
            var p = this.originalSidePaddingTotal;
            
            var cssToApply = {
                'height':'auto',
                'width':paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p + 'px'
            }

            if(settings.scrollbarOnLeft) {
                cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
            } else {
                cssToApply.paddingRight = settings.scrollbarMargin + 'px';
            }

            $this.css(cssToApply);

            var contentHeight = $this.outerHeight();
            var percentInView = paneHeight / contentHeight;

            if (percentInView < .99) {
                var $container = $this.parent();
                $container.append(
                    jQuery('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
                        jQuery('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
                            jQuery('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
                            jQuery('<div></div>').attr({'className':'jScrollPaneDragHandler'}).css({'width':settings.scrollbarWidth+'px'}).append(jQuery('<div></div>').attr({'className':'jScrollPaneDragHandlerC'})),
                            jQuery('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
                        )
                    )
                );
                
                var $track = jQuery('>.jScrollPaneTrack', $container);
                var $drag = jQuery('>.jScrollPaneTrack .jScrollPaneDrag', $container);
                
                if (settings.showArrows) {
                    
                    var currentArrowButton;
                    var currentArrowDirection;
                    var currentArrowInterval;
                    var currentArrowInc;
                    var whileArrowButtonDown = function()
                    {
                        if (currentArrowInc > 4 || currentArrowInc%4==0) {
                            positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
                        }
                        currentArrowInc ++;
                    };
                    var onArrowMouseUp = function(event)
                    {
                        jQuery('html').unbind('mouseup', onArrowMouseUp);
                        currentArrowButton.removeClass('jScrollActiveArrowButton');
                        clearInterval(currentArrowInterval);
                        //console.log($(event.target));
                        //currentArrowButton.parent().removeClass('jScrollArrowUpClicked jScrollArrowDownClicked');
                    };
                    var onArrowMouseDown = function() {
                        //console.log(direction);
                        //currentArrowButton = $(this);
                        jQuery('html').bind('mouseup', onArrowMouseUp);
                        currentArrowButton.addClass('jScrollActiveArrowButton');
                        currentArrowInc = 0;
                        whileArrowButtonDown();
                        currentArrowInterval = setInterval(whileArrowButtonDown, 100);
                    };
                    $container
                        .append(
                            jQuery('<a></a>')
                                .attr({'href':'javascript:;', 'className':'jScrollArrowUp'})
                                .css({'width':settings.scrollbarWidth+'px'})
                                .html('Scroll up')
                                .bind('mousedown', function()
                                {
                                    currentArrowButton = jQuery(this);
                                    currentArrowDirection = -1;
                                    onArrowMouseDown();
                                    this.blur();
                                    return false;
                                }),
                            jQuery('<a></a>')
                                .attr({'href':'javascript:;', 'className':'jScrollArrowDown'})
                                .css({'width':settings.scrollbarWidth+'px'})
                                .html('Scroll down')
                                .bind('mousedown', function()
                                {
                                    currentArrowButton = jQuery(this);
                                    currentArrowDirection = 1;
                                    onArrowMouseDown();
                                    this.blur();
                                    return false;
                                })
                        );
                    var $upArrow = jQuery('>.jScrollArrowUp', $container);
                    var $downArrow = jQuery('>.jScrollArrowDown', $container);
                    if (settings.arrowSize) {
                        trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
                        $track
                            .css({'height': trackHeight+'px', top:settings.arrowSize+'px'})
                    } else {
                        var topArrowHeight = $upArrow.height();
                        settings.arrowSize = topArrowHeight;
                        trackHeight = paneHeight - topArrowHeight - $downArrow.height();
                        $track
                            .css({'height': trackHeight+'px', top:topArrowHeight+'px'})
                    }
                }
                
                var $pane = jQuery(this).css({'position':'absolute', 'overflow':'visible'});
                
                var currentOffset;
                var maxY;
                var mouseWheelMultiplier;
                // store this in a seperate variable so we can keep track more accurately than just updating the css property..
                var dragPosition = 0;
                var dragMiddle = percentInView*paneHeight/2;
                
                // pos function borrowed from tooltip plugin and adapted...
                var getPos = function (event, c) {
                    var p = c == 'X' ? 'Left' : 'Top';
                    return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
                };
                
                var ignoreNativeDrag = function() {    return false; };
                
                var initDrag = function()
                {
                    ceaseAnimation();
                    currentOffset = $drag.offset(false);
                    currentOffset.top -= dragPosition;
                    maxY = trackHeight - $drag[0].offsetHeight;
                    mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
                };
                
                var onStartDrag = function(event)
                {
                    initDrag();
                    dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
                    jQuery('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
                    if (jQuery.browser.msie) {
                        jQuery('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
                    }
                    return false;
                };
                var onStopDrag = function()
                {
                    jQuery('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
                    dragMiddle = percentInView*paneHeight/2;
                    if (jQuery.browser.msie) {
                        jQuery('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
                    }
                };
                var positionDrag = function(destY)
                {
                    destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
                    ScrollInfo.dragPosition = dragPosition = destY;
                    //Debug.dump([dragPosition, paneHeight, contentHeight]);
                    $drag.css({'top':destY+'px'});
                    var p = destY / maxY;
                    $pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
                    $this.trigger('scroll');
                    if (settings.showArrows) {
                        $upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
                        $downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
                    }
                };
                var updateScroll = function(e)
                {
                    positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
                };
                
                var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
                
                $drag.css(
                    {'height':dragH+'px'}
                ).bind('mousedown', onStartDrag);
                
                var dragTopH = jQuery('.jScrollPaneDragTop', $drag).height();
                var dragBottomH = jQuery('.jScrollPaneDragBottom', $drag).height();
                
                var dragHandler = jQuery('.jScrollPaneDragHandler', $drag);
                var dragHandlerH = dragH - Math.abs(dragTopH + dragBottomH);
                dragHandler.css(
                    {
                        'height' : dragHandlerH + 'px',
                        'top' : dragTopH + 'px'
                    }
                );
                
                var dragHandlerC = jQuery('.jScrollPaneDragHandlerC', $drag);
                var dragHandlerCT = Math.round(dragHandlerH / 2) - Math.round(dragHandlerC.height() / 2);
                var dragHandlerCL = Math.floor(dragHandler.width() / 2) - Math.round(dragHandlerC.width() / 2);
                dragHandlerC.css(
                    {
                        'top' : dragHandlerCT + 'px',
                        'left' : dragHandlerCL + 'px'
                    }
                );
                
                var trackScrollInterval;
                var trackScrollInc;
                var trackScrollMousePos;
                var doTrackScroll = function()
                {
                    if (trackScrollInc > 8 || trackScrollInc%4==0) {
                        positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
                    }
                    trackScrollInc ++;
                };
                var onStopTrackClick = function()
                {
                    clearInterval(trackScrollInterval);
                    jQuery('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
                };
                var onTrackMouseMove = function(event)
                {
                    trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
                };
                var onTrackClick = function(event)
                {
                    initDrag();
                    onTrackMouseMove(event);
                    trackScrollInc = 0;
                    jQuery('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
                    trackScrollInterval = setInterval(doTrackScroll, 100);
                    doTrackScroll();
                };
                
                $track.bind('mousedown', onTrackClick);
                
                // if the mousewheel plugin has been included then also react to the mousewheel
                if ($container.mousewheel) {
                    $container.mousewheel(
                        function (event, delta) {
                            initDrag();
                            ceaseAnimation();
                            var d = dragPosition;
                            positionDrag(dragPosition - delta * mouseWheelMultiplier);
                            var dragOccured = d != dragPosition;
                            return !dragOccured;
                        },
                        false
                    );                    
                }
                var _animateToPosition;
                var _animateToInterval;
                function animateToPosition()
                {
                    var diff = (_animateToPosition - dragPosition) / settings.animateStep;
                    if (diff > 1 || diff < -1) {
                        positionDrag(dragPosition + diff);
                    } else {
                        positionDrag(_animateToPosition);
                        ceaseAnimation();
                    }
                }
                var ceaseAnimation = function()
                {
                    if (_animateToInterval) {
                        clearInterval(_animateToInterval);
                        delete _animateToPosition;
                    }
                };
                var scrollTo = function(pos, preventAni)
                {
                    if (typeof pos == "string") {
                        $e = jQuery(pos, this);
                        if (!$e.length) return;
                        pos = $e.offset().top - $this.offset().top;
                    }
                    ceaseAnimation();
                    var destDragPosition = -pos/(paneHeight-contentHeight) * maxY;
                    //Debug.dump(['new', pos, destDragPosition, paneHeight, contentHeight, maxY]);
                    if (preventAni || !settings.animateTo) {
                        positionDrag(destDragPosition);
                    } else {
                        _animateToPosition = destDragPosition;
                        _animateToInterval = setInterval(animateToPosition, settings.animateInterval);
                    }
                };
                $this[0].scrollTo = scrollTo;
                
                $this[0].scrollBy = function(delta)
                {
                    var currentPos = -parseInt($pane.css('top')) || 0;
                    scrollTo(currentPos + delta);
                };
                
                initDrag();
                
                //Debug.dump(currentScrollPosition);
                
                scrollTo(-currentScrollPosition, true);
                
                jQuery.jScrollPane.active.push($this[0]);

            } else {
                $this.css(
                    {
                        'height':paneHeight+'px',
                        'width':paneWidth-this.originalSidePaddingTotal+'px',
                        'padding':this.originalPadding
                    }
                );
                // remove from active list?
            }
            
        }
    )
};

// clean up the scrollTo expandos
jQuery(window)
    .bind('unload', function() {
        var els = jQuery.jScrollPane.active; 
        for (var i=0; i<els.length; i++) {
            els[i].scrollTo = els[i].scrollBy = null;
        }
    }
);


function ScrollInfo(){
    this.dragPosition = 0;
}

var ScrollInfo = new ScrollInfo();


        
function toggle_postform(id) {
    var post = document.getElementById(id);
    var postdiv = post.childNodes[post.childNodes.length-1];
    if(!document.all)
        postdiv = post.childNodes[post.childNodes.length-2];
    if(postdiv.innerHTML != undefined && postdiv.innerHTML != "") {
       postdiv.innerHTML = "";
       return false;
    }
    var form = document.getElementById("idMBPostForm");
    postdiv.innerHTML = '<div class="mb-post-form">'+form.innerHTML+'</div>';
    // hidden
    if(document.all && document.selection && !window.opera)
        postdiv.childNodes[0].childNodes[0].elements['mb_parentid'].value = id;
    else
        postdiv.childNodes[0].childNodes[1].elements['mb_parentid'].value = id;
    
    return false;
}

function ClearValue(obj, checkTo){
    if (obj.value == checkTo)
        obj.value = "";
}

function ChangeValue(obj, checkTo, type){
    var compare = type ? "" : checkTo;
    var newValue = type ? checkTo : "";
    if (obj.tagName == "textarea"){
        if (obj.innerHTML == compare)
            obj.innerHTML = newValue;
    } else if (obj.value == compare)
            obj.value = newValue;
}


function AjaxRequest(cmd, data, callback, nocache, async) {
    data.cmd = cmd;
    return $.ajax({
        url: "/ajax.php",
        cache: nocache,
        timeout: 10000, 
        data: data, 
        type: "POST",
        processData: true,
        async: async != undefined ? async : false,
        time: new Date(),
        success: callback
    });
}

function AjaxRunTemplate(prefix, object, template, args, callback) {
    args.cmd = prefix+':'+object+'.'+template;
    return $.ajax({
        url: "/ajax.php",
        cache: false,
        timeout: 10000, 
        data: args, 
        type: "POST",
        processData: true,
        async: true,
        time: new Date(),
        success: callback
    });
}

var op = function(src, width, height) {
    if(!width) width = 800;
    if(!height) height=600;
    window.open('/image.php?src=' + src, 'image', 'width='+width+',height='+height+',status=no,address=no,scrollbars=yes');
}


