$(function () {
    var timeout = 500,closetimer = 0,ddmenuitem = 0,ddmenuitem2 = 0;

    function top_menu_open() {
        top_menu_canceltimer();
        top_menu_close();
        $(this).addClass('active');
        if ($('select#pr_year')) { $('select#pr_year').blur() }
        if ($('select#pr_month')) { $('select#pr_month').blur() }
        if ($('select#pr_sp_s')) { $('select#pr_sp_s').blur() }
        if ($('select#lib_technology')) { $('select#lib_technology').blur() }
        if ($('select#lib_event')) { $('select#lib_event').blur() }
        if ($('select#lib_year')) { $('select#lib_year').blur() }
    }

    function top_menu_close() {
        $('#top_menu > li').removeClass('active');
    }

    function top_menu_timer() {
        closetimer = window.setTimeout(top_menu_close, timeout);
    }

    function top_menu_canceltimer() {
        if (closetimer) {
            window.clearTimeout(closetimer);
            closetimer = null;
        }
    }

    $('#top_menu > li').bind('mouseover', top_menu_open);
    $('#top_menu > li').bind('mouseout', top_menu_timer);
    $(document).bind('click', top_menu_close);


    // adds 'current' class to the top menu button of the section we're on
    var path_regex = /(cn|de|fr|in|jp|kr|tw|us)\/(.+?)\//;
    var path_parts = location.pathname.substring(1).match(path_regex);
    if (path_parts && path_parts[2] && path_parts[1]) {
        var matchingstring = '/' + path_parts[1] + '\/' + path_parts[2] + '/';
        var secondregex = new RegExp(matchingstring);
        $('ul#top_menu>li>a').each(function () {
            if (this.href.match(secondregex)) {
                $(this).addClass('current');
            }
            if (this.href.match('library') && path_parts[2] == 'downloads') {
                $(this).addClass('current');
            }
        });
    }


    // for the dynamic "read more" text block
    $('.read_more_text').hide();
    $('<div class="read_more"><span class="closed">Read More</span></div>').insertBefore('.read_more_text');

    // for the dynamic "read more" FAQ
    $('.read_more_content').hide();

    // controls the arrow pointing and displays hidden text
    $('.read_more').toggle(function() {
        $(this).children('.closed').removeClass('closed').addClass('open');
        $(this).next().slideToggle('fast');
    }, function() {
        $(this).children('.open').removeClass('open').addClass('closed');
        $(this).next().slideToggle('fast');
    });


    // image rotator  ( cycle function is defined in jquery.cycle.js file)
    $('div.image_rotator').cycle({
        fx:     'fade',                 // ratation effect
        speed:   300,                   // speed of image rotation
        timeout: 5000,                  // will automatically rotate images after 5 seconds
        next:   'div.image_rotator',    // enables user to click on image/div to manual advance
        pause: 1 // allows mouse hover to pause the rotating
    });



    // Video Player Controls
    //
    //      Declare defaults for video width and height
    var defaultVideoWidth = 550,defaultVideoHeight = 333,tvHeight = 436;

    //      Assign default players for media
    $.fn.media.defaults.flvPlayer = '/assets/js/mediaplayer/player-licensed.swf';
    $.fn.media.defaults.mp3Player = '/assets/js/mediaplayer/player-licensed.swf';

    //      Determine the height of the video, based on whether the aspect ratio
    //      is "media"(4:3) or "medialetterbox" (16:9)
    function determineVideoHeight ( aspectRatio ) {
        var height = defaultVideoHeight; // for videos with letterbox aspect ratio (16:9)
        if (aspectRatio == "media") {
            height = tvHeight; // for videos with old TV aspect ratio (4:3)
        }
        return height;
    }

    //      Play the video using jquery.media plug-in. See jquery.media for
    //      instructions for using the .media() menthod.
    function playVideo( viddiv, vidwidth, vidheight, vidfile ) {
        $( viddiv ).media({
            src: vidfile,
            width: vidwidth,
            height: vidheight,
            autoplay: true,
            params: {
                allowfullscreen: true,
                allowscriptaccess: 'always'
            },
            flashvars: {
                autostart: 'true',
                plugins: 'viral-2,gapro-1',
                'gapro.accountid': 'UA-5962948-1',
                'gapro.trackpercentage': true,
                'gapro.tracktime': true,
                'viral.functions': 'embed,link',
                'viral.callout': 'none',
                'viral.onpause': false
            }
        });
    }



    //  Video Abstract Page Controls
    //
    $('.media a, .medialetterbox a').each( function() {

        //      When we're within Publish, the link's href will be relative so therefore not display.
        //      For the Publish environment, we remove the "pub:" from the "rel" value which gives us
        //      an absolute url to the video. Finally, we add a prefix to the url so that Publish will
        //      understand it relative to Publish's site root.
        var js_root = location.href.replace( /(^.*sp_id=[a-z0-9]+-[a-z0-9]+).*$/, "$1" );
        if ( js_root.match( /\/center\/publish\//gi ) ) {
            var my_rel = $(this).attr('rel');
            var new_href = my_rel.replace( /^pub:(.*)$/, "$1" );
            $(this).attr('href', js_root + new_href);
        }

        //      remove text from link and play video
        $(this).text('');
        playVideo( $(this), defaultVideoWidth, defaultVideoHeight, $(this).attr('href') );

    });




    //  Video Carousel
    //
    //      Check to see if the video_carousel div exists on this page.  If so, grab path to video
    //      carousel snippet from link within the video_carousel div.
    var carousel_file = false;
    if ($('div.video_carousel a.carousel_file').length) { // will be false if the element doesn't exist

        //  Within Publish, we need to massage the url so that it will display.  First, if we find "/center/publish/"
        //  in the url of our current location, we know we're in Publish. We then remove the "?spk=1" from the
        //  end of the url, if it exists. Next, we remove the "http://rambus.com" from the beginning of the url.
        //  Finally, we add the publish prefix to the front of the URL.
        var js_root = location.href.replace( /(^.*sp_id=[a-z0-9]+-[a-z0-9]+).*$/, "$1" );
        var rawUrl = $( 'div.video_carousel a.carousel_file' ).attr( 'href' );
        if ( js_root.match( /\/center\/publish\//gi ) ) {
            rawUrl = rawUrl.replace( /\?.*$/, '' );  //remove everything after the "?"
            rawUrl = rawUrl.replace( /http:\/\/.*.com/, '' ); //remove everything before the root directory
            rawUrl = js_root + rawUrl;
        }
        carousel_file = rawUrl + " div#loadable_content";

        // replaces <div.video_carousel> with the contents of the video carousel file
        $('div.video_carousel').load(carousel_file, function () {

            // if there are 3 or fewer carousel items, don't show prev and next buttons
            if ($(".jCarouselLite ul li").length <= 3) {
                $(".prev, .next").css('display', 'none');
            }

            // add the .next or .prev class to the buttons, which controls the scrolling
            $(".jCarouselLite").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev"
            });

            // if we're in Publish, massage the urls of the links and images like we did above
            if ( js_root.match( /\/center\/publish\//gi ) ) {
                $('div.jCarouselLite a.video-link').each( function() {
                    var temp_href = $(this).attr('href');
                    temp_href = temp_href.replace( /http:\/\/.*.com/, js_root );
                    $(this).attr( "href", temp_href );
                });
                $('div.jCarouselLite img.thumbnail').each( function() {
                    var temp_src = $(this).attr('src');
                    temp_src = temp_src.replace( /[\.\.\/]*/, js_root+'/' );
                    $(this).attr( "src", temp_src );
                });
            }

            // when clicked, will replace default image with video player which will start automatically
            $('div.jCarouselLite a.video-link').click(function () {

                // make sure that Flash is installed
                flashplayerVersion = swfobject.getFlashPlayerVersion();
                if (flashplayerVersion.major > 6) {

                    // remove any existing html
                    $(".video_screen *").remove();

                    var video_file = $(this).attr('href'); // grab path of video file
                    var video_title = $(this).children('div.title').html(); // grab video title
                    var video_aspect_ratio = $(this).children('div.aspect_ratio').html(); // grab video aspect ratio

                    // determine height of media player window, based on aspect ratio
                    var video_height = determineVideoHeight( video_aspect_ratio );

                    // play video
                    playVideo( '.video_screen', defaultVideoWidth, video_height, video_file );

                    // Place the headline of this video as a sibling just before the <object> in the video_screen div
                    $('<h3 class="video_title">' + video_title + '</h3>').insertBefore('.video_screen object');

                } // end of if statement checking for flash version
                return false; // make sure to prevent the link from working
            }); // end of ('div.jCarouselLite a.video-link').click function
        }); // end of ('div.video_carousel').load function
    } // end of if statement checking for video_carousel div
}); // end of $(document).ready function

