var loc = document.location + ""
var jsNothing = "javascript://"
var sliding = 0
var bookmarkLoading = 0

$(document).ready(function() { init() })

//main event initilization
function init() {
    //adjust tab menus
    var menuWidth
    var menuLength
    var newWidth
    $('.tabMenu').each(function() {
        if (!$(this).hasClass('noFormat')) {
            menuWidth = ($(this).width() / 100);
            menuLength = $(this).find('ul li').length
            menuPercent = parseInt((1 / menuLength) * 100)
            newWidth = parseInt((100 / menuLength) * menuWidth)
            if (newWidth == 0) {
                $(this).find('ul li').css('width', menuPercent + '%')
            }
            else {
                $(this).find('ul li').css('width', newWidth + 'px')
            }
            $(this).find('ul li:last a').css('margin-right', '0')

        }
    })


    preLoad("BGFeaturedEpisodeExpanded.jpg") // image preloaded, accepts comma-delimited values
    window.setTimeout(function() { initScrollPanels(); initScrollbars() }, 1000)
    columnify() //break long drop-downs into columns
    initDD($('.mnuDestination')) //choose a detination drop-down
    initDD($('.chooseRegion'))
    initDD($('.chooseCounty'))
    //set date selection drop-downs
    $('.hasDD').each(function() {
        initDD(this)
    })
    initHiddenDialog() //hook up all hidden dialog events
    initSetVal() //drop downs that emulate <select>		
    initTopBanner() //animate top banner ad.
    initTabPanels() //all tab panels, hook up tabs
    initPanelList() //horizontal scroll buttons
    initTopSlider() //top of home page, right slider
    initPlayerSwitch() //buttons on video players
    initChooseRegion() //drop-down for choose region
    initChooseCounty() //drop-down for choose region
    initSiteMap() // open/close sections on site map
    initBottomPanels()	//paging controls for bottom RSS lists
    initSearchResults()
    detectBookmark()
    //fix travel guide titles
    if ($('.guideItem').length) {
        $('.guideItem').find('h3').each(function() {
            truncateText($(this), 27)
        })
    }
    $('.clear').css('height', '0')
    initUploadPanels()

    initImg()//fix display issue when <img> src is null;



}

function initImg() {
    $('img').each(function() {
        var src = $(this).attr('src');
        if (src == '') {
            $(this).css('display', 'none');
        }
    });
}

function initDestinationFeaturedVideos() {

    $('.destRight .scrollLeft').css('visibility', 'hidden'); //left button is hiden at the first;

    $('.destRight .scrollRight').click(function() {

        $('.destRight .scrollLeft').css('visibility', 'visible');
        var margainLeft = $('.destRight .scrollPanel ul').css('margin-left').replace('px', '');
        var moveLeft = margainLeft - 430;
        $('.destRight .scrollPanel ul').css('margin-left', moveLeft + 'px');

        var amount = $('.destRight .scrollPanel ul li').length;
        var currentNum = (-1 * (moveLeft / 430) + 1) * 3;
        if (amount <= currentNum) {
            $('.destRight .scrollRight').css('visibility', 'hidden');
        }

    });

    $('.destRight .scrollLeft').click(function() {

        $('.destRight .scrollRight').css('visibility', 'visible');
        var margainLeft = $('.destRight .scrollPanel ul').css('margin-left').replace('px', '');
        var moveRight = parseInt(margainLeft) + 430;
        $('.destRight .scrollPanel ul').css('margin-left', moveRight + 'px');

        var amount = $('.destRight .scrollPanel ul li').length;
        var currentNum = (-1 * (moveRight / 430)) * 3;
        if (currentNum <= 0) {
            $('.destRight .scrollLeft').css('visibility', 'hidden');
        }
    });

}

function initUploadPanels() {
    $('.uploadMedia input:checkbox').click(function() {
        $(this).parent().find('.uploadPanel').toggle()
    })
}



function initHiddenDialog() {
    $('a.openDialog').click(function() {
        openDialog($(this).next('div.hidden'))
    })

    $('a.popUpEvents').click(function() {
        openDialog($(this).next('div.hidden'))
    })

}


function initSetVal() {
    //initialize drop-downs that set hidden value
    $('.setVal').each(function() {
        var target = $(this).parent().find('.dd input')
        $(this).parent().find('.dd ul li a').click(function() {
            //set hidden field
            if (target.hasClass('index')) {
                //find ordinal value of selected item
                var wrapper = target.next()
                for (var x = 0; x < wrapper.children().length; x++) {
                    if (wrapper.children().eq(x).children().html() == $(this).html()) {

                        target.attr('value', x + 1)
                    }
                }
            }
            else {
                target.attr('value', $(this).html())
            }
            //set header label
            target.parent().prev().html($(this).html())
            target.parent('.dd').hide()
        })
    })
}


function initTopBanner() {
    $('.bannerWide a.opener').click(function() {
        target = $('.wildernessAd')
        var startHeight = target.css('min-height')
        var endHeight = target.css('height')
        target.css('height', startHeight)
        target.parent().removeClass('hidden')
        target.animate({
            height: endHeight
        }, 800, function() {
            window.setTimeout(function() { closeTopBanner(startHeight, endHeight) }, 7000)
        });
    })
    $('.bannerWide a.closer').click(function() {
        closeTopBanner()
    })

}

function closeTopBanner(minHeight, height) {
    target = $('.wildernessAd')
    target.animate({
        height: "30px"
    }, 800, function() {
        $('.wildernessAd').parent().addClass('hidden')
        $('.wildernessAd').css('min-height', minHeight)
        $('.wildernessAd').css('height', height)
    });
}


function homeEpisode(element, target, filename, autoPlay) {
    var title = $(element).find('.eTitle').html()
    $('.featuredEpisodeWrapper h3.title').html(title)
    playVideo(target, filename, autoPlay)
}

function setEpisode(element) {

    var content = $(element).next().html()
    if (!$('.inThisEpisodeWrapper').length) {
        //home page player

        $('.featuredEpisodeWrapper').find('.showDetails').children().children().html(content)
        var title = $('.featuredEpisodeWrapper').find('.showDetails').children().children().find('h3').eq(0).html()
        $('.featuredEpisodeWrapper h3.title').html(title)
        $('.featuredEpisodeWrapper').find('.showGuide').find('a').eq(0).click()
        if ($(element).parent().find('.relatedDestinations').length) {
            var content = $(element).parent().find('.relatedDestinations').find('.episodeDestinations').html()
            $('.episodeDestinations.wrapper').html(content)
        }
        else {
            $('.episodeDestinations.wrapper').html("")
        }

    }
    else {
        $('.inThisEpisodeWrapper').find('.showDetails h3').eq(0).remove()
        $('.inThisEpisodeWrapper').find('.showDetails .fb').eq(0).remove()
        $('.inThisEpisodeWrapper').find('.showDetails .alt').eq(0).remove()
        $('.inThisEpisodeWrapper').find('.showDetails a').eq(0).remove()
        $('.inThisEpisodeWrapper').find('.showDetails .sliderTrack').eq(0).css('margin-top', '85px')
        $('.inThisEpisodeWrapper').find('.showDetails .sliderHandle').eq(0).css('top', '0px')
        $('.inThisEpisodeWrapper').find('.showDetails .tabPanel').eq(0).css('height', '258px')
        $('.inThisEpisodeWrapper').find('.showDetails .tabPanel').html(content)
    }


}

function columnify() {
    //make a long ul list into a number of shorter ones
    var listMax = 20
    var colSize = 10
    var colCount = 10
    var output
    $('.dd.selPanel ul').each(function() {

    	if ($(this).find('li').length > listMax) {
    		target = $(this)
    		//target.parent().addClass('selPanel')
    		output = "<ul>"
    		colCount = 10
    		for (var x = 0; x < target.children().length; x++) {
    			output = output + "<li>" + target.children().eq(x).html() + "</li>"
    			colCount--
    			if (!colCount) {
    				colCount = colSize
    				output = output + "</ul>"
    				if (x < target.children().length - 1) {
    					output = output + "<ul>"
    				}
    			}
    		}
    		
    		output = output + "</ul><div class='clear'></div>"
    		target.parent().html(output)
    	}


    })
}


function truncateText(element, maxHeight) {
    //truncate overflowing items
    if ($(element).hasClass('adj')) {
        return
    }
    var myHeight
    var limit = 50
    var attempts = 0
    var target
    $(element).addClass('adj')

    var myHeight = element.height()
    while (myHeight > maxHeight && attempts < limit) {
        //element.css('background-color','#ffff00')
        var target = element.html().replace("&hellip;", "")
        var wordArr = target.split(" ")
        wordArr.length = wordArr.length - 1
        element.html(wordArr.join(" ") + "&hellip;")
        myHeight = element.height()
        attempts++
    }
    //element.css('height', element.parent().height() + 'px')
    if (attempts > 0) {

    }

}


function truncateItems(targetPanel, maxHeight) {
    //truncate overflowing items
    if ($(targetPanel).hasClass('adj')) {
        return
    }
    var myHeight
    var limit = 50
    var attempts = 0
    var target
    var wasHidden
    $(targetPanel).addClass('adj')
    $(targetPanel).find('dd a').each(function() {
        element = $(this)
        wasHidden = 0
        attempts = 0
        if (element.parent().hasClass('hidden')) {
            element.parent().removeClass('hidden')
            wasHidden = 1
        }
        var myHeight = element.height()
        while (myHeight > maxHeight && attempts < limit) {
            //element.css('background-color','#ffff00')
            var target = element.html().replace("&hellip;", "")
            var wordArr = target.split(" ")
            wordArr.length = wordArr.length - 1
            element.html(wordArr.join(" ") + "&hellip;")
            myHeight = element.height()
            attempts++
        }
        element.parent().prev().css('height', element.parent().height() + 'px')

        if (wasHidden) {
            element.parent().addClass('hidden')
        }
    })

}


function makeBookmark() {
    var filename = "sba1002_2vacation.flv"
    var loc = document.location = ""
    if (loc.indexOf("#")) {
        temp = loc.split("#")
        loc = temp[0]
    }
    window.location.hash = "#" + filename
}

function detectBookmark() {
    //detect hash mark and attemp to find resource in this page
    var resource
    var temp
    if (loc.indexOf("#")) {
        temp = loc.split("#")
        resource = temp[1]
        var target = $('#root').find("a:[onclick*='" + resource + "']").eq(0)
        if (target.length) {
            bookmarkLoading = 1
            window.setTimeout(function() { target.trigger('click') }, 2500)
        }

    }
    //
    //set up existing bookmarks
    $('a.canBookmark').click(function() {
        var filename = $(this).attr('href').replace("javascript://", "")
        window.location.hash = filename
    })
}


function initSearchResults() {
    $('.searchResults').find('a.moreSR').click(function() {
        $(this).parent().prev().children().show()
        $(this).hide()
    })
}

function expandPlayer() {
    var target = $('.featuredEpisodeWrapper')
    target.css('background-image', 'url(../Images/BGFeaturedEpisodeExpanded.jpg)')
    target.animate({
        height: '525px'
    }, 800, function() {
        target.find('.tabbedScroller').fadeIn('slow')
    });
}

function preLoad(imgList) {
    //image preloader
    var iTemp = []
    imgList = imgList.split(",")
    for (var x = 0; x < imgList.length; x++) {
        iTemp[x] = new Image
        iTemp[x].src = "/Images/" + imgList[x]
    }

}


function doSearch(element) {
    var searchTerm = $('#subNav').find('.search').val()
    if (searchTerm != null && searchTerm != "") {
        document.location = "Search.aspx?s=" + escape(searchTerm)
    }
}

function playVideo_FirstLoad(container, fileName, autoPlay) {

    if (fileName.indexOf('.mp3') > 0) {
        var fv = '<object type="application/x-shockwave-flash" data="/Flash/player_mp3_mini.swf" width="400" height="20">'
        fv = fv + '<param name="movie" value="/Flash/player_mp3_mini.swf" />'
        fv = fv + '<param name="bgcolor" value="000000" />'
        fv = fv + '<param name="FlashVars" value="mp3=#M#" />'
        fv = fv + '</object>'
        container = "audioPlayer"
    }
    else {
        var fv = "<div style='width:400px;height:280px; position:relative; z-index:1;'><div style='position:absolute; height:249px; width:400px; top:0px; left:0px; z-index;9;'><object width='400' height='249' id='flvPlayer'>"
        fv = fv + "<param name='allowFullScreen' value='true'>"
        fv = fv + "<param name='wmode' value='opaque'>"
        fv = fv + "<param name='allowScriptAccess' value='always'>"
        fv = fv + "<param name='movie' value='/Flash/OSplayer.swf?movie=" + fileName + "&btncolor=0x333333&accentcolor=0x31b8e9&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=" + autoPlay + "&vTitle=#T#&showTitle=yes'>"
        fv = fv + "<embed src='/Flash/OSplayer.swf?movie=" + fileName + "&btncolor=0x333333&accentcolor=0x31b8e9&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=" + autoPlay + "&vTitle=#T#&showTitle=yes' width='400' height='249' allowFullScreen='true' wmode='opaque' type='application/x-shockwave-flash' allowScriptAccess='always'>"
        fv = fv + "</object></div>";
        fv = fv + "<div style='position:absolute; height:249px; width:400px; top:0px; left:0px; z-index;99; cursor:pointer;background-image:url(../Images/trans.png);	background-position:left center;	background-repeat:repeat;' onclick='javascript:playVideo(\"" + container + "\",\"" + fileName + "\", \"on\")'></div></div>"

    }
    var videoTemp
    if (container == "lightBox") {
        if (!$('#videoTemp').length) {
            $(document.body).append('<div id="videoTemp"></div>')
        }
        fv = fv + "<a href='javascript://' class='closeB' onclick='closeDialog()'></a>"
        videoTemp = fv.replace("'400'", "'640'")
        videoTemp = videoTemp.replace("'249'", "'360'")
        $("#videoTemp").html(videoTemp.replace('#M#', fileName))
        openDialog($('#videoTemp'))
        return
    }
    else {
        if (autoPlay == 'on') {
            $('.featuredEpisodeWrapper').css('background-image', 'url(../Images/BGFeaturedEpisodeExpandedActive.jpg)')
        }
    }

    $("#" + container).html(fv.replace('#M#', fileName))
    //$("#" + container).html(fv.replace('#M#', fileName))

}


function playVideo(container, fileName, autoPlay) {
    if (fileName.indexOf('.mp3') > 0) {
        var fv = '<object type="application/x-shockwave-flash" data="/Flash/player_mp3_mini.swf" width="400" height="20">'
        fv = fv + '<param name="movie" value="/Flash/player_mp3_mini.swf" />'
        fv = fv + '<param name="bgcolor" value="000000" />'
        fv = fv + '<param name="FlashVars" value="mp3=#M#" />'
        fv = fv + '</object>'
        container = "audioPlayer"
    }
    else {
        var fv = "<div style='width:400px;height:280px'><object width='400' height='249' id='flvPlayer'>"
        fv = fv + "<param name='allowFullScreen' value='true'>"
        fv = fv + "<param name='wmode' value='opaque'>"
        fv = fv + "<param name='allowScriptAccess' value='always'>"
        fv = fv + "<param name='movie' value='/Flash/OSplayer.swf?movie=" + fileName + "&btncolor=0x333333&accentcolor=0x31b8e9&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=" + autoPlay + "&vTitle=#T#&showTitle=yes'>"
        fv = fv + "<embed src='/Flash/OSplayer.swf?movie=" + fileName + "&btncolor=0x333333&accentcolor=0x31b8e9&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=" + autoPlay + "&vTitle=#T#&showTitle=yes' width='400' height='249' allowFullScreen='true' wmode='opaque' type='application/x-shockwave-flash' allowScriptAccess='always'>"
        fv = fv + "</object></div>"

    }
    var videoTemp
    if (container == "lightBox") {
        if (!$('#videoTemp').length) {
            $(document.body).append('<div id="videoTemp"></div>')
        }
        fv = fv + "<a href='javascript://' class='closeB' onclick='closeDialog()'></a>"
        videoTemp = fv.replace("'400'", "'640'")
        videoTemp = videoTemp.replace("'249'", "'360'")
        $("#videoTemp").html(videoTemp.replace('#M#', fileName))
        openDialog($('#videoTemp'))
        return
    }
    else {
        if (autoPlay == 'on') {
            $('.featuredEpisodeWrapper').css('background-image', 'url(../Images/BGFeaturedEpisodeExpandedActive.jpg)')
        }
    }

    $("#" + container).html(fv.replace('#M#', fileName))
    //$("#" + container).html(fv.replace('#M#', fileName))

}


function initBottomPanels() {
    var listHeight = 0
    var limit = 3
    $('.bottomPanel .tabPanel dt').each(function() {
        $(this).css('height', $(this).next().height() + 'px')
    })
    $('.bottomPanel .tabPanel dl').each(function() {

        var myList = $(this).children('dt')
        var range = ""
        var pages = parseInt(myList.length / limit)
        var startPage = limit + 1
        var endPos
        if (myList.length > limit) {
            range = range + "<a class='range down' style='display:none' onclick='bPage(this,0)'>1 - 3</a>"
            for (var x = limit; x < myList.length; x++) {
                $(this).children('dd').eq(x).addClass('hidden')
                $(this).children('dt').eq(x).addClass('hidden')
            }

            for (var x = 0; x < pages; x++) {
                endPos = limit
                if (x == pages - 1) {
                    endPos = parseInt(myList.length % limit)
                }
                if (startPage == startPage + endPos) {
                    //range = range + "##<a class='range' style='display:none' onclick='bPage(this," + (x + 1) + ")'>" + startPage + "</a>"
                }
                else {
                    range = range + "<a class='range' style='display:none' onclick='bPage(this," + (x + 1) + ")'>" + startPage + " - " + (startPage + endPos - 1) + "</a>"
                }
                startPage = startPage + limit
            }
            $(this).parent().find('.bottomNav').html(range + "<div class='clear'></div>")
            //$(this).parent().find('.bottomNav').find('.range').eq(0).show()
            $(this).parent().find('.bottomNav').find('.range').eq(1).show()
        }
        else {
            $(this).parent().find('.bottomNav').hide()
        }

    })
}


function bPage(element, page) {
    var limit = 3
    var startPos = page * limit
    var myList = $(element).parent().parent().find('dl')
    myList.children().addClass('hidden')
    for (var x = startPos; x < startPos + 3; x++) {
        myList.children('dd').eq(x).removeClass('hidden')
        myList.children('dt').eq(x).removeClass('hidden')
    }
    //manage button visibility
    var buttons = $(element).parent().find('.range');
    buttons.hide()
    buttons.removeClass('down')
    buttons.eq(page - 1).addClass('down')
    buttons.eq(page - 1).show()
    buttons.eq(page + 1).show()


}


function initSiteMap() {
    $('siteMap ul li h2 a').click(function() {
        $(this).toggleClass('active'); $(this).parent().parent().toggleClass('active')
    })
}


function initTopSlider() {
    $('.topFeature ul').click(function() {
        //var target = this;
        if ($(this).css('marginLeft') == "667px") {
            newPos = '906px'
        }
        else {
            newPos = '667px'
        }
        $(this).animate({
            marginLeft: newPos
        }, 480, function() {

        });

    });
    changeBackImage($('.topFeature ul li')[0]);

    $('.topFeature ul li').click(function() {
        changeBackImage(this);
    })
}


function changeBackImage(obj) {
    var fullsizeurl = $(obj).find('img').attr('fullsizeurl');
    fullsizeurl = 'url(..' + fullsizeurl + ')';
    $('.topFeature').css('background-image', fullsizeurl);
    var content = $(obj).find('.hidden').html()
    $('.topFeatureText').html(content)

}


function viewDetails(clicked) {
    openDialog($(clicked).parent().parent().find('.detailsHidden'))
}



function gotoRegion(element) {
    var panel = $(element).parent().parent().parent()
    panel.hide()
    var wrapper = panel.parent().find('.outer')
    var target = panel.parent().find("h2:contains('" + $(element).html() + "')")
    $(wrapper).find("ul").hide()
    $(wrapper).find("h2").hide()
    $(target).show()
    $(target).next().show()

    $(wrapper).find('.inner').css("margin-top", "0")
    $('.discoverWisconsin').find('.sliderHandle').css("top", "10px")
    if ($(wrapper).find('.inner').height() < 750) {
        $('.discoverWisconsin').find('.sliderTrack').addClass('hide')
    }
    else {
        $('.discoverWisconsin').find('.sliderTrack').removeClass('hide')
    }

}

function initPlayerSwitch() {
    //large 
    $('a.selectTV').click(function() {
        $('.selectRadio').removeClass('active');
        $('.selectTV').addClass('active');
        $('.largePlayerWrapper').find('.videoPlayer').show();
        $('.largePlayerWrapper').find('.audioPlayer').hide()
        $('.largePlayerWrapper').find('.radioGuide').hide()
        $('.largePlayerWrapper').find('.tvGuide').show()
    })
    $('a.selectRadio').click(function() {
        $('.selectRadio').addClass('active');
        $('.selectTV').removeClass('active');
        $('.largePlayerWrapper').find('.videoPlayer').hide();
        $('.largePlayerWrapper').find('.audioPlayer').show()
        $('.largePlayerWrapper').find('.tvGuide').hide()
        $('.largePlayerWrapper').find('.radioGuide').show()
        $('.radioGuide .listingWrapper .tabMenu').find('a').eq(0).click()

        //$('.radioGuide .sliderTrack ').css('margin-top','0')
    })

    //home page	
    $('a.btnTv').click(function() {
        var wrapper = $(this).parent().parent().parent().parent()
        $('a.btnRadio').removeClass('active')
        $('a.btnTv').addClass('active')
        wrapper.find('.panel_tv').show()
        wrapper.find('.panel_tv ul').css('margin-top', '0')
        wrapper.find('.panel_tv').addClass('active')
        wrapper.find('.panel_radio').hide()
        wrapper.find('.panel_radio').removeClass('active')
        wrapper.find('.sliderHandle').css("top", "0px")

    })
    $('a.btnRadio').click(function() {
        var wrapper = $(this).parent().parent().parent().parent()
        $('a.btnRadio').addClass('active')
        $('a.btnTv').removeClass('active')
        wrapper.find('.panel_radio ul').css('margin-top', '0')
        wrapper.find('.panel_tv').hide()
        wrapper.find('.panel_tv').removeClass('active')
        wrapper.find('.panel_radio').show()
        wrapper.find('.panel_radio').addClass('active')
        wrapper.find('.sliderHandle').css("top", "0px")
    })
    //in this episode / air schedules
    $('.showGuide .tabMenu ul li').eq(0).find('a').click(function() {
        $('.showGuide .selector').hide()
    })
    $('.showGuide .tabMenu ul li').eq(1).find('a').click(function() {
        $('.showGuide .selector').show()
    })
}

function initScrollbars() {
    // hook up handler for all scroll bars
    var scrollHandle
    $("#root .sliderHandle").each(function() {
        var parentHeight = $(this).parent().height()
        if (parentHeight == 0) {
            parentHeight = 350
        }
        $(this).wrap('<div style="padding-top:10px;padding-bottom:10x;position:relative;height:' + (parentHeight - 20) + 'px">')


        // does the scrollbar need to be shown?
        //find active panel
        if (4 == 4) {
            var wrapper = $(this).parent().parent().parent()
            var activePanel = findActive(wrapper, '.tabPanel')
            var panel = $(wrapper).find('.tabPanel').eq(activePanel)
            var panelNav = panel.find('.panelNav')
            var scrollPanel = panel.find('ul')
            if (!scrollPanel.length || panelNav.length) {
                scrollPanel = panel.find('.contentPanel')
            }
            var contentHeight = $(scrollPanel).outerHeight(true) + 20
            //panel.css('background-color', '#ff0000')
            //scrollPanel.css('background-color', '#0000ff')
            //alert(contentHeight + ", " + $(panel).outerHeight(true))

            if (4 == 5 && parseInt(contentHeight) < parseInt($(panel).outerHeight())) {
                $(this).parent().parent().addClass('fade')
            }
            else {
                $(this).draggable({ axis: 'y', containment: 'parent', drag: function(event, ui) { setScroll(this) } });
            }
        }


    })



}

function setScroll(scrollHandle) {
    //this moves the associated panel with the scroll action
    scrollHandle = $(scrollHandle)
    var myTop = parseInt(scrollHandle.css('top').replace('px', '')) - 10

    var trackHeight = scrollHandle.parent().height()


    var sliderPos = myTop / trackHeight //* 1.2
    var wrapper = scrollHandle.parent().parent().parent()

    var panel = $(wrapper).find('.tabPanel.active')

    var panelNav = panel.find('.panelNav')

    //var scrollPanel = panel.find('ul').eq(0)
    var scrollPanel = $(wrapper).find('.tabPanel.active ul')


    //find the scroll taget
    if (scrollPanel.length > 1) {
        scrollPanel = $(wrapper).find('.tabPanel.active div.inner')

        if (scrollPanel.length == 0) {
            scrollPanel = $(wrapper).find('.listPanel.active ul').eq(0)
        }
    }
    if (scrollPanel.length == 0) {
        scrollPanel = $(wrapper).find('.tabPanel.active').find('div.active ul').eq(0)
    }
    if (scrollPanel.length == 0) {
        scrollPanel = $(wrapper).find('.tabPanel.active').find('div.active ul').eq(0)
    }

    if (!scrollPanel.length || panelNav.length) {
        scrollPanel = panel.find('.contentPanel')
    }
    //wrapper.css('border','1px solid #ff0000')
    var contentHeight = $(scrollPanel).height()
    newTop = parseInt((sliderPos * (trackHeight - contentHeight)) * 1.3)
    //$('.controlDial').html("pl: "+panel.length+"<br />"+trackHeight+"<br />"+contentHeight)
    if (myTop < 11) {
        newTop = 0
    }
    if (newTop > 1) {
        scrollHandle.css("top", "0px")
        return
    }

    $(scrollPanel).css("margin-top", newTop + 'px')

}



function initPanelList() {
    $('.panelNav .scrollLeft').click(function() { panelScroll(this, -1) })
    $('.panelNav .scrollRight').click(function() { panelScroll(this, 1) })
    
}

function panelScroll(btn, dir) {
    //horizontal scroller for calendar list
    var wrapper = $(btn).parent().parent()

    //$(wrapper).css('border','1px solid #ff0000')
    panelLength = $(wrapper).find('.listPanel').length
    var datePanel = $(wrapper).find('.dateBox')

    if (panelLength) {
        var activePos = findActive(wrapper, '.listPanel')
        var activePanel = $(wrapper).find('.listPanel').eq(activePos)
        activePanel.removeClass('active')
        activePanel.hide()
        if (dir == 1) {
            if (activePos == panelLength - 1) {
                activePos = -1
            }
            var targetPanel = $(wrapper).find('.listPanel').eq(activePos + 1)
            targetPanel.addClass('active')
            targetPanel.show()
        }
        else {
            if (activePos == 0) {
                activePos = panelLength
            }
            var targetPanel = $(wrapper).find('.listPanel').eq(activePos - 1)
            targetPanel.addClass('active')
            targetPanel.show()
        }
        wrapper.parent().parent().find('.tabMenu a.active').click()
        //update date panel
        $(wrapper).find('.dateBox').html(targetPanel.find('.hiddenDate').html())

        //find vertical scroll and reset position of scroller
        if ($(wrapper).find('.sliderTrack').length) {
            $(wrapper).find('.tabPanel').children().css("margin-top", "0")
            $(wrapper).find('.sliderHandle').css("top", "0px")
        }

    }

}

function findActive(wrapper, className) {
    //find the position of the active item in the list
    panelLength = $(wrapper).find(className).length
    for (var x = 0; x < panelLength; x++) {
        if ($(wrapper).find(className).eq(x).hasClass('active')) {
            return x
        }
    }
    return -1
}


function initTabPanels() {
    $('.tabMenu ul li a').click(function() {
        swapTab(this)
    })
}

function setRadioScroll() {
    wrapper = $('.radioGuide')
    window.setTimeout(function() { swapTab(wrapper.find('a.active')) }, 500)
    window.setTimeout(function() { swapTab(wrapper.find('a.active')) }, 1000)
}

function swapTab(btn) {
    //change the tab state and associated panel visibility

    var panel = $(btn).parent().parent()
    var wrapper = $(btn).parent().parent().parent().parent()
    var panelLength = $(panel).find('li a').length
    var panelPos = 0
    var scrollPanel
    var panelWidth
    var panelItems
    var targetPanel
    $(panel).find('li a').removeClass('active')
    $(btn).addClass('active')


    if ($(wrapper).find('.tabPanel').length) {
        $(wrapper).find('.tabPanel').hide()
        $(wrapper).find('.tabPanel').removeClass('active')
        for (var x = 0; x < panelLength; x++) {
            if ($(panel).find('li').eq(x).children().hasClass('active')) {
                targetPanel = $(wrapper).find('.tabPanel').eq(x)
                targetPanel.show()
                targetPanel.addClass('active')
                //fix widths of horizontal scroller

                if (targetPanel.find('ul').length && targetPanel.hasClass('scrollPanel')) {
                    //adjust panel width
                    panelWidth = $(targetPanel).find('ul li').eq(0).outerWidth(true)
                    if (panelWidth < 140) {
                        panelWidth = 140
                    }
                    panelItems = $(targetPanel).find('li').length + 1
                    targetPanel.find('ul').css('width', panelWidth * panelItems + 'px')
                }
            }
        }
    }

    //find vertical scroll and reset position of scroller

    if ($(wrapper).find('.sliderTrack').length) {
        $(wrapper).find('.tabPanel').children('ul').eq(0).css("margin-top", "0")
        $(wrapper).find('.sliderHandle').css("top", "10px")

        //determine if scrollbar is needed
        var scrollTarget = $(wrapper).find('.tabPanel.active').children('ul').eq(0)
        //scrollTarget.css('border', '1px solid #ff0000')
        if (scrollTarget.length == 0) {
            scrollTarget = $(wrapper).find('.tabPanel.active').children().children('ul').eq(0)
        }
        if (scrollTarget.length == 0) {
            scrollTarget = $(wrapper).find('.tabPanel.active').children().eq(0)
        }
        var scrollWrapper = $(wrapper).find('.tabPanel.active')

        if (isNaN(scrollTarget.height()) || scrollTarget.height() <= scrollWrapper.height()) {

            $(wrapper).find('.sliderTrack').addClass('hide')
        }
        else {
            $(wrapper).find('.sliderTrack').removeClass('hide')
        }


    }

    //find horizontal scroll and reset buttons and position

    if ($(wrapper).find('.scrollPanel').length) {
        $(wrapper).find('.scrollPanel ul').css('margin-left', '0')
        setScrollButtons(wrapper, 1)
    }
    //truncate items if this is the bottom nav
    if ($(wrapper).find('.noFormat').length) {
        truncateItems(targetPanel, 31)
    }


}



function initScrollPanels() {
    //initialize horizontal scroll panels

    var paneWidth
    var panelItems
    var panel
    var pAdjust
    $('.scrollPanel').each(function() {
        //duplicate the first n panels and put at the end
        pAdjust = 0
        var wrapper = $(this).parent()


        var wrapperClass = wrapper.attr('class')
        if (wrapperClass.indexOf('showing_') < 0) {
            return
        }
        var showing = wrapperClass.split('showing_')
        var panelShowing = showing[1]
        setScrollButtons(wrapper, panelShowing)
        panelWidth = $(this).find('ul li').eq(0).outerWidth(true)
        if (panelWidth < 140) {
            panelWidth = 140
            pAdjust = 1
        }
        
        panelItems = $(this).find('li').length + pAdjust
        $(this).find('ul').css('width', panelWidth * panelItems + 'px')
        var clickLeft = wrapper.find('.scrollNav .scrollLeft')
        var clickRight = wrapper.find('.scrollNav .scrollRight')
        wrapper.find('.scrollLeft').click(function() { slideScroll(clickLeft, 1) })
        wrapper.find('.scrollRight').click(function() { slideScroll(clickRight, -1) })
        clickLeft.addClass('hide')
       
    })
}

function setScrollButtons(wrapper, showing) {
    //set button visibility for active panel
    //wrapper.css('border','1px solid #ff0000')
    var myClass = $(wrapper).attr('class')
    var cPos = myClass.indexOf('showing_')
    if (cPos > -1) {
        showing = parseInt(myClass.substring(cPos + 8, cPos + 9))
        if (showing > 4) {
            showing = 4
        }
    }
    if (showing == 1) {
        showing = 4
    }

    if ($(wrapper).find('.scrollPanel.active ul li').length <= showing) {
        
        
        wrapper.find('.scrollRight').addClass('hide')
    }
    else {
        wrapper.find('.scrollRight').removeClass('hide')
        wrapper.find('.scrollRight').show()
    }
    //wrapper.find('.scrollLeft').addClass('hide');

    var leftArrowCSS = $(wrapper).parent().find('.scrollLeft').hasClass('hide');
    var rightArrowCSS = $(wrapper).parent().find('.scrollRight').hasClass('hide');
    $(wrapper).parent().find('label').removeClass('hide');
    if (leftArrowCSS && rightArrowCSS) {
        $('#navBtn').hide();
        $(wrapper).parent().find('label').addClass('hide');
    }

}

function slideScroll(ele, dir) {
    // slide the video list
    if (sliding) {
        return;
    }

    sliding = 1
    var moveTime = 480
    var curPos
    var wrapper = $(ele).parent().parent()
    $(wrapper).parent().find('.scrollLeft').removeClass('hide')
    $(wrapper).parent().find('.scrollRight').removeClass('hide')
    var wrapperClass = wrapper.attr('class').replace('active', '')

    if (wrapperClass.indexOf('showing_') < 0) {
        return
    }
    var showing = wrapperClass.split('showing_')
    var panelShowing = showing[1]
    var target = wrapper.find('.scrollPanel').eq(findActive(wrapper, '.scrollPanel')).find('ul')
    var panelWidth = target.outerWidth(true)
    //alert(target.width() + " " + target.outerWidth(true) + " " + target.parent().width())
    //fix for webkit
    if (target.outerWidth(true) == target.parent().width()) {
        panelWidth = target.width() - target.parent().width()
    }

    //target.css('border', '1px solid #ff0000')

    var panelCount = $(ele).find('li').length
    var moveWidth = dir * panelShowing * $(target).find('li:first').outerWidth(true)

    var movePos = curPos / moveWidth
    var maxMove = parseInt(panelCount / panelShowing)


    //move one group

    $(target).animate({
        marginLeft: '+=' + moveWidth
    }, 480, function() {
        sliding = 0
        curPos = parseInt($(target).css('margin-left').replace('px', ''))
        //alert((curPos + moveWidth) + ", " + panelWidth)
        if (Math.abs(curPos + moveWidth) > panelWidth && dir == -1) {
            $(wrapper).parent().find('.scrollRight').addClass('hide')
            $(wrapper).parent().find('.scrollLeft').removeClass('hide')
        }
        if (curPos == 0) {
            $(wrapper).parent().find('.scrollRight').removeClass('hide')
            $(wrapper).parent().find('.scrollLeft').addClass('hide')
        }
    });


    return false

}



function initChooseRegion() {
    $('.chooseRegion').next('.dd').find('ul li a').click(function() {
        gotoRegion(this)
    })
}

function initChooseCounty() {
    $('.chooseCounty').next('.dd').find('ul li a').click(function() {
        gotoRegion(this)
    })
}



// mouse drop-down panel handler
function initDD(element) {
    var target = $(element).parent().next('.dd')
    if (target.length == 0) {
        target = $(element).next('.dd')
    }
    $(element).click(function() {
		$('div.dd').hide()
		target.parent().css('z-index', '5000')
        if(target.hasClass('open')) {
        	target.removeClass('open')
        	target.parent().css('z-index', '1000')
			target.hide()
        }
        else {
			target.addClass('open')
			target.show()
        }
    })

	$(target).mouseout(function() {
		$(this).removeClass('open')
		$(this).parent().css('z-index', '1500')
		$(this).hide()
		//window.setTimeout(function() { closeDD(target) }, 600)
	})

	$(target).mouseover(function() {
		$(this).addClass('open')
		$(this).parent().css('z-index', '5000')
		$(this).show()
		//window.setTimeout(function() { closeDD(target) }, 600)
	})
   
//    $(element).mouseout(function() {

//        window.setTimeout(function() { closeDD(target) }, 600)
//    })
//    target.mouseout(function() {
//		target.removeClass('open')		
//        window.setTimeout(function() { closeDD(target) }, 600)
//    })
//    setCloseDD(target)

    //set clear button
    $('.btnClear').click(function() {
        clearDate(this)
    })

}

function clearDate(element) {
    $(element).parent().find('.dateSelect').each(function() {
        $(this).find('input').attr('value', '0')
        var myName = $(this).find('input').attr('name')

        if (myName == 'startMonth' || myName == 'endMonth') {
            $(this).find('.mnuDate').html("Month")
        }
        if (myName == 'startDay' || myName == 'endDay') {
            $(this).find('.mnuDay').html("Day")
        }
        if (myName == 'startYear' || myName == 'endYear') {
            $(this).find('.mnuYear').html("Year")
        }
        if (myName == 'startTime' || myName == 'endTime') {
            $(this).find('.mnuDate').html("Time")
        }
        if (myName == 'startAMPM' || myName == 'endAMPM') {
            $(this).find('.mnuDate').html("AM / PM")
        }


    })


}

function closeDD(element) {
    if ($(element).hasClass('open')) {
        return
    }

    $(element).hide()

    if ($(element).parent()) {
        //$(element).parent().css('z-index', 'inherit')
        //removed because of IE bug
    }

}

function setCloseDD(element) {
    $(element).find('ul').mouseover(function() {
        $(this).parent().addClass('open')
    })
    $(element).find('ul').mouseout(function() {
        $(this).parent().removeClass('open')
    })
    $(element).find('ul li a').mouseover(function() {
        $(this).parent('dd').addClass('open')
    })
    $(element).find('ul li a').mouseout(function() {
        $(this).parent('dd').removeClass('open')
    })
}

function expandPoll(element) {
    $(element).next('.results').toggle()
}

function onAir(running) {
    if ($('.featuredEpisodeWrapper').length) {
        if (running == 'true') {
            $('.featuredEpisodeWrapper').css('background-image', 'url("../Images/BGFeaturedEpisodeExpandedActive.jpg")')
        }
        else {
            $('.featuredEpisodeWrapper').css('background-image', 'url("../Images/BGFeaturedEpisodeExpanded.jpg")')
        }
    }
    if ($('.largePlayerWrapper').length) {
        if (running == 'true') {
            $('.largePlayerWrapper').css('background-image', 'url("../Images/BGVideoConsoleLargeActive.jpg")')
        }
        else {
            $('.largePlayerWrapper').css('background-image', 'url("../Images/BGVideoConsoleLarge.jpg")')
        }
    }
}

jQuery(document).ready(function() {
    jQuery('.calendarList .panelNav a').each(function() {
        jQuery(this).removeClass('hide');
    });
});

jQuery('.scrollLeft').click(function() {
    jQuery('.calendarList .panelNav a').removeClass('hide');
});
