// 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;
}



/*
* 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://www.davidsonccc.edu/images/loading.gif', alt: 'loader' })
        .css({ position: 'absolute', 'margin-left': '5px' });
}

// 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

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();
    });


    // 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>');
        });
    }


    // 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() { });

});


