// Browser Checks

var BROWSER_IE = false;
var BROWSER_IE6 = false;
var BROWSER_IE7 = false;
var BROWSER_SAF = false;

if ($.browser.msie) {
    BROWSER_IE = true;
    if ($.browser.version.substr(0,1) == 6) {
        BROWSER_IE6 = true;
    } else if ($.browser.version.substr(0,1) == 7) {
        BROWSER_IE7 = true;
    }
} else if (navigator.userAgent.indexOf("safari")) {
    BROWSER_SAF = true;
}

// This section fixes plugins!!!
if (jQuery.fn.dialog) {
    $.ui.dialog.defaults.zIndex = ($.browser.safari) ? 99999 : 9999999;
}

// Functions

//open dialog boxes when login re-direction
function activateFxDialog(fxName, elementid) {
    var $elem = (elementid instanceof jQuery) ? elementid : $("#" + elementid);  
    if (fxName == "reply") {
        $elem.parents('.comments').find('p.toggle:first .count_toggle').trigger('click');                        
    }                 
    $elem.trigger('click');
    $.scrollTo($elem, 800);   
} 
    
function hideWidgets() {
    if ( $('.widget_container') ) {
        $('.widget_container').hide();

        if (BROWSER_IE6) {
            $('select').show();
        }
    } else {
        window.close();
    }
}

function removeLeaderboardAdStyles() {
    if ( ( ($('#critics_quotes').length > 0) && ($('#critics_quotes').is(':hidden')) ) || ($('#critics_quotes').length == 0) ) {
        $('#leaderboard_ad').css({'float' : 'none', 'width' : 'auto'});
    }
}

// RT common functions

/*
* remove the unused ad to prevent it from taking up space in the browser
* @automated BOOL toggles whether plugin destroys the ad element or returns the rt_adcheckObj
* @match STR pass in a custom string to check against. The default is common to ad server
*/
jQuery.fn.rt_adcheck = function( automated, match ){
    var automated = (automated || 'on');
    var match = (match || ' **This is a default 1x1** ');
    var commentArr = new Array;
 
    this.each( function( intI, objNode ){
        var objChildNode = objNode.firstChild;
        while (objChildNode){
            if (objChildNode.nodeType === 8){ // if this node is a comment
                commentArr.push(objChildNode.nodeValue); // found comment node. Add it to commentArr
            }
            objChildNode = objChildNode.nextSibling;
        }
    });

    // if automated is disabled, output rt_adcheckObj; otherwise destroy the ad element
    if (automated === 'off') {
        rt_adcheckObj = new Object;
        rt_adcheckObj.automated = false;
        rt_adcheckObj.match = ( jQuery.inArray( match, commentArr ) != -1 ) ? true : false;
        rt_adcheckObj.commentArr = commentArr;
        return rt_adcheckObj;
    } else { // Removes the ad element if @match is found
        if ( jQuery.inArray( match, commentArr ) != -1 ) {
            this.remove();
        }
    }

}

jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++) {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

/*
* Appends loader img to selector
* Possible to extend this so it supports a variety of loader img and scenarios
*/
jQuery.fn.sortable_loaderImg = function() {
    this.append('<img />')
        .find('img')
        .attr({ src: 'http://images.rottentomatoes.com/images/icons/ico_loader_sm.gif', alt: 'loader' })
        .css({ position: 'absolute', 'margin-left': '5px' });
}

/*
* skin STR matches cssclass of the same name
* settings ARRAY of options (extends default)
*/
jQuery.fn.rt_buzzad = function(skin, settings) {
    
    if ( (typeof settings != 'undefined') && (typeof settings['link_href'] != 'undefined') ) {
    
        var uniqueID = jQuery(this).attr('id'); // the box module ID
        
        var config = jQuery.extend ({
            header_image:      '',
            border_color:      '',
            text_color:        '',
            link_href:         '',
            link_color:        '',
            link_hover_color:  '',
            link_active_color: '',
            abstract_image:    '',
            abstract_color:    '',
            selected_color:    '',
            list_cssclass:     '',
            background_color:  '',
            background_image:  ''
        }, settings);
        
        var css_output = function(hook, skin) { // outputs inherited styles
            var hook = '#' + hook + ' .content_body';
            var output = '<style type="text/css">';
            if (skin == 'bob_box_sidebar_ad') {
                output += hook + ",\n" + hook + " li,\n" + hook + " h5,\n" + hook + " span { color: " + config.text_color + "; }\n";
                output += hook + " a,\n" + hook + " a:visited { color: " + config.link_color + "; }\n";
                output += hook + " a:hover { color: " + config.link_hover_color + "; }\n";
                output += hook + " a:active { color: " + config.link_active_color + "; }\n";
                output += hook + " hr { background-color: " + config.abstract_color + "; }\n";
                output += hook + " h5, " + hook + " h5 a, " + hook + " caption, " + hook + " caption a, " + hook + " hr, " + hook + " .icon span, " + hook + " .cloudFake em { color: " + config.abstract_color + " !important; }\n";
            }
            output += '</style>';
            return output;
        }
        
        // Only output if params are set
        if ( (typeof settings['link_href'] != 'undefined') ) {
            
            // Skin: bob_object_toolbar
            if (skin == 'bob_object_toolbar') {
                this.addClass('bob_object_toolbar')
                    .append('<a class="bob_object_toolbar_image png_ignore" style="background-image: url(' + config.header_image + ')" href="' + config.link_href + '" target="_blank">Sponsored by</a>');

            // Skin: bob_box_moduletitle_ad
            } else if (skin == 'bob_box_moduletitle_ad') {
                this.find('.content_inner')
                    .prepend('<a class="bob_box_moduletitle_ad" href="' + config.link_href + '" target="_blank"><span>Sponsored by</span><img src="' + config.header_image + '" class="png_ignore" border="0" alt="Sponsored Ad" /></a>');

            // Skin: bob_box_sidebar_ad
            } else if (skin == 'bob_box_sidebar_ad') {
                
                var box_bg_settings = new Array;
                box_bg_settings['background-image'] = (config.background_image) ? 'url(' + config.background_image + ')' : '';
                box_bg_settings['background-color'] = (config.background_color) ? config.background_color : '';
                box_bg_settings['border-color']     = (config.border_color)     ? config.border_color : '';
                
                var abstract_img = '<div class="bob_ad_abstract_image"><a href="' + config.link_href + '" target="_blank"><img src="' + config.abstract_image + '" border="0" /></a></div>';
                
                $('head').append( css_output( uniqueID, 'bob_box_sidebar_ad' ) );
                this.addClass('bob_box_sidebar_ad')
                    .find('.content_body').css( box_bg_settings )
                    .prepend('<a class="bob_box_sidebar_ad_header" href="' + config.link_href + '" target="_blank"><span>Bob Ad</span></a>').css({ 'background-image': 'url(' + config.header_image + ')' });
                this.find('ul').addClass( 'normalViewList_' + config.list_cssclass );
                
                // abstract_img has special placement
                if (config.abstract_img) {
                    if (this.find('hr').is()) {
                        this.find('hr').before(abstract_img);
                    } else {
                        this.find('.content_body').append(abstract_img);
                    }
                }
                
            // Skin: bob_movies_sidebar_ad
            } else if (skin == 'bob_movies_sidebar_ad') {

                this.addClass('bob_movies_sidebar_ad')
                    .css({ borderColor: config.border_color });
                this.find('caption a')
                    .addClass('bob_ad_title')
                    .css({ color: config.text_color })
                    .hover(
                        function () { jQuery(this).css({ color: config.link_hover }); }, 
                        function () { jQuery(this).css({ color: config.text_color }); }
                    );
                this.find('caption')
                    .css('background-image','url(' + config.background_image + ')')
                    .append('<a class="bob_ad_anchor" target="_blank" href="' + config.link_href + '"><span>click here</span></a>');
                
                // Style IE6 (doesn't support first-child selector)
                if (BROWSER_IE6) {
                    this.find('tbody tr:first-child').addClass('first-child');
                }

            }
            
        }
    }
        
}

function print_r(obj){
    var s='';
    for(a in obj){
        s+=a +'=>'+ (obj[a]?obj[a]:'')+'\n';    
    }
    return s;
}
// Returns our RT box module
jQuery.fn.rt_boxModule = function (config) {
                             
    var cfg = jQuery.extend({
        id: '',
        title: '',
        title_url: '',
        header_text: '',
        header_url: '',
        content: ''
    }, config);           
                                  
    
    var o = '<div class="content clearfix" id="' + cfg.id + '">';
    if (cfg.title) {
        o += '<div class="content_header">';
        o += (cfg.header_url) ? '<div class="header_text"><a href="' + cfg.header_url + '">' + cfg.header_text + '</a></div>' : '<div class="header_text">' + cfg.header_text + '</div>';
        o += (cfg.title_url) ? '<h3><a href="' + cfg.title_url + '">' + cfg.title + '</a></h3>' : '<h3>' + cfg.title + '</h3>';
        o += '</div>';
    }
    o += (cfg.title) ? '<div class="content_body clearfix">' : '<div class="content_body clearfix noHead">';
    o += cfg.content + '</div></div>';
                       
    return o;
    
}

jQuery.fn.rt_sortSelect = function(){ 
      this.append( 
        //remove the first item from the drop down: Assuming it might be a Select.
        $('option:not(:first-child)', this).remove().get() 
        .sort(function(a,b){  
          return $(a).text().toLowerCase() > $(b).text().toLowerCase() ? 1: -1;  
        }) 
      ) 
};

jQuery.fn.truncate = function( max, settings ) {
    settings = jQuery.extend( {
        chars: /\s/,
        trail: [ "...", "" ]
    }, settings );
    var myResults = {};
    var ie = $.browser.msie;
    function fixIE( o ) {
        if ( ie ) {
            o.style.removeAttribute( "filter" );
        }
    }
    return this.each( function() {
        var $this = jQuery(this);
        var myStrOrig = $this.html().replace( /\r\n/gim, "" );
        var myStr = myStrOrig;
        var myRegEx = /<\/?[^<>]*\/?>/gim;
        var myRegExArray;
        var myRegExHash = {};
        var myResultsKey = $("*").index( this );
        while ( ( myRegExArray = myRegEx.exec( myStr ) ) != null ) {
            myRegExHash[ myRegExArray.index ] = myRegExArray[ 0 ];
        }
        myStr = jQuery.trim( myStr.split( myRegEx ).join( "" ) );
        if ( myStr.length > max ) {
            var c;
            while ( max < myStr.length ) {
                c = myStr.charAt( max );
                if ( c.match( settings.chars ) ) {
                    myStr = myStr.substring( 0, max );
                    break;
                }
                max--;
            }
            if ( myStrOrig.search( myRegEx ) != -1 ) {
                var endCap = 0;
                for ( eachEl in myRegExHash ) {
                    myStr = [ myStr.substring( 0, eachEl ), myRegExHash[ eachEl ], myStr.substring( eachEl, myStr.length ) ].join( "" );
                    if ( eachEl < myStr.length ) {
                        endCap = myStr.length;
                    }
                }
                $this.html( [ myStr.substring( 0, endCap ), myStr.substring( endCap, myStr.length ).replace( /<(\w+)[^>]*>.*<\/\1>/gim, "" ).replace( /<(br|hr|img|input)[^<>]*\/?>/gim, "" ) ].join( "" ) );
            } else {
                $this.html( myStr );
            }
            myResults[ myResultsKey ] = myStrOrig;
            $this.html( [ "<div class='truncate_less'>", $this.html(), settings.trail[ 0 ], "</div>" ].join( "" ) )
            .find(".truncate_show",this).click( function() {
                if ( $this.find( ".truncate_more" ).length == 0 ) {
                    $this.append( [ "<div class='truncate_more' style='display: none;'>", myResults[ myResultsKey ], settings.trail[ 1 ], "</div>" ].join( "" ) )
                    .find( ".truncate_hide" ).click( function() {
                        $this.find( ".truncate_more" ).css( "background", "Transparent" ).fadeOut( "normal", function() {
                            $this.find( ".truncate_less" ).css( "background", "Transparent" ).fadeIn( "normal", function() {
                                fixIE( this );
                                $(this).css( "background", "none" );
                            });
                            fixIE( this );
                        });
                        return false;
                    });
                }
                $this.find( ".truncate_less" ).fadeOut( "normal", function() {
                    $this.find( ".truncate_more" ).fadeIn( "normal", function() {
                        fixIE( this );
                    });
                    fixIE( this );
                });
                jQuery(".truncate_show",$this).click( function() {
                    $this.find( ".truncate_less" ).css( "background", "Transparent" ).fadeOut( "normal", function() {
                        $this.find( ".truncate_more" ).css( "background", "Transparent" ).fadeIn( "normal", function() {
                            fixIE( this );
                            $(this).css( "background", "none" );
                        });
                        fixIE( this );
                    });
                    return false;
                });
                return false;
            });
        }
    });
};

/* Temporary fix for old sponsored links styling */
function fix_google_afc (elem) {
    $elem = (elem instanceof jQuery) ? elem : '$("#' + elem + ')';
    if ($elem) {
        var $afc_sidebar = $('#afc_sidebar').find('.content_body');
        $afc_sidebar.html( $elem.html() ); // restores afc content within new box module
        $('#ad-wrap').remove(); // removes the old afc module
        if (BROWSER_IE6) { $afc_sidebar.find('a:first-child').addClass('first-child'); }
    }
}

function valign(elem) {
    elem = (elem instanceof jQuery) ? elem : '$("#' + elem + ')';
    elem.wrap('<div class="valign_container_outer"><div class="valign_container_middle"><div class="valign_container_inner"></div></div></div>');
}

/* Helpers for targeting IE unsupported selectors */
function menuViewList(elem) {
    elem = (elem instanceof jQuery) ? elem : '$("#' + elem + ')';
    elem.find('li:first-child').addClass('first-child').end()
        .find('li:last-child').addClass('last-child');
}

function proViewTbl_lastCol(elem) {
    elem = (elem instanceof jQuery) ? elem : '$("#' + elem + ')';
    if (BROWSER_IE) {
        elem.find('tbody tr:last-child').addClass('last-child');
    }
}

function submitBtnToggle(el, status) {
    el = (el instanceof jQuery) ? el : '$("#' + el + ')';
    if (status == 'enabled') {
        el.removeAttr('disabled').removeClass('submitBtn_disabled').addClass('submitBtn');
    } else {
        el.attr('disabled', 'disabled').removeClass('submitBtn').addClass('submitBtn_disabled');
    }
}

function arrowExpandToggle(el) {
    el = (el instanceof jQuery) ? el : '$("#' + el + ')';
    arrow = el.find("img.icon").attr("src").split("/").pop();
    if (arrow == "expand_arrow_right.gif") {
        new_arrow = "expand_arrow_down.gif";
    } else if (arrow == "expand_arrow_down.gif") {
        new_arrow = "expand_arrow_right.gif";
    }

    arrow_path = el.find("img.icon").attr("src").replace(arrow, new_arrow);
    el.find("img.icon").attr("src", arrow_path);
}

function containerArrowToggle(id, target_id) {    
    var arrow = $("#" + id).children('.icon');
    var target_container = $("#" + target_id);
    
    target_container.slideToggle(animSpeed, function() {
        target_container.toggleClass('selected');
        if ( target_container.hasClass('selected') ) {
            arrow.attr('src', arrow_down);
        } else {
            arrow.attr('src', arrow_right);
        }
    });
}

function isNotEmptyInput(el) {
    el = (el instanceof jQuery) ? el : '$("#' + el + ')';
    if (jQuery.trim(el.val()).length) {
        return true;
    } else {
        return false;
    }
}

function refreshRTAds(ads) {
    jQuery.each(ads, function(k, v) {
        if (k != 'interstitial') {
            if (k == 'leaderboard') {
                var iframe_params = 'width="728" height="90"';
            } else {
                var iframe_params = 'width="0" height="0"';
            }

            $('#' + k + '_ad').text('');
            $('#' + k + '_ad').html('<iframe id="' + k + '_ad_iframe" src="/includes/js.php?iframe=1&src=' + urlencode(v) + '" ' + iframe_params + ' valign="top" scrolling="no" frameborder="0" allowtransparency="yes"></iframe>');

            $('#' + k + '_ad_iframe').load(function() {
                if ($('#' + k + '_ad').children().size() == 1) {
                    var text = $(this).contents().find('body').html();
                    var data = { html: text };

                    $.ajax({
                        type: "POST",
                        url: "/includes/iframe_buster_ad.php",
                        data: data,
                        dataType: "json",
                        success: function(response) {
                            if (response.success) {
                                if ( (k == 'text') || (k == 'leaderboard') ) {
                                    $('#' + k + '_code').text(response.html);
                                }

                                $('#' + k + '_ad').text('');
                                $('#' + k + '_ad').html(response.html);
                            }
                        }
                    });
                }
            });
        }
    });
}

function abuseRequest(id, dom_id) {
    var el = $("#" + id);
    var link = el.attr("rel");

    el.cluetip({
        width: 140,
        activation : 'click',
        sticky : true,
        mouseOutClose : true,
        ajaxCache : false,
        ajaxSettings : {
            type : "POST",
            data : { dom_id : dom_id }
        },
        onShow : function () {
            $("#tooltip_confirmation_cancel").click(function() {
                $("#cluetip-close").click();
                return false;
            });

            $("#tooltip_confirmation_submit").click(function() {
                $("#cluetip-close").click();
                
                $.ajax({
                    type: "POST",
                    url: link,
                    data: { rpc : true, dom_id : dom_id, action : 'add' },
                    dataType : "json",
                    success: function(response) {
                        if (response.success) {
                            el.before('Abuse repoted.').remove();
                        }
                    }
                });

                return false;
            });
        }
    });

    if (document.createEventObject) {
        document.getElementById(id).fireEvent("onclick");
    } else if (document.createEvent) {
        el.click();
    }
}

// RT common jQuery calls


$.elementReady('nav_primary', function(){

    $(this).find('a').click(function(e){
        var $this = $(this);

        var urlAttr  = $this.attr('href');
        var idAttr   = $this.attr('id').replace(/nav_primary\_/, '');
        var int_cmp  = nav_primary_data[idAttr].intcmp_id;
        var url      = urlAttr + '?intcmp=' + int_cmp;

        // Selects after click in primary navigation
        $('ul#nav_primary a').removeClass('selected');
        $this.addClass('selected');

        // Adds int_cmp param to querystring of primary nav urls
        window.location = url;
        e.preventDefault();
    });

});

if (jQuery.fn.cluetip) {
    $.fn.cluetip.defaults.cluezIndex = 9999999;
    $.fn.cluetip.defaults.leftOffset = 10;
    $.fn.cluetip.defaults.showTitle = false;
    $.fn.cluetip.defaults.cluetipClass = 'rt';
    $.fn.cluetip.defaults.arrows = true;
    $.fn.cluetip.defaults.dropShadow = false;
    $.fn.cluetip.defaults.sticky = true;
    $.fn.cluetip.defaults.mouseOutClose = true;
    $.fn.cluetip.defaults.fx = { open: 'fadeIn', openSpeed: 200 };
    $.fn.cluetip.defaults.hoverIntent = { sensitivity: 10, interval: 150, timeout: 200 };
}

$(document).ready(function() {

    // Removed outlines when elements are selected
    $("input[type='radio'],input[type='checkbox'],button").focus(function(){
        this.blur();
    });

    // Widget Tooltip
    // Requires jquery.tooltip.min.js
    if (jQuery.fn.tooltip) {
        $("a.widget_access_icon").tooltip({
            delay: 500, showURL: false, fixPNG: true, opacity: 1, showBody: " - ",  extraClass: "bubbleFixedLeftXSmallTop", top: -75, left: -2
        });
    }

    // Google SearchBar Tooltip
    var searchbar_google_Target     = $('#searchBar_google a');
    var searchbar_google_Tooltip    = $('#searchBar_google_tooltip');
    if ($('div#searchBar') && (jQuery.fn.hoverIntent)) {
        searchbar_google_Target.hoverIntent(
            function(){
                searchbar_google_Tooltip.show();
            },
            function(){
                searchbar_google_Tooltip.hide();
            }
        );
    }

    // Prepend Named Anchor to Box Module for IE6 only
    if (BROWSER_IE6) {
        $('div.content').each(function(i){
            var boxID = $(this).attr('id');
            $(this).prepend('<a name="' + boxID + '" id="' + boxID + '"></a>');
        });
    }

    // Keep Google IMG from resizing after pngFix
    if (BROWSER_IE6) {
        $("img#searchBar_googleImg").attr("src", "http://images.rottentomatoes.com/images_REDESIGN/template/searchbar_poweredbygoogle.gif");
    }
    
    // Selects after clicks for all abstract imgs
    $('.abstract img').click(function(){
        if ( $(this).parent().is('a') ) {
            $(this).addClass('selected');
        }
    });

    // Video Image control
    if (!BROWSER_IE6) {
        $('.videoImg').each(function() {
            if ($(this).children('div.videoImgControl a')) {
                $(this)
                    .mouseover(function() {
                        $(this).children('a.abstract').addClass("hover");
                        $(this).children('div.videoImgControl').children('a').addClass("hover");
                    })
                    .mouseout(function() {
                        $(this).children('a.abstract').removeClass("hover");
                        $(this).children('div.videoImgControl').children('a').removeClass("hover");
                    })
                    .mousedown(function() {
                        $(this).children('div.videoImgControl').children('a').toggleClass("active");
                    })
                    .mouseup(function() {
                        $(this).children('div.videoImgControl').children('a').removeClass("hover active");
                    });
            }
        });
    }

    $("#nav_primary_movies").hover(function() {
        $("#nav_bg").css({height: ""});
    }, function() { });

});

/**
*   Global variable that is defined when a flash rater exists
*
**/
var rt_rater_exists=false;                
/**
*   This has been put in place to rectify the mouse up issue 
*   outside of the rater.  Flash acts differently in firefox 
*   than it does in iexplorer.
*  
**/                        

 $(document).ready(function() {                   
    if(rt_rater_exists){
        if($('.rt_embed_flash_rater_class').length >0){
            $(document).mouseup(function(){              
              var obj=  $('.rt_embed_flash_rater_class');
                if(obj){
                    if(obj.length && obj.length >0){
                        for(i=0;i<obj.length;i++){
                           if(obj[i].SetVariable){
                                obj[i].SetVariable("rater_mouseup", 'stop&submit'); 
                           } 
                        }        
                    }
                }        
            });       
        }
    }               
 });          
          