
// CALLS

jQuery(function($) {

	// doubleclick ads

	$(".refreshAds").click(function(){
		var bAlert = false;
		
		/* Google Hit */
		if (typeof _gaq != 'undefined') {
			var ga_account = document.getElementById("ga_hidden")
			if(ga_account) {
				_gaq.push(['_setAccount', ga_account.value]);
				_gaq.push(['_trackPageview']);
				if (bAlert) {alert('Google Hit: ' + ga_account.value);}
			}
		}
		
		/* Omniture Hit */
		if (typeof s != 'undefined') {
			void(s.t());
			if (bAlert) {alert('Omniture Hit: ' + s.pageName);}
		}

		/* Refresh Ads */
		var iframe = document.getElementById("frameads")
		
		if(iframe) {iframe.src = "/includes/doubleclickad.htm";}
		
		jQuery.each($(".adFrame"), function() {
			$(this).attr({
				src: $(this).attr("src")
			});
		});
	});

// masthead

	$(".dropTab").each(function(){
		var tab = $(this).find("a");
		var swf = $(this).find(".swfHolder");

		$(this).click(function(){
			closeTab();
			swf.show().bgiframe();
			tab.addClass("open");
			return false;

		}, function(){
			closeTab();
			return false;
		});
	});


// main navigation

	$(".mainPanelNav .mainLink").each(function(i) {
		var navPanel = $(this).siblings(".navPanel");
		var rollover = $(this);
		$(this).parents("li").hoverIntent(function(){
		navPanel.css({'left':'0'}).bgiframe();
			rollover.addClass("active");
		}, function() {
		navPanel.css({'left':'-9999em'});
			rollover.removeClass("active");
		});
	});

// equalize columns

	$('.cmsColumn_1, .cmsColumn_2').matchHeights();
	
	$('.cmsCenter, .cmsRight').matchHeights();
	$('.cmsCenter').each(function(){
		var adjheight = $(this).height();
		$(this).css({'min-height': adjheight - 66});
	});
	
// set news image float width

	var newsImgWidth = $(".newsPhotoRight img").width() + 6;
	$(".newsPhotoRight").css("width",newsImgWidth);

// START Media Wall
    $(".mediaWallThumbs").each(function() {
        PauseToggle = 0
        var galleryNav = $(this);
        var galleryNavWrap = ".mediaWallThumbs";
        var galleryCycleWrap = $(".mediaWallCycleWrpr");
        var gallerySize = 4
        galleryNav.scrollable({
            //loop: true,
            size: gallerySize,
            items: ".items",
            clickable: false,
            onSeek: function (){
                   setToolTipRighPosition(galleryNav);
            }
       
        }).find(".scrollable .items a").tooltip({delay: 1, tip: '#tooltip', relative: false, offset: [7, 85]});  
       
        var galleryNavAPI = galleryNav.scrollable({ api: true });

        setToolTipRighPosition(galleryNav);
	
        galleryCycleWrap.cycle({
            
            manualTrump: true,
            timeout: 0,
            //delay:3000,
            speed: 0,
            slideExpr: '.mediaWallCycleItem',
            next: '.mwBtnFakeForward',
            prev: '.mwBtnFakeBack',
            pager: galleryNav.find('.items'),
            pause: 1,
            fastOnEvent: 10,
            before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
		$("div.mediaWallVideoCue",$(currSlideElement)).toggle(true);
            	galleryCycleWrap.cycle('pause');    
		var firstslide = $('.mediaWallStage:first')
		$(nextSlideElement).find('.mediaWallStage').fadeIn('slow', function() {
			galleryCycleWrap.cycle('resume');
		});
                var currentSlideIndex = $(".mediaWallCycleItem").index(nextSlideElement);
                var navGroupAmount = galleryNav.find(".galleryIndexNav:first li").size();
                var setPage = currentSlideIndex / navGroupAmount + 0.1;
                var lastSlideItem = $(".mediaWallCycleItem:last"); 
                var lastItemIndex = $(".mediaWallCycleItem").index(lastSlideItem) +1;
                var  whichWay = forwardFlag                   

                if (whichWay == true && currentSlideIndex > 0) {
                    if (currentSlideIndex%gallerySize == 0)  {galleryNavAPI.nextPage()};
                }
                if (whichWay == false) {
                    if (currentSlideIndex%(gallerySize-1) == 0)  {galleryNavAPI.prevPage()};
                }

                if (currentSlideIndex == (lastItemIndex-1))  {galleryNavAPI.end()};
                if (currentSlideIndex == 0) {galleryNavAPI.begin()};
                            
            },
            pagerAnchorBuilder: function(idx, slide) {
                return galleryNavWrap + ' .items li:eq(' + idx + ') a';
            }
        });


        $(".mwBtnBack").hover( 
            function () {$(this).css("background-position","0px -26px");},
            function () {$(this).css("background-position","0px 0px");}
        );

        $(".mwBtnForward").hover( 
            function () {$(this).css("background-position","-74px -26px");},
            function () {$(this).css("background-position","-74px 0px");}
        );

        $(".mwBtnPause").hover( 
            function () {$(this).css("background-position","-21px -26px");},
            function () {
                if (PauseToggle != 1) {
                    $(this).css("background-position","-21px 0px");
                }
            }
        );
        
        $(".mwBtnPause").click( 
            function () {
				if (PauseToggle != 1) {
					galleryCycleWrap.cycle('pause');
					$(".mwBtnPause").css("background-position","-21px -26px");
					PauseToggle = 1
				} else {
					galleryCycleWrap.cycle('resume');
					$(".mwBtnPause").css("background-position","-21px 0px");
					PauseToggle = 0
				}
            }
        );
        
        $(galleryNavWrap).mouseenter(function() {
            galleryCycleWrap.cycle('pause');
        }).mouseleave(function() {
            galleryCycleWrap.cycle('resume');
        });

        var giHeight = $(".items ul li", this).height();
        $(this).css({ 'height': giHeight });
	$(".mwBtnBack").click(function () {galleryNavAPI.prevPage();});
        $(".mwBtnForward").click(function () {galleryNavAPI.nextPage();});
    });


    function setToolTipRighPosition(galleryNav) {     
        var FirstLastGalleryNavAPI = galleryNav.scrollable({ api: true });

           // Get the first and last visible srollable items
        var listScrollableItem = FirstLastGalleryNavAPI.getVisibleItems(),
        lastScrollableItem = listScrollableItem.filter(":last"); 

        var mediaThumbsNumb = $(".mediaWallThumbs .scrollable .items a").length;
        
        //alert(mediaThumbsNumb);
         
        if (mediaThumbsNumb != 0) {
            var toolTipLastApi = $(".mediaWallThumbs .scrollable .items a").tooltip($(".mediaWallThumbs .scrollable .items li").index(lastScrollableItem))
        
            //console.log($(".scrollable .items li").index(lastScrollableItem));
        
        
            $(".scrollable .items a").each(function(){
				    var toolAPI = $(this).tooltip({api: true});
				    toolAPI.unbind("onShow");
            });
                    
            toolTipLastApi.onShow(function(){
                $("#tooltip").addClass("left");                   
                var tooltipoffset = $("#tooltip").offset()
                var tooltipleft = tooltipoffset.left - 170
                $("#tooltip.left").css("left",tooltipleft);
                
             }).onBeforeHide(function(){
                 $("#tooltip").removeClass("left");                   
             });
        }
        
    };
    
    
    $(".mediaWallThumbs .scrollable .items a").mouseleave(function(){
        $("#tooltip").removeClass("left");                   
    })

    $(".mediaWallVideoPlay").mouseover(function(){
    	$(this).addClass("mediaWallVideoPlayHover");
    }).mouseout(function(){
    	$(this).removeClass("mediaWallVideoPlayHover");		
    });
    
	$(".mediaWallVideoPlay").click(function () {

		var $div = $(this).parent();

		$div.hide();

		//Goofy FF bug...need a delay here. For once IE does something right!
		window.setTimeout("playVideo('video" + $div.attr("videoid") + "');",1);

		var videoId = $(this).parent().attr("videoid");
		updateVideoViewCount(videoId);
		pauseMediaWall();

	});

	$("ul.galleryIndexNav li a").click(function(e) {
		var current = $(this).parent();
		var index = current.parent().children().index(current);

		var div = $("div.mediaWallCycleWrpr div.mediaWallCycleItem:eq(" + index + ")");
		var divOverlay = $("div.mediaWallVideoCue", div);

		if (divOverlay) {divOverlay.toggle(true);}

	});


    // END Media Wall

	//Begin blogs
	$('#blog_archive li.blog_archive_month').toggle();
    $('#blog_archive li.blog_archive_story').toggle();

    $('#blog_archive img.blog_archive_year_link').bind('click', function() {
        if($('#blog_archive li.blog_archive_month').is(':hidden')){
            $(this).attr('src', '/cms/images/arrow_open.gif');            
        }else{
            $(this).attr('src', '/cms/images/arrow_closed.gif');
            $('#blog_archive img.blog_archive_month_link').attr('src', '/cms/images/arrow_closed.gif');
        }
                
        $('#blog_archive li.blog_archive_month').toggle();
        $('#blog_archive li.blog_archive_story').toggle();
        return false;
    });

    $('#blog_archive img.blog_archive_month_link').bind('click', function() {
        if ($('#blog_archive li.blog_archive_story').is(':hidden')) {
            $(this).attr('src', '/cms/images/arrow_open.gif');
        } else {
            $(this).attr('src', '/cms/images/arrow_closed.gif');
        }
    
        $('#blog_archive li.blog_archive_story').toggle();
        return false;
    });
	//End blogs


// moh carousel
    $(".mohCarousel .scrollable").scrollable({
        size: 4,
        items: ".mohItems"
    }).circular().navigator();

// boh promo carousels

    $(".promoCarousel .scrollable").scrollable({
        size: 1,
        items: ".promoItems"
    }).autoscroll({
    	interval: 8000
    }).circular().navigator();

    $(".promoCarousel2 .scrollable").scrollable({
        size: 1,
        items: ".promoItems"
    }).autoscroll({
    	interval: 8000
    }).circular().navigator();


// shop application

	$('#shopAppSSW').cycle({
		fx: 'fade',
		speed: 800,
		timeout: 6000,
        prev:   '.shopAppBack',
        next:   '.shopAppNext',
		before: 	function(currSlideElement, nextSlideElement, options, forwardFlag) {
			var aLocation = $(this).find('a').attr('href');
			$(".shopAppView").attr('href',aLocation);
		}
	});


});


// FUNCTIONS

// protennislive.com popup window

	function openLSWindowTandR(year, wkno, lang, tabno, eventid, ref_file, width, height, hasScrollBars) {
		var theWidth = width;
		var theHeight = height;
		var scrollBars = "scrollbars";
		if (hasScrollBars == false) scrollBars = "scrollbars=0";
		if ((theWidth == "")||(theWidth == null)) theWidth =500;
		if ((theHeight == "")||(theHeight == null)) theHeight =750;
		var theLeft = (screen.availWidth - theWidth)/2;
		var theTop = (screen.availHeight - theHeight)/2;
		var strCheckRef = escape(ref_file);
		var lsURL = "http://www.protennislive.com/frameset.asp?year="+year+"&wkno="+wkno+"&lang="+lang+"&tabno="+tabno+"&eventid="+eventid+"&ref="+strCheckRef;
		var popupWin = window.open(lsURL, '_' + Math.round(Math.random() * 1000000),'top='+theTop+',left='+theLeft+',menubar=0,toolbar=0,location=0,directories=0,status=0,'+scrollBars+',width='+theWidth+', height='+theHeight);
	}

