var popWin = ''; // set the top variable to know if we're the parent or child pop up
var RecaptchaOptions = { theme : 'clean' };

$(document).ready(function(){

    // browser sepecific fixes
    if( (   // show the old browser message for
            ( $.browser.msie    && parseFloat($.browser.version) < 7 )   ||     // < ie 7
            ( $.browser.webkit  && parseFloat($.browser.version) < 300 ) ||     // < safari 3
            ( $.browser.opera   && parseFloat($.browser.version) < 9 )   ||     // < opera 9
            ( $.browser.mozilla && parseFloat($.browser.version) < 1.9 )        // < ff 2
        )
    ) { $('#old-browser').show(); }

    // fix evaluated overlay in ie < 8
    if( $.browser.msie && parseFloat($.browser.version) < 8 && $('#evaluated').length > 0 ) {
        $('#evaluated').css({height : $('#evaluated').parent().outerHeight() + 'px', width : $('#evaluated').parent().outerWidth() + 'px', left : '0px', marginLeft : '0px'});
    }

    // add js validation for these forms
    $('form.admin-form:not(#edit-fieldnotes), #comment-form, #sign-up-form').lb_validate();

    // jAlert if there's a status message
    if( $('.status-message').length )
        jAlert($('.status-message').html());

    // TIMELINE
    if( $('#timeline .block, #timeline2 .blok').length > 4 && parseInt($('#slide-timeline').css('marginLeft')) < 0 ){
        var mrginLeft = parseInt($('#timeline-selection').css('marginLeft'));
            mrginLeft -= parseInt($('#slide-timeline').css('marginLeft')) - 4;
            $('#timeline-selection').css({ 'marginLeft' : mrginLeft + 'px' })
    }

    var phases           = $('#timeline .block, #timeline2 .blok')
    var number_of_phases = phases.length;
    var current_phase    = false;
    var max_percentage   = 0;

    phases.each(function(i){
        var percent = parseInt($(this).css('backgroundPosition').split('% ')[0]);

        current_phase   = ( max_percentage && percent <= max_percentage ? i : current_phase );
        max_percentage  = ( max_percentage > percent ? max_percentage : percent);

        percent         = (-(percent/100) * $(this).width()) + 940;

        $(this).css({ backgroundPosition : '-940px 50%' });
        $(this).css({ backgroundPosition : -percent + 'px 50%' }, 1000);
    });

    if( $('h1#sony-header').length ) {
        $('#timeline2 .blok span.text').each(function(){
                $(this).text($(this).text().replace('Announced', ''));
        });

        $('#timeline2 .blok h3').each(function(){
            if( $(this).height() < 25 )
                $(this).css({ paddingBottom : '10px' });
        });
    }

    /* ie7 timeline fix */
    if ( $('#timeline-window').length && $.browser.msie ) {

          if( parseFloat($.browser.version) < 8  ) {
              $('#timeline-window').hide().after('<div id="ie7-left-timeline-border"></div><div id="ie7-right-timeline-border"></div><div id="ie7-top-timeline-border"></div><div id="ie7-bot-timeline-border"></div>');
          }
          
          var width = $('#timeline .block a').eq(0).width();
          var height = $('#timeline .block a').eq(0).height();
          $('#timeline .block a').append('<span class="background-layer" style="width : ' + width + 'px; height : ' + height + 'px">&nbsp;</span>')
    }
    /* ie7 timeline fix end */

    if( $('#slide-timeline').length ) {
        var width = 0;
        
        $('#timeline .block, #timeline2 .blok').each(function(){
            width += $(this).outerWidth();
        });

        width += 100;

        $('#timeline #slide-timeline').width(width).css({ overflow : 'hidden'});
        
        if( $('#timeline .block').length > 4 )
            $('#timeline-window').before('<a href="#" class="go-left"></a><a href="#" class="go-right"></a>');
        
        $('.go-right').click(function(){
            var blocks = $('#timeline .block');
            var slider = $('#timeline #slide-timeline');
            var width_of_block = $('#timeline .block').eq(0).width();
            var position = 0;
            var blocks_to_see = 4;

            blocks.each(function(i){
                if( $(this).hasClass('current-pos') ) {
                    $(this).removeClass('current-pos');
                    position = i+1;
                }
            });
            
            var moveto = -width_of_block * position;

            if( moveto > ( -width_of_block * (blocks.length - (blocks_to_see-1)) ) ) {

                $('#timeline-window').css({ zIndex : 6 });
                slider.animate({ 'marginLeft' : moveto + 'px' }, function() { $('#timeline-window').css({ zIndex : 1 }); });
                blocks.eq(position).addClass('current-pos');

                if( moveto > -100 )
                    $('.go-left').hide();
                else
                    $('.go-left').show();

                if( moveto > ( -width_of_block * (blocks.length - (1+blocks_to_see)) ) && blocks.length > blocks_to_see )
                    $('.go-right').show();
                else
                    $('.go-right').hide();

                if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) < 10 ) {
                    $('#timeline-selection').addClass('select-1');
                }

                if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) < 800 &&
                    moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) > 0    ) {
                    $('#timeline #timeline-selection').fadeIn();
                }

                if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) > 800 ||
                    moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) < -10    ) {
                    $('#timeline #timeline-selection').hide();
                }

                if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) < 600 )
                    $('#timeline-selection').removeClass('t-end');
                else
                    $('#timeline-selection').addClass('t-end');
            }
            
            return false;

        });

        $('.go-left').click(function(){
            var blocks = $('#timeline .block');
            var slider = $('#timeline #slide-timeline');
            var width_of_block = $('#timeline .block').eq(0).width();
            var position = 0;
            var blocks_to_see = 5;

            blocks.each(function(i){
                if( $(this).hasClass('current-pos') ) {
                    $(this).removeClass('current-pos');
                    position = i-1;
                }
            });
            
            var moveto = -width_of_block * position;

            if( moveto <= 0 ) {
                
                $('#timeline-window').css({ zIndex : 6 });
                slider.animate({ 'marginLeft' : moveto + 'px' }, function(){ $('#timeline-window').css({ zIndex : 1 }); });
                blocks.eq(position).addClass('current-pos');

                if( moveto > -100 )
                    $('.go-left').hide();
                else
                    $('.go-left').show();

                if( moveto > ( -width_of_block * (blocks.length - blocks_to_see) ) && blocks.length > blocks_to_see )
                    $('.go-right').show();
                else
                    $('.go-right').hide();


                if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) > 50 ) {
                    $('#timeline-selection').removeClass('select-1');
                } else if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) > -50 ) {
                    $('#timeline #timeline-selection').fadeIn();
                }

                if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) > 800 ) {
                    $('#timeline #timeline-selection').hide();
                }

                if( moveto + parseInt($('#timeline #timeline-selection').css('marginLeft')) < 600 ) {
                    $('#timeline-selection').removeClass('t-end');
                } else {
                    $('#timeline-selection').addClass('t-end');
                }
            }
            
            return false;
        });
        
        if( parseInt($('#timeline #slide-timeline').css('marginLeft')) > -1 ) {
            $('.go-left').hide();
        }

        if( -parseInt($('#timeline #slide-timeline').css('marginLeft')) > ($('#timeline #slide-timeline').width()-($('#timeline .block').eq(0).width()*6)) -10 ) {
            $('.go-right').hide();
        }
        
        $('#timeline .block').each(function(i){
            var blocks_to_see = 5;
            if( i > (blocks_to_see-1) && $(this).hasClass('current-pos') ) {
                $(this).removeClass('current-pos');
                $('#timeline .block').eq(i-(blocks_to_see-1)).addClass('current-pos');
            } else if( $(this).hasClass('current-pos') ) {
                $(this).removeClass('current-pos');
                $('#timeline .block').eq(0).addClass('current-pos');
            }
        });
        
        if( $('#timeline-selection').length  )
            current_phase = parseInt($('#timeline-selection').attr('class').replace('select-', ''))-1;
    }
    
    $('#feedback-btn').click(function(){
        if( $(this).hasClass('logged-in-zen') ) {   // visit the page to make sure they're logged in
            $('#temp-zen-iframe').remove();
            if( navigator.userAgent.toLowerCase().indexOf('safari') > 0 && navigator.userAgent.toLowerCase().indexOf('chrome') < 0 ) {
                safari_zend_pop = window.open('/zendesk_login.html', 'safari_zend_pop', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=100,height=100');
                top.focus();
                setTimeout(function(){ safari_zend_pop.close() }, 15000);
            } else {
                $('body').append('<iframe src="/zendesk_login.html" id="temp-zen-iframe" style="display:none"></iframe>');
            }
        }

        Zenbox.show();  // show the zendesk frame

        return false;
    });
    
    if( $('#feedback-btn').length ) {
        $('#feedback').click(function(){
            $('#feedback-btn').click();
            return false;
        });
    }

    if( $('#how-it-works-page').length ) { // phase info for sony timelines
        $('#timeline2 a, #timeline a').hover(
            function(){
                $('#timeline2 a, #timeline a').removeClass('hovered');
                var trigger = $(this).addClass('hovered');
                var url = trigger.attr('href');
    
                if( !$('#phase-info').length ) {
                    $('body').prepend('<div id="phase-info"><h3>title</h3><div></div></div>');
    
                    $('#phase-info').hover(
                        function(){
                            $(this).addClass('ontop');
                        },
                        function(){
                            $(this).removeClass('ontop');
                            
                            setTimeout(function() {
                                if( !$('#timeline2 a.hovered, #timeline a.hovered').length )
                                    $('#phase-info').fadeOut(300);
                            }, 200);
                        }
                    )
                }
                
                $.getJSON(url + 'phase_summary.json', function(response) {
                    var left_post = ( trigger.offset().left + trigger.width() / 2 ) - ( $('#phase-info').width() / 2 );

                    if( left_post + $('#phase-info').width() >  ($(document).width()-200) ) {
                        left_post = ( trigger.offset().left + trigger.width() / 4 ) - ( $('#phase-info').width() / 2 );
                    }

                    $('#phase-info').delay(200).stop(true, true).animate({
                        top : (trigger.offset().top + trigger.outerHeight()) + 'px',
                        left : left_post + 'px'
                    }, 500, 'easeOutBack').fadeIn(300, function(){ $(this).css({opacity : 1 })});
                    
                    setTimeout(function(){
                                    if ( !trigger.hasClass('hovered') )
                                        $('#phase-info').stop(true, true);
                                }, 1000);

                    var position = 0;
                    var title = trigger.find('h3').text();

                    $('#timeline2 a h3, #timeline a h3').each(function(){
                        position++;
                        if( $(this).text() == title )
                            return false;
                    });

                    if( $('#phase-info h3').text() != 'Phase ' + position + ': ' + title ) {

                        $('#phase-info h3').delay(600).stop(true, true).fadeOut(200, function() {
                           
                            $(this).text('Phase ' + position + ': ' + title ).fadeIn(400, function(){ $(this).css({opacity : 1 })});
                        });
        
                        $('#phase-info div').delay(600).stop(true, true).fadeOut(200, function() {
                            $(this).html(response.summary).fadeIn(400, function(){ $(this).css({opacity : 1 }) });
                        });
                    }
                });
            },
            function() {
                $(this).removeClass('hovered');
            }
        );
        
        $('#timeline2, #timeline').hover(
            function() { },
            function() {
                setTimeout(function(){
                    if( !$('#phase-info').hasClass('ontop') )
                        $('#phase-info').fadeOut(300);
                }, 100);
            }
        );
    }
    // TIMELINE END

    $('.captcha-container').each(function(){
        if( $(this).parent().hasClass('error') )
            $(this).show();
    });


    // Suggest tags    
    $("#usertags-fill").fcbkcomplete({  // facebook complete widget init
        json_url        : '/suggested_tags',
        filter_case     : false,
        filter_hide     : true,
        firstselected   : true,
        filter_selected : true,
        newel           : true
    });

    if ( $("#usertags-fill").length && jQuery.trim($("#usertags-fill").val()) != '' ) {
        // set initial elements for suggested user tags
        var str = $("#usertags-fill").val();
            str = str.replace(/\'/g,'');        // strip slashes

        var pre_fill_auto = str.split(',');

        for( var i=0; i < pre_fill_auto.length; i++ )
            $("#usertags-fill").trigger('addItem', [{ 'title': pre_fill_auto[i], 'value': pre_fill_auto[i] }]);
    }

    $("#usertags-fill").trigger('initiated_true');
    // Suggest tags END

    $('.ajax-action').click(function(){
        var trigger = $(this);
        $.getJSON( $(this).attr('href').replace('.html', '.json'), function(response) {
            if( !trigger.hasClass('vote') )
                jAlert(response.status_message);
            
            if( trigger.hasClass('delete-question') )
                trigger.parent().fadeOut();

            if( trigger.hasClass('hide-after-action') )
                trigger.fadeOut();  
        });

         return false;
    });

    $('input.auto-fill').auto_fill();

    $('.mini-t-container').each(function(){
        if( !$('h1#sony-header').length )
            $(this).find('.mini-timeline').attr({ 'rel' : $(this).find('.mini-timeline').attr('rel').replace('openideo.com/sony/', 'openplanetideas.com/') });

        var url = $(this).find('.mini-timeline').attr('rel') + '?callback=?';

        var timeline = $(this);

        if( 106 % ($(this).find('.block').length)  > 0 ) {
            $(this).find('.block:last').css({ width : (parseInt($(this).find('.block:last').css('width')) + 2) + 'px', borderRight : '0px' })
        }

        try {
            $.get(url,{}, function(response) {
                timeline.find('.selected-pointer').text(response.current_phase);
                var selected_index = -1;
                var total_phases = response.phases.length;
                jQuery.each(response.phases, function(count, ob){
                    var bg_width = 106;
                    var bg_pos = ( ob.completed / 100 ) * parseInt(timeline.find('.block').css('width'));
                        bg_pos -= bg_width;
    
                    if( response.phases.length > 1 && ob.completed )
                        bg_pos+=2;
    
                    timeline.find('.block').eq(count).css({ backgroundPosition : '-106px 0px'}).addClass(ob.type).delay( ((count) * 600) + 900 ).animate({ backgroundPosition : bg_pos+'px 0px'}, 1000);
    
                    if( (ob.completed != 100 && selected_index < 0 && timeline.find('.selected-pointer').length) ||
                        (ob.completed == 100 && selected_index < 0 && response.phases.length == count+1) ) {
                        timeline.find('.selected-pointer').addClass(ob.type);
    
                        var new_pos = (timeline.find('.block').eq(count).outerWidth() * count) + (( ob.completed / 100 ) * timeline.find('.block').eq(count).width()) - 4;
                            if ( new_pos < 0 ) new_pos = 0;
    
                        if(  timeline.find('.selected-pointer').length ) {
                            var selected_point = timeline.find('.selected-pointer').eq(0);
    
                            if( typeof(selected_point.css('backgroundPosition')) == 'undefined' ) {
                                selected_point
                                .css({ 'background-position-x' : '0px' })
                                .delay(1000).animate({ 'background-position-x' : (new_pos < 102 ? new_pos : 102 ) + 'px'}, 1000+(600*count));
    
                            } else {
                                selected_point
                                .css({ 'backgroundPosition' : selected_point.css('backgroundPosition').replace('50%', '0px') })
                                .delay(1000).animate({ backgroundPosition : selected_point.css('backgroundPosition').replace('0px', (new_pos < 102 ? new_pos : 102 )  + 'px')}, 1000+(600*count));
                            }
                        }
    
                        selected_index = count;
                    }
                });
    
            }, 'json');
        } catch(err) {}
    });

    $('.switchable').click(function(){
        var trigger = $(this);
            trigger.addClass('selected');

        $('#' + $(this).attr('rel')).delay(1000).slideDown(function(){
            equate_heights();
        });

        trigger.siblings().each(function(){
            $(this).removeClass('selected');
            
            $('#' + $(this).attr('rel')).slideUp();
        });
    });

    $('.trigger').click(function(){
        var show_id = $(this).attr('rel');
        var trigger = $(this);
        var hide_id = false;
        // hide any other layer being shown
        $('.trigger').each(function(){
            hide_id = $(this).attr('rel');
            if( hide_id != show_id ) {
                $('#' + hide_id ).fadeOut();
            } else if( $(this).get(0) == trigger.get(0) && $('#' + show_id).css('display') == 'none' ) {
                $('#' + show_id ).fadeIn();
                $('#coverupper').fadeIn();
            } else if( $(this).get(0) == trigger.get(0) ) {
                $('#' + show_id ).fadeOut();
                $('#coverupper').fadeOut();
            }
        });

        return false;
    });
    
    $('.trigger.join-trigger').click(function(){
        var show_id = $(this).attr('rel');
        var trigger = $(this);
        var hide_id = false;
        var hide_slider_parent = true;

        // hide any other layer being shown
        $('.trigger-slider').each(function(){
            hide_id = $(this).attr('rel');
            if( hide_id != show_id ) {
                $('#' + hide_id ).animate({ right : '-300px' }, 500, 'easeOutBack', function(){ $(this).hide() });
            } else if( $(this).get(0) == trigger.get(0) && $('#' + show_id).css('display') == 'none' ) {
                $('#' + hide_id ).show().animate({ right : '80px' }, 500, 'easeOutBack');
                $('#sliders-container').show();
                hide_slider_parent = false;
                $('#' + hide_id + ' .autofocus').focus();

                if( hide_id == 'join-form' && $('h1#sony-header').length ) {
                    ebConversionTracker(77046);
                }

            } else if( $(this).get(0) == trigger.get(0) ) {
                $('#' + hide_id ).animate({ right : '-300px' }, 500, 'easeOutBack', function(){ $(this).hide() });
            }
        });
        
        if( hide_slider_parent ) { setTimeout(function(){$('#sliders-container').hide();}, 500); }
    });
    
    $('.themes').hover(
        function(){
            if( !$(this).find('.text').hasClass('showing') )
                $(this).find('.text').addClass('showing').animate({ height : '35px', marginTop : '-35px'}, 250);
        },
        function() {
            $(this).find('.text').animate({ height : '25px', marginTop : '-25px'}, 250, function(){ $(this).removeClass('showing') });
        }
    );

    $('.watch-how-it-works').fancybox({
        'speedIn'               :       600, 
        'speedOut'              :       200, 
        'overlayShow'   :       true,
        'type'          :   'swf',
        'width'         :   640,
        'height'        :   360,
        'centerOnScroll':   true,
        'titleShow'     :   false,
        'swf'                   : { 'allowfullscreen'   : 'true' }
    });

    $('.collab-map,.collab-map-challenge').fancybox({
        'speedIn'       :       600,
        'speedOut'      :       200,
        'overlayShow'   :       true,
        'type'          :   'swf',
        'width'         :   1000,
        'height'        :   700,
        'autoDimensions': false,
        'autoScale' : false,
        'centerOnScroll':   false,
        'titleShow'     :   false,
        'swf'           : { 'allowfullscreen'   : 'true' },
        'onStart'       : function(){ window.location = '#collaboration-map'},
        'onCleanup'     : function(){ window.location = '#'}
    });

    $('.theme-form-listing tr').click(function(){

        var input = $(this).find('input');
        if( input.attr('checked') )
            input.removeAttr('checked');
        else
            input.attr({'checked' : 'checked'});
    });

    $('.theme-form-listing tr input').click(function(e){
        e.stopPropagation();
    });
    
    $('.trigger-slider, #coverupper').click(function(){
        var show_id = $(this).attr('rel');
        var trigger = $(this);
        var hide_id = false;
        var hide_slider_parent = true;

        // hide any other layer being shown
        $('.trigger-slider').each(function(){
            hide_id = $(this).attr('rel');
            if( hide_id != show_id ) {
                $('#' + hide_id ).animate({ right : '-300px' }, 500, 'easeOutBack', function(){ $(this).hide() });
            } else if( $(this).get(0) == trigger.get(0) && $('#' + show_id).css('display') == 'none' ) {
                $('#' + hide_id ).show().animate({ right : '80px' }, 500, 'easeOutBack');
                $('#sliders-container').show();
                hide_slider_parent = false;
                $('#' + hide_id + ' .autofocus').focus();

                if( hide_id == 'join-form' && $('h1#sony-header').length ) {
                    ebConversionTracker(77046);
                }

            } else if( $(this).get(0) == trigger.get(0) ) {
                $('#' + hide_id ).animate({ right : '-300px' }, 500, 'easeOutBack', function(){ $(this).hide() });
            }
        });
        
        if( hide_slider_parent ) { setTimeout(function(){$('#sliders-container').hide();}, 500); }

        return false;
    });

    $('#coverupper').click(function(){
        $('.trigger').each(function(){
            var hide_id = $(this).attr('rel');
            $('#' + hide_id).fadeOut();
        });
        $('#coverupper').fadeOut();
        
        return false;
    });
    
    $(document).keyup(function(e){
        var keycode = false;
        if (e == null) { // ie 
            keycode = event.keyCode; 
        } else { // mozilla 
            keycode = e.which; 
        }

        if( keycode == 27) $('#coverupper').click();
    });

    $('.close-btn').click(function(){
        $('a[rel=' + $(this).parent().attr('id') + ']').eq(0).click(); return false;
        if( $('a[rel=' + $(this).parent().attr('id') + ']').eq(0).hasClass('trigger') ) {
            $(this).parent().fadeOut();
            $('#coverupper').fadeOut();
        } else {}

        return false;
    });

    $('.show-hide-parent a.trigger').click(function(){      // show and hiders
        if( $(this).hasClass('selected') ){
            $(this).removeClass('selected').next().slideUp();
        } else {
            $(this).addClass('selected').next().slideDown();
        }
        
        return false;
    });

    $('#comments textarea').focus(function(){
        if( jQuery.trim($(this).val()) == 'Write a reply' )
            $(this).val('');

        $(this).closest('form').addClass('active').removeClass('not-active');
    });

    $('#comments textarea').blur(function(){
        if( jQuery.trim($(this).val()) == 'Write a reply' || jQuery.trim($(this).val()) == '' ) {
            $(this).val('Write a reply');
            $(this).closest('form').addClass('not-active').removeClass('active');
        }
    });
    
    $('#comments form').addClass('loaded');

    $('#comment-form textarea').attr({ alt : 'Write a comment' }).val('Write a comment').auto_fill().blur(function(){ if( jQuery.trim($(this).val()) == '' || jQuery.trim($(this).val()) == 'Write a comment' )$(this).css({ fontStyle : 'italic' }) }).focus(function(){ $(this).css({ fontStyle : 'normal' }) });

    $('#dq-chart-privacy a, #dq-table-privacy a').click(function(){
        $(this).addClass('selected').siblings().removeClass('selected');

        $('#dq-chart-privacy a, #dq-table-privacy a').each(function(){
            $(this).text( $(this).text().replace('make ', '') );
        });

        $('#dq-chart-privacy a:not(.selected), #dq-table-privacy a:not(.selected)').each(function(){
            $(this).text( 'make ' + $(this).text() );
        });
        var show_graph  =  $('#dq-chart-privacy a.selected').text() == 'public' ? 'True' : 'False';
        var show_values =  $('#dq-table-privacy a.selected').text() == 'public' ? 'True' : 'False';

        $.getJSON($(this).attr('href'), { 'show_graph' : show_graph, 'show_values' : show_values }, function(response) {
            jAlert(response.status_message);
        });
        return false;
    });

    $(window).load(function() {    /* equal height */
        equate_heights();
    });

    $('.flag, a.report').click(function(){                            // comment flagging
        // must check if logged in first i guess
        var url     = $(this).attr('href');
        var title   = $(this).attr('title');
        var trigger = $(this);

        jConfirm('You are about to report this item for questionable or offensive content. Are you sure you want to report this?', 'Confirm', function(accept) {
            if( accept ) {
                 $.getJSON(url.replace('.html', '.json'), { ajax : true }, function(response) {
                    jAlert(response.status_message);
                    trigger.fadeOut();
                    trigger.siblings().fadeIn();
                });
            }
        });

        return false;
    });

    $('.delete-comment').click(function(){                            // comment flagging
        // must check if logged in first i guess
        var url     = $(this).attr('href').replace('.html', '.json').replace('#comment-', 'comments/').replace('delete.json', '\/delete.json');
        var title   = $(this).attr('title');
        var trigger = $(this);

        jConfirm('Are you sure you want to ' + title, 'Confirm', function(accept) {
            if( accept ) {
                 $.getJSON(url, { ajax : true }, function(response) {
                    jAlert(response.status_message);
                    
                    var to_hide = (trigger.parent()[0].nodeName == 'TD' || trigger.parent()[0].nodeName == 'td') ? trigger.parent().parent() : trigger.closest('.comment');

                    if ( parseInt(to_hide.css('marginLeft')) < 10 ) { // this is a parent comment, hide the children and form
                        to_hide.nextUntil('form').fadeOut(function(){ $(this).remove() });
                        to_hide.siblings('form').eq(0).fadeOut(function(){ $(this).remove() });
                    }

                    to_hide.fadeOut(function(){ $(this).remove() });
                });
            }
        });

        return false;
    });


    $('.button.delete').click(function(){                            // comment flagging
        var url = $(this).attr('href');
        // must check if logged in first i guess
        jConfirm('Are you sure you want to delete this? There is no undo for this option.', 'Confirm', function(accept) {
            if( accept ) {
                window.location = url;
            } else {
                return false;
            }
        });
        return false;
    });

    $('.vote-listing:not(.applauded), .vote-action').click(function() {
        var trigger = $(this);
        var url     = trigger.attr('href');
        var title   = trigger.attr('title');
    
        var accepted_item = trigger.siblings('.accept_tnc_vote');   // in search listings

        if( !accepted_item.length ) {                                // in actual page
            accepted_item = $('.accept_tnc_vote_in_phase');
        }

        if( accepted_item.length && accepted_item.val() != 'accepted' ) {    // check if the challenge this belongs to has had its tncs accepted
            accepted_item = accepted_item.eq(0);
            
            
            accepted_item.addClass('accept-tnc-before-voting');
            trigger.addClass('accept-tnc-before-voting-trigger');
     
            $.fancybox({
                'href'          :   accepted_item.val(),
                'type'          :   'iframe',
                'speedIn'       :       600, 
                'speedOut'      :       200, 
                'autoScale'     :   false,
                'overlayShow'   :       true,
                'width'         :   530,
                'height'        :   460,
                'centerOnScroll':   false,
                'titleShow'     :   false,
                'onClosed'              : function() {
                    accepted_item.removeClass('accept-tnc-before-voting');
                    trigger.removeClass('accept-tnc-before-voting-trigger');
                }
            });

            return false;
        }

        $.getJSON(url.replace('.html', '.json'), { ajax : true }, function(response) {
            trigger.addClass('applauded');
            
            trigger.unbind('click');
            trigger.click(function(){ return false; });

            if( trigger.hasClass('vote-action') ) {
                trigger.fadeOut();
                if( $('.side-bar-n .sponsor span.votes') ) {
                    var num = parseInt($('.side-bar-n .sponsor span.votes').text().split(' ')[0]) + 1;
                    $('.side-bar-n .sponsor span.votes').text( num + ' applause' );
                }
            } else if( trigger.siblings('a.votes') ) {
                var num = parseInt(trigger.siblings('a.votes').text().split(' ')[0]) + 1;
                trigger.siblings('a.votes').text( num + ' applause' );
            }
        });

        return false;
    });

    $('.comment-text a.applaud').click(function() {
       // vote a comment
        var url     = $(this).attr('href');
        var title   = $(this).attr('title');
        var trigger = $(this);

         $.getJSON(url.replace('.html', '.json'), { ajax : true }, function(response) {
            trigger.fadeOut(500, function(){ $(this).remove() });   // remove link

            if( trigger.siblings('span.applaud') ) {
                trigger.siblings('span.applaud').text(parseInt(trigger.siblings('span.applaud').text().split(' ')[0]) + 1);
            }
        });

        return false;
    });
    
    $('#auto-refresh-activities').click(function(){
        if( $(this).hasClass('selected') ) {
            $('#activities-feed').stop_refresh();
            $(this).removeClass('selected');
        } else {
            $('#activities-feed').auto_refresh();
            $(this).addClass('selected');
        }

        return false;
    });

    $('#usertags-form').submit(function(){
        var tags = '';

        $(this).find('.bit-box').each(function(i){
            if( i ) tags += ',';

            tags += $(this).attr('rel');
        });
        
        $(this).find('#usertags').val(tags);
    });

    $('.tabbed-browsing .panels>div').hide();
    $('.tabbed-browsing .panels>div').eq(0).show();
    
    $('.tabbed-browsing .tabbed-buttons').children().each(function(i){
        if( i < 1 ) $(this).addClass('selected');
        
        $(this).css({ cursor : 'pointer' });

        $(this).click(function() {
            $(this).addClass('selected').siblings().removeClass('selected');

            var panels = $(this).parent().parent().find('.panels>div');
            panels.removeClass('showing');
            panels.eq($(this).siblings().next().length).addClass('showing');

            $(this).parent().parent().find('.panels>div:not(.showing)').fadeOut(function(){
                $(this).parent().find('.showing').fadeIn();
            });
        });
    });


    
    if( $('#last-comment').length ) {
        $.getJSON( '/featured_comments.json', function(response) {
           
           var count = 0;
           var html = '';
           jQuery.each(response, function(url, text){
                if ( text.length > 85 )
                    text=text.substr(0,82) + '...';
                html += '<div class="comment comment-' + count + '"><div class="last-text"><div><a href="' + url + '">"' + text + '"</a></div></div></div>';
                count++;
           });

           $('#last-comment').prepend(html);
            
            $('#last-comment .comment').hover(
                function(){
                    $(this).find('.last-text').fadeIn();
                },
                function() {
                    $(this).find('.last-text').fadeOut();
                }
            );
        });
    }    

    $('.questions .radio-button, .questions-admin .radio-button').wrap('<span class="styled-radio"></span>').css({ opacity : 0 }).parent().parent().addClass('styled-radio-label');
    $('.questions .radio-button, .questions-admin .radio-button').change(function(){
        $(this).closest('form').find('input[name="' + $(this).attr('name') + '"]').parent().removeClass('checked');
        $(this).parent().addClass('checked');
    });

    $('#just-me-feed, #every-body-feed').click(function(){
        var urls = new Array();

        if( !$(this).hasClass('sony') && $(this).attr('href') != '#' ) {
            urls.push({ url : $(this).attr('href') });
        }

        if( $(this).attr('id') == 'every-body-feed' ) {
            if( $(this).hasClass('sony') ) {
                urls.push({ url : '/sony/activity.rss' });
                
                if( $(this).attr('rel') && $(this).attr('rel') != '' ) {
                    var feeds = $(this).attr('rel').split(',');
            
                    for(var i = 0; i < feeds.length; i++) {
                        var url = feeds[i].split(window.location.hostname.toString());
                        if( url.length > 1 ) {
                            url = url[1];
                            url = url.replace(':6543/', '/');
                        } else {
                            url = feeds[i];
                        }

                        urls.push({ url : jQuery.trim(url.replace('#', '')) });
                    }
                }
                    
            } else {
                urls.push({ url : '/activity.rss' });
            }

        }

        $(this).closest('.mid').find('.feed-load').fadeIn();
        $(this).addClass('selected').siblings().removeClass('selected');

        // try to align the height of the activity feed as well as possible
        var max_results = 12;
        if( $('.content-2-4 .future-challenges').length ) { // just in the homepage
            var height = $('.content-2-4 .future-challenges').closest('.content-2-4').height();
            // each item's height will be about 75px ( but probs more )
            max_results = Math.floor(height/90)-1;
            max_results = 0;
            max_results = max_results > 0 ? max_results : 12; // make sure we don't send off a negative number
        }

        if( !$('#activities-feed').children().length )
            $('#activities-feed').lb_feed({feeds : urls,
            format      : '<div class="activity-item">\
                                <a href="[%url%]" target="_blank" class="img">[%img%]</a>\
                                <div class="text">\
                                    <span class="action"><a href="[%url%]" target="_blank">[%username%]</a>[%action%]</span>\
                                    <div class="activity-text">[%description%]</div>\
                                </div><input type="hidden" class="feed-publish-date" value="[%pubdate%]" />\
                                <div class="clear"></div>[%challengeupdate%]\
                            </div>', max_results : max_results });

        $('#activities-feed').children().slideUp(1000, function(){
            $(this).remove();
            $('#activities-feed').lb_feed({feeds : urls });
        });
        
        return false;
    });


    if( $('#recent-comments').length ) {
        var feeds = $('#recent-comments').attr('rel').split(',');
        var urls = new Array();

        for(var i = 0; i < feeds.length; i++)
            urls.push({ url : feeds[i] });
        
        $('#recent-comments').lb_feed({feeds : urls,
                format      : '<div class="recent-comment"> \
                                <strong>[%username%]</strong> \
                                [%description%] \
                                <div class="time">[%pubdate%]</div> \
                            </div>'});
        
    }
    
    $('#every-body-feed').click();

    $('.save-button').click(function(){
        var trigger = $(this);
        $.getJSON( $(this).attr('href').replace('.html', '.json'), function(response) {
            jAlert(response.status_message);
            trigger.fadeOut(function(){ $(this).remove(); });
            
            top.$('#bookmark-list').load(top.window.location.toString() + ' #bookmark-list');
        });

         return false;
    });

    $('#bookmark-list').css({ overflow : 'auto', maxHeight : ( $(window).height() - 320 > 100 ? $(window).height() - 320 : 100 ) + 'px' });
    
    if( jQuery.browser.msie )
        $('#sliders-container').css({ height : ( $(window).height() - 246 ) + 'px' });

    $('#search-form .advanced-listing label input, #advanced-search .advanced-listing label input').change(function(){
        var form = $(this).closest('form');
        form.find('label input[name="' + $(this).attr('name') + '"]').each( function(){
            $(this).parent().removeClass('selected');

            if( $(this).val() == form.find('input[name="' + $(this).attr('name') + '"]:checked').val() )
                $(this).parent().addClass('selected');
        });
        
        $(this).closest('.advanced-listing').delay(400).slideUp(100, function(){
            if( $(this).parent().find('input.search').val() == '' )
                $(this).parent().find('input.search').focus();
            else
                $(this).closest('form').submit();
        });
    });

    if ( $.browser.msie ) {
        $('#by-search .advanced-listing label').click(function(){
            var input = $(this).find('input');
            if( input.attr('checked') )
                input.removeAttr('checked');
            else
                input.attr({'checked' : 'checked'});
            input.change();
        });
    }

    $('#by-search .advanced-listing label input').change(function(){
        var form = $(this).closest('form');
        form.find('label input[name="' + $(this).attr('name') + '"]').each( function(){
            $(this).parent().removeClass('selected');

            if( $(this).val() == form.find('input[name="' + $(this).attr('name') + '"]:checked').val() )
                $(this).parent().addClass('selected');
        });
        
        $(this).closest('.advanced-listing').delay(400).slideUp(100, function(){
            if( $(this).parent().find('input.search').val() == '' )
                $(this).parent().find('input.search').focus();
            else {
                $('#based-on-search #searcher').addClass('clickedonsomething').keydown();
            }    
        });
    });
    
    $('.show-advanced').click(function(){
        var options = $(this).parent().find('.advanced-listing');
        
        if( options.is(':visible') )
            options.slideUp(100);
        else
            options.slideDown(100);
    });

    $("a.modal").fancybox({
        'speedIn'       :       600, 
        'speedOut'      :       200, 
        'overlayShow'   :       false,
        'titleShow'     :   false
    });
    

    $('.themes a').fancybox({
        'speedIn'       :      600, 
        'speedOut'      :      200, 
        'overlayShow'   :       true,
        'type'          :   'iframe',
        'width'         :   712,
        'height'        :   684,
        'centerOnScroll':   true,
        'titleShow'     :   false
    });

    $('a.upload-media').fancybox({
        'speedIn'       :       600, 
        'speedOut'      :       200, 
        'overlayShow'   :       true,
        'type'          :   'iframe',
        'width'         :   480,
        'height'        :   280,//200,
        'centerOnScroll':   true,
        'titleShow'     :   false
    });

    $('a.share-this').fancybox({
        'speedIn'       :       600, 
        'speedOut'      :       200, 
        'overlayShow'   :       true,
        'type'          :   'iframe',
        'width'         :   680,
        'height'        :   344,
        'centerOnScroll':   true,
        'titleShow'     :   false
    });

    $('a.question-this').fancybox({
        'speedIn'       :       600, 
        'speedOut'      :       200, 
        'overlayShow'   :       true,
        'type'          :   'iframe',
        'width'         :   680,
        'height'        :   394,
        'centerOnScroll':   true,
        'titleShow'     :   false
    });

    $('button.evaluate-this:not(.selected)').click(function(){
        $(this).addClass('selected');
    });

    $('.go-back-page').click(function(){
        history.go(-1);
        return false;
    });

    $('#edit-fieldnotes').submit(function(){
        var variables = $(this).serialize();
        var url       = $(this).attr('action'); 
        
        jQuery.ajax({
                    url     : url,
                    data    : variables,
                    dataType: 'json',
                    type    : 'POST',
                    success : function(response){
                                    if( response.success ) {
                                        jAlert('Done!');
                                        window.location.reload();
                                    } else {
                                        jAlert('There was an error submitting form.\nPlease check that all the fields have been filled in.');
                                    }
                              },
                    error : function(){
                            jAlert('There was an error submitting form.\nPlease check that all the fields have been filled in');
                    }
        });
        
        return false;
    });

    /* IF NOT LOGGED IN */
    if( top.$('#login-side').length ) {
        var classes = '.add-inspiration, .add-concept, .ajax-action, .vote-listing, .flag, .follow-button, .button.bookmark.save-button, .add-inspiration-assignment, .postcomment, a.applaud, a.report';

        $(classes).unbind('click');
        $(classes).click(function(){
            top.$('#login-side').click();
            return false;
        });

        $('#comment-form').unbind('submit');
        $('#comment-form, .questions form#add-content').submit(function(){
            top.$('#login-side').click();
            return false;
        });

    } else if( $('.contribute-terms').length ) {
        $('.add-inspiration, .add-concept, .add-inspiration-assignment').click(function(){
            $(this).addClass('follow-my-link');
            $('.contribute-terms').click();
            return false;
        });
    }

    $('.list .top-part h4 a').each(function(){
        while( $(this).height() > 24 )
            $(this).text( $(this).text().substring(0,($(this).text().length-4)) + '...' );
    });

    $('#theme-page .related-inpir-item .text h5 a').each(function(){
        while( $(this).height() > 22 )
            $(this).text( $(this).text().substring(0,($(this).text().length-4)) + '...' );
    });

    $('.blog-list h4').each(function() {
        var line_height = 26;
        if( $(this).height()+2 > (line_height*4) ) {
            $(this).css({ width : 'auto' });
        } else if( $(this).height()+2 > (line_height*3) ) {
            $(this).css({ width : '300px' });
        }
    });

    $('#iframe_page .cancel-button').click(function(){
        parent.$.fancybox.close();
        return false;
    });

    set_gallery();

    if ( $('#challenge-themes').length && window.location.toString().indexOf('#theme-') > -1 ) {
        var theme_to_see = window.location.toString().split('#theme-')[1];
            $('#theme-item-listed-' + theme_to_see).click();
    }

    $(window).load(function(){ $('<span class="clear-digg">Digg this</span>').insertAfter('a.db-anchor');  });

    $(window).resize(function() {
        $('#bookmark-list').css({ maxHeight : ( $(window).height() - 320 > 100 ? $(window).height() - 320 : 100 ) + 'px' });
        if( jQuery.browser.msie )
            $('#sliders-container').css({ height : ( $(window).height() - 246 ) + 'px' });
    });

    $('#narrow-sidebar').html($('.side-bar-n:not(#narrow-sidebar)').eq(0).html());

    $('label.terms-label').hide();

    $('.terms-conditions-link').fancybox({
        'type'          :   'iframe',
        'speedIn'               :       600, 
        'speedOut'              :       200, 
        'autoScale'     :   false,
        'overlayShow'   :       true,
        'width'         :   530,
        'height'        :   460,
        'centerOnScroll':   false,
        'titleShow'     :   false
    });

    $('#join-form .terms-conditions-link').unbind('click');

    $('.terms-conditions-link').click(function(){ $(this).addClass('submitting-this-form') });
    
    $('#join-form .terms-conditions-link').click(function(){
        var url = $(this).attr('href');
        strWidth = 530;
        strHeight = 530;

        leftStr = (screen.width-strWidth)/2;
        topStr = (screen.height-strHeight)/2-50;
        windowProperties = "toolbar=no,menubar=no,scrollbars=no,statusbar=no,height="+strHeight+",width="+strWidth+",left="+leftStr+",top="+topStr+"";
        popWin = window.open(url,'newWin',windowProperties);
        
        return false;
    });
    
    $('#iframe_page.terms .yes').click(function(){
        var parent_window = parent;

        if ( window.opener ) parent_window = window.opener;
        
        parent_window.$('.terms-label input').attr('checked', true);
        
        if( parent_window.$('.submitting-this-form').length && !parent_window.$('.submitting-this-form').closest('form#sign-up-form').length )
            parent_window.$('.submitting-this-form').closest('form').submit();
        
        if( parent_window.$('.follow-my-link').length  ) {
            var url = parent_window.$('.follow-my-link').eq(0).attr('href');
            if( url.indexOf('?') > -1 )
                url += '&';
            else
                url += '?';

            parent_window.window.location = url + 'accept=True';
            parent_window.$('.follow-my-link').unbind('click', this.onClick);
        }
        
        if( parent_window.$('.accept-tnc-before-voting').length ) { // voting
            var input = parent_window.$('.accept-tnc-before-voting').eq(0);
                input.val('accepted');
            parent_window.$('.accept-tnc-before-voting-trigger').click();
        }

        parent_window.$.fancybox.close();

        if ( window.opener && window.opener.popWin != '') {
            window.opener.popWin.close();
            parent_window.popWin = '';
        }
    });

    $('#terms-languages').each(function(){
        var parent_window = parent;
        if ( window.opener ) parent_window = window.opener;

        if( parent_window.$('h1#sony-header').length ) {
            $(this).show();
        }
    });

    $('#iframe_page.terms .no').click(function(){
        var parent_window = parent;

        if( parent_window.$('h1#sony-header').length && !$(this).hasClass('clicked-once') ) {
            $(this).addClass('clicked-once');
            
            $('#terms-box').css({ height : '324px' }).after('<span id="whine">Please accept the challenge rules to participate int he Open Planet Ideas challenge. Read the Challenge Rules.</span>');
            
            return false;
        }

        if ( window.opener ) parent_window = window.opener;

        parent_window.$('.terms-label input').attr('checked', false);
        parent_window.$('.submitting-this-form').removeClass('submitting-this-form');
        parent_window.$('.follow-my-link').removeClass('follow-my-link');
        parent_window.$.fancybox.close();
        if( window.opener && parent_window.popWin != '') { 
            parent_window.popWin.close();
            parent_window.popWin = '';
        }
        
        return false;
    });
    
    $('#view-collab').bind('click', function(){
        
        $('#gallery .thumbs a').eq($('#gallery .thumbs a').length-1).click();
        $('#gallery .enlarger').click();
        
        return false;
    });

    if( $('.collab-map, .collab-map-challenge').length && window.location.toString().indexOf('#collaboration-map') > -1 ) {
        if( $('.collab-map-challenge').length )
            $('.collab-map-challenge').eq(0).click();
        else
            $('.collab-map').eq(0).click();
    }

    $('textarea:not(.no-grow)').autogrow().css({'overflow': 'hidden'});

});

$('#activities-feed .activity-item a').live('click', function(){

    var link = $(this).attr('href');
    if( link.indexOf('#theme-') > -1 ) {
        link = link.split('#theme-')[1];
        
        if( $('#theme-item-listed-' + link ) ) {
            $('#theme-item-listed-' + link ).click();
            return false;
        }
    }
});

$('.deletemes').live('click', function(){
    $(this).parent().fadeOut(function(){ 
        if( $(this).hasClass('from-bookmarks') ) {
        
            if( $('#by-bookmarks ul').length )
                $('#by-bookmarks ul').append($(this));
            else if( $('#search-users #based-on-results').length )
                $('#search-users #based-on-results').append($(this));
            
            if( $('#search-users').length )
                $('#based-on-search input[name="blog.authors"]').remove();
            else
                $('#based-on-search input[name="content.basedon"]').remove();
            $(this).show();
        } else if( $(this).hasClass('from-techno') ) {
        
            if( $('#by-tech ul').length )
                $('#by-tech ul').append($(this));

            $('#by-tech input[name="content.basedon"]').remove();
            $(this).show();
        } else
            $(this).remove()
    });
});

$('.add-remove-user-as-admin').live('click', function(){
    if( $(this).closest('#admin-listing').length )
        $(this).parent().parent().fadeOut(function(){ $(this).remove() });
    else {
        $('#admin-listing').append('<tr>' + $(this).parent().parent().html() + '</tr>');
        $(this).parent().parent().remove();

       $('#admin-listing').find('td.information').each(function(i){
           if( !$(this).find('input').length ) {
                $(this).append('<input type="hidden" name="administrator" value="' + $(this).attr('rel') + '" />');
           }
       });
       
       $('#admin-listing .add-remove-user-as-admin').text('remove');

    }
});

$('.follow-button').live('click', function(){
    var url = $(this).attr('href') != undefined ? $(this).attr('href') : $(this).attr('rel');
    var trigger = $(this);
    
    if( trigger.hasClass('unfollow-button') )
        return false; //url += 'unfollow.json';
    else
        url += 'follow.json';

    $.getJSON( url, function(response) {
        jAlert(response.status_message);

        var count = parseInt($('#challenge-follow .followers span').text());
        
        if( trigger.hasClass('unfollow-button') ) {
            $('.follow-button').removeClass('unfollow-button');
            $('#challenge-follow .followers span').text( count-1 );
        } else if( trigger.closest('#follow-sony-challenge').length ) {
            $('#follow-sony-challenge').fadeOut();
        } else {
            $('.follow-button').addClass('unfollow-button');
            $('#challenge-follow .followers span').text( count+1 );
            
            if( $('h1#sony-header').length ) $('.follow-button.unfollow-button').text('Following challenge').addClass('cursorless');
        }
    });
    
     return false;
});

function equate_heights() {
    $('.equal-height, .expandable').css({ minHeight : '' });

    $('.equal-height').each(function(){
        var min_height  = $(this).outerHeight();
        var title        = $(this).attr('title');

        $('*[title=' + title + ']').each(function(){
            if( $(this).outerHeight() > min_height ) {
                min_height = $(this).outerHeight();
            }
        });

        $('*[title=' + title + ']').each(function(){
            var my_min_height = min_height - (parseInt($(this).css('paddingTop')) + parseInt($(this).css('paddingBottom')));

            if( !$(this).find('.expandable').length ) {
                $(this).css({ minHeight : my_min_height + 'px'});
            } else {
                var child_expand = $(this).find('.expandable').eq(0);
                var new_min_height = $(this).height() - child_expand.outerHeight();
                    new_min_height = my_min_height - new_min_height - 41;

                child_expand.css({ minHeight : new_min_height + 'px'});
            }

            $(this).removeClass('equal-height').removeAttr('title');
        });
    });
}


function set_gallery() {
    $('#gallery .thumbs a').each(function(){
        if( $(this).attr('rel').indexOf('<object width="500" height="338"><param name="movie" value="http://www.youtube.com') < 0 && 
            $(this).attr('rel').indexOf('alue="http://vimeo.com/moogaloop.swf?') < 0 ) {

            // it's an image! check and make sure large version exists
            var trigger = $(this);
            var new_url = $(this).find('img').attr('src').replace('/gallery/', '/gallery/fullsized_');
            trigger.attr({ 'rel_large' : new_url });

            $.ajax({ url: new_url,  // make sure we only link those which DO have the fullscreen size
                                    // also acts as a pre-loader :)
                success: function(response){
                if( response.indexOf('page doesn') > -1 )
                    trigger.attr({ 'rel_large' : trigger.find('img').attr('src') });
            }});

            $(this).addClass('not-video');

        } else {
            $(this).attr({ 'rel_large' : $(this).attr('rel') });
        }
    });

    $('#gallery .enlarger').click(function(){
        var html =  $('#gallery .thumbs a.selected').attr('rel_large');


        if( $('#gallery .thumbs a.selected').hasClass('not-video') ) {
            $.fancybox(html, {
                'speedIn'               :       600,
                'type'          :   'image',
                'speedOut'              :       200,
                'overlayShow'   :       true,
                'width'         :   740,
                'height'        :   486,
                'centerOnScroll':   true,
                'titleShow'     :   false
            });
        } else {
            html = html.replace(/width="500"/gi, 'width="720"').replace(/height="338"/gi, 'height="486"');

            $.fancybox(html, {
                'speedIn'               :       600, 
                'speedOut'              :       200,
                'overlayShow'   :       true,
                'width'         :   740,
                'height'        :   486,
                'centerOnScroll':   true,
                'titleShow'     :   false
            });
        }
    });

    $('#gallery .thumbs a').click(function(){
        var load = $(this).attr('rel');
        var trigger = $(this);
        var filetype = load.split('.');
        var html = unescape(load);
        $('#gallery .thumbs a.selected img').fadeTo('slow', 0.5);
        $('#gallery .thumbs a').removeClass('selected');
        $(this).addClass('selected');
        $('#gallery .thumbs a.selected img').fadeTo('slow', 1);

        if( filetype[filetype.length-1] == 'jpg' ||
            filetype[filetype.length-1] == 'png' ||
            filetype[filetype.length-1] == 'gif'  )
            html = '<img src="' + load + '" alt="" />';

        $('#gallery .content-loader>div').fadeOut(function(){
            $(this).html(html);
            
            if( $(this).find('img').length )
                $(this).find('img').load(function(){$(this).parent().fadeIn(800);});
            else
                $(this).fadeIn(800);
        });
        
        return false;
    });

    $('.delete-image-gallery').click(function(e) {
        e.stopPropagation();
        var thumb = $(this).parent();
        
        if( thumb.hasClass('delete-on-submit') ) {
            if ( $.browser.msie ) {
                $(this).css({ padding : '5px 10px'});
            } else {
                $(this).animate({ padding : '5px 10px'});
            }
            thumb.removeClass('delete-on-submit');
            thumb.find('input.to-delte-on-submit').remove();
        } else {
            if ( $.browser.msie ) {
                $(this).css({ padding : '22px 38px'});
            } else {
                $(this).animate({ padding : '22px 38px'});
            }

            var url_to_delete = thumb.find('img').attr('src');

            if( !thumb.hasClass('not-video') ) {
                url_to_delete = window.location.toString().split('edit.html')[0] + 'gallery/';
                url_to_delete += thumb.find('input[type="hidden"]').val();
                url_to_delete += '/delete.html';
            }

            thumb.addClass('delete-on-submit').append('<input type="text" class="to-delte-on-submit" value="' + url_to_delete + '" />');
        }
        return false;
    });

    if( typeof(rich_text) != 'undefined' )
        rich_text('textarea.rte');

    $('#gallery .thumbs a').eq(0).click();

    if( $('.admin-reorder-thumbs .thumbs').length ) {

        $('.admin-reorder-thumbs .thumbs').append('<ul>');
        $('.admin-reorder-thumbs .thumbs a').wrap('<li>');
        $('.admin-reorder-thumbs .thumbs ul').append($('.admin-reorder-thumbs .thumbs li'));

        $('.admin-reorder-thumbs ul').sortable().disableSelection();
    }
}

function ebConversionTracker(conv){
    var ebConversionImg = new Image();
    var ebConversionURL = 'HTTP://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?';
    ebConversionURL     += 'cn=as&ActivityID='+conv+'&ns=1';
    ebConversionImg.src = ebConversionURL;
}

