var $j = jQuery.noConflict();

$j(document).ready(function()
{
    // Init Function
    function initjQuery()
    {
        var isEditMode = false;
        
        if ($j('#nlcEditMode').length > 0)
        {
            isEditMode = true;
        }
    
    
    
    
    
    
    
    //  ==========================================
    //  Setup all input text box to clear on focus
        /*$j('input[type="text"]').each(function()
        {
            $j(this).CreateAutoSelect();
        });*/
     // Search box behaviour.
        $j('#search #q').each(function() {
            var default_value = $j(this).attr('value');
            var search_box = $j(this);
            // some pages need jQuery 1.3 which doesn't have focusin()/focusout()
            if (typeof search_box.focusin=="function") {
                search_box.focusin(function() {
                    if (search_box.attr('value')==default_value) {
                        search_box.attr('value','');
                    }
                });
                search_box.focusout(function() {
                    if (search_box.attr('value')=="") search_box.attr('value',default_value);
                });
            } else {
                search_box.click(function() {
                    if (search_box.attr('value')==default_value) {
                        search_box.attr('value','');
                    }
                });
            }

            $j('#search').submit(function() {
                if (search_box.attr('value')==default_value || search_box.attr('value')=="") {
                    alert("Please enter search criteria.");
                    return false;
                }
                return true;
            });
        });
        
    //  ============================
    //  Setup the homepage Accordion
    // /*
        $j('.home-accordion').each(function()
        {
            $j(this).CreateAccordion();
        });
    // */
    
        $j('.home-accordion ul.hide a').click(function() {
          window.location = $j(this).attr('href');
        });
    
    
        //$j('.home-accordion .block-nav').accordion();
    
        /*
        var prevChild = null;
    
        $j('.home-accordion .parent').click(function() {
                                                     
            if (prevChild)
            {
                prevChild.toggle('slow');
            }
                                                     
            $j(this).children('ul:first').toggle('slow');
            
            prevChild = $j(this).children('ul:first');
            return false;
        });
    // */
        
        //Cufon.replace('h2.customFont', {fontFamily: 'tradeGothic', fontSize: '35px', letterSpacing: '.8px'});
        //Cufon.replace('h3.customFont', {fontFamily: 'tradeGothicBold', fontSize: '20px', letterSpacing: '.8px'});
        
        
    //  --------------------
    //  Horizontal Scrollers
    
        // Homepage Banner Slide Show
        if ($j('.home-slider').length > 0)
        {
            $j('.home-slider').each(function()
            {   
                if (!isEditMode)
                {
                    var sliderTimer = 0;
                
                    if ($j(this).attr('id'))
                    {
                        var timer = $j(this).attr('id').split("-");
                        sliderTimer = parseInt(timer[timer.length - 1]);
                    }
                    
                    $j(this).find('.slideItem').addClass('hide');
                    var n = Math.floor( Math.random() * $j(this).find('.slideItem').length );
                    $j(this).find('.slideItem:eq('+n+')').removeClass('hide');
                    
                    $j(this).CreateSlider({ 
                                              animationType: 'customFade', 
                                              animationTime: 750, 
                                              autoSlideDelay: (sliderTimer != 0) ? sliderTimer : 8000, 
                                              controlType: null,
                                              isAutoSlide: false
                                         });
                }
                else
                {
                    $j(this).css({ position: 'relative', height: 'auto' })
                    $j('.slideItem', this).each(function()
                    {
                        $j(this).css({ position: 'relative' }).removeClass('hide');
                    });
                }
            });
            //$j('.home-feature .slider-holder').show();
        }
        
        // Homepage What Inspires You Slider
        if ($j('.home-feature-slider').length > 0)
        {
            $j('.home-feature-slider').each(function()
            {   
                $j('.slideItem', this).each(function()
                {
                    $j(this).css({ position: (isEditMode) ? 'relative' : 'absolute' });
                });
                
                if (!isEditMode)
                {
                    $j(this).CreateSlider({ 
                                              animationType: 'customSlide',
                                              animationTime: 750, 
                                              disableOnLast: false
                                         });
                }
                else
                {
                    $j('.home-feature-holder').css({ position: 'relative' });
                    $j('.home-feature-wrapper').css({ position: 'relative', height: 'auto', padding: '20px 0' });
                    $j('.home-feature').css({ bottom: 'auto', top: 0 })
                    $j('.banner-home').css({ height: 'auto' });
                    $j('.home-accordion').css({ top: 0 });
                }
            });
        }
        
        // Slider on main landing pages
        if ($j('.slider01').length > 0)
        {
            $j('.slider01').each(function()
            {   
                
                if (!isEditMode)
                {
                    $j('.slideItem', this).each(function()
                    {
                        $j(this).css({ position: 'absolute' });
                    });
                    
                    var sliderTimer = 0;
                
                    if ($j(this).attr('id'))
                    {
                        var timer = $j(this).attr('id').split("-");
                        sliderTimer = parseInt(timer[timer.length - 1]);
                    }
                
                    $j(this).CreateSlider({ 
                                              animationType: 'customSlide',
                                              animationTime: 750, 
                                              disableOnLast: false,
                                              autoSlideDelay: (sliderTimer != 0) ? sliderTimer : 8000,
                                              isAutoSlide: true
                                         });
                }
                else
                {
                    $j(this).css({ position: 'relative', height: 'auto' })
                    $j('.slideItem', this).each(function()
                    {
                        $j(this).css({ position: 'relative' }).removeClass('hide');
                    });
                }
            });
        }
        
        // Subsite Landing Page Sliders (Athletics too!)
        if ($j('.slider02').length > 0)
        {
            $j('.slider02').each(function()
            {   
                if (!isEditMode)
                {
                    $j('.slideItem', this).each(function()
                    {
                        $j(this).css({ position: 'absolute' });
                    });
                    
                    // With Thumbnails
                    if ($j(this).attr('class').indexOf('Thumb') > 0)
                    {
                        $j(this).CreateSlider(
                        { 
                            controlType: 4,
                            dynamicCategoriesTag: 'h2',
                            animationType: 'customSlide',
                            animationTime: 750, 
                            disableOnLast: true,
                            autoHideControls: false,
                            autoSlideDelay: 8000, 
                            isAutoSlide: true 
                        });
                    }
                    // Without Thumbnails
                    else
                    {
                        $j(this).CreateSlider(
                        { 
                            animationType: 'customSlide',
                            dynamicCategoriesTag: 'h2',
                            animationTime: 750, 
                            disableOnLast: false,
                            autoSlideDelay: 8000,
                            isAutoSlide: true,
                            autoHideControls: true
                        });
                    }
                
                }
                else
                {
                    $j(this).css({ position: 'relative', height: 'auto' })
                    $j('.slideItem', this).each(function()
                    {
                        $j(this).css({ position: 'relative' }).removeClass('hide');
                    });
                }
                
            });
        }
        
        // Event Details - More Event Slider
        if ($j('.slider03').length > 0)
        {
            $j('.slider03').each(function()
            {   
                var h = 0;
            
                $j('.slideItem', this)
                    .each(function()
                    {
                        var img = $j('.slideImg img', this);
                        h = (img.outerHeight(true) > h) ? img.outerHeight(true) : h;
                        img.css({ position: 'absolute' });
                        
                        $j(this).css({ position: 'absolute' });
                        
                    })
                    .each(function()
                    {
                        $j('.slideImg', this).css({ height: h + 'px' });
                    });
                
                $j(this).CreateSlider({ 
                                          animationTime: 750, 
                                          disableOnLast: true
                                     });
            });
        }
        
         // Subsite Landing Page Sliders (Athletics too!)
        if ($j('.slider04').length > 0)
        {
            $j('.slider04').each(function()
            {   
                if (!isEditMode)
                {
                    $j('.slideItem', this).each(function()
                    {
                        $j(this).css({ position: 'absolute' });
                    });
                   
                    $j(this).CreateSlider(
                    { 
                        animationType: 'customSlide',
                        dynamicCategoriesTag: 'h2',
                        animationTime: 750, 
                        disableOnLast: false,
                        autoSlideDelay: 8000,
                        isAutoSlide: true,
                        autoHideControls: false
                    });
                
                }
                else
                {
                    $j(this).css({ position: 'relative', height: 'auto' })
                    $j('.slideItem', this).each(function()
                    {
                        $j(this).css({ position: 'relative' }).removeClass('hide');
                    });
                }
                
            });
        }
        
        
        
    //  -----------------------------------------------------------------
    //  Add the image alt text as a caption overlaid on the image
    //  Every image can use this by adding a class of "photoGalleryImage"
        if ($j('.photoGalleryImage').length > 0)
        {
            $j('.photoGalleryImage').each(function()
            {
                var imgTitle = $j(this).attr('alt'),
                    imgHref  = $j(this).parent('a').attr('href'),
                    imgWidth = $j(this).width(),
                    ctns     = $j(this).parent('a').contents();
                  
                $j(this).parent('a').replaceWith(ctns);
                $j(this).before('<div class="photoGallery" style="width: ' + imgWidth + 'px"><div class="photoGalleryTitle"><a href="' + imgHref + '">' + imgTitle + '</a></div><div class="photoGalleryBG"></div></div>');
            });
        }
        
    //  ----------------------------------------------------
    //  Position the Subsite Search Box if there is an image
        if ($j('img', '.subsite-header').length > 0)
        {
            var imgHeight = $j('img', '.subsite-header').height();
            
            if ($j('.hdr-search', '.subsite-header').length > 0)
            {   
                $j('.hdr-search', '.subsite-header').css({ 'margin-top': Math.round((imgHeight / 2)) + 'px' })
            }
        }
        
    //  --------------------
    //  Create custom select
        $j('select').uniform();
        
        

        
    //  --------------------
    //  Create the Alert Box
        /* Done inline now, due to the AJAXy nature of the emergency alert system
        if ($j('#alert').length > 0)
        {
            var h = 200; //$j('#alert').height();
                        
            $j('#alert').css({ 'margin-top': -h + 'px', display: 'block' }).animate({ 'margin-top': 0 });
            
            $j('a.btn-alertClose', '#alert').click(function()
            {
                $j('#alert').animate({ 'margin-top': -h + 'px' });
                return false;
            });
        }
    //  */
    
        
    //  -------------------
    //  Filter Program List
        if ($j('#filter-programs').length > 0)
        {
            var keymatch = '';
            
            $j('#filter-programs').val('');
            
            $j('#filter-programs').keyup(function(event)
            {
                
                var keymatch = $j('#filter-programs').val();
                
                var i = 0;
                var len_i = $j('.dl-programsList > dt').length;
                
                for (i; i < len_i; i++)
                {
                    var program = $j('.dl-programsList > dt:eq(' + i + ')');
                    var keywords = $j('.dl-programsList > dd:eq(' + i + ')');
                    
                    var str = program.text().toLowerCase();
                    var k_str = keywords.text().toLowerCase();
                    
                    if (str.indexOf(keymatch) >= 0 || k_str.indexOf(keymatch) >= 0)
                    {
                        //$j(program).highlight(keymatch);
                        
                        $j(program).removeClass('hide').addClass('show');
                        $j(keywords).removeClass('hide').addClass('show');
                    }
                    else
                    {
                        $j(program).removeClass('show').addClass('hide');
                        $j(keywords).removeClass('show').addClass('hide');
                    }
                    
                    if (keymatch == "")
                    {
                        $j(program).removeClass('hide').addClass('show');
                        $j(keywords).removeClass('hide').addClass('show');
                    }
                }
            });
        }
        
        
        
        
        // ------------ 
        // AutoSearcher
        
        if ($j('#autosearch').length > 0) {
            var temp = function(event) {
                var keymatch = $j('#autosearch').val().toLowerCase();
                if (keymatch == autosearchDefaultText.toLowerCase()) keymatch = '';
                var filter = $j('#autosearchfilter').length > 0 ? $j('#autosearchfilter').val().toLowerCase() : "";
                
                var i = 0;
                var len_i = $j('.autosearchlist > li').length;
                $j('.autosearchnotfound').each(function(i){ $j(this).removeClass('hide').addClass('show'); });
                
                for (i; i < len_i; i++) {
                    var program = $j('.autosearchlist > li:eq(' + i + ')');
                    
                    var parts = program.text().toLowerCase().split("|||||");
                    var str = parts[0];
                    var ftr = parts.length > 1 ? parts[1] : "";
                    
                    if (!$j(program).hasClass('autosearchnotfound')) {
                        if ( (keymatch=="" || str.indexOf(keymatch) >= 0) && (filter=="" || ftr.indexOf(filter) >= 0) ) {
                            $j(program).removeClass('hide').addClass('show');
                            $j(program).parent().children().last().removeClass('show').addClass('hide');
                        } else {
                            $j(program).removeClass('show').addClass('hide');
                        }
                    }
                }
            };
            
            $j('#autosearch').keyup(temp);
            $j('#autosearchfilter').change(temp);
        }
        
        
        
        
        
        $j('.table-sets').each(function()
        {
            var parent = $j(this);
            
            var toggleItem = $j('.js-toggle', parent);
            
            toggleItem
                .addClass('js-close')
                .mouseover(function()
                {
                    toggleItem.addClass('hover');//.css({ cursor: 'pointer', 'background-color': '#363636' });
                })
                .mouseout(function()
                {
                    toggleItem.removeClass('hover');//.css({ 'background-color': '#000000' })
                })
                .click(function()
                {
                    $j('.toggle-content', parent).toggle();
                    
                    if (toggleItem.attr('class').indexOf('js-close') > 0)
                    {
                        toggleItem.removeClass('js-close').addClass('js-open');
                    }
                    else
                    {
                        toggleItem.removeClass('js-open').addClass('js-close');
                    }
                    
                    return false;
                });
        });
        
        
        
        
        
        lastBlock = $j("#accordionFirstOpen");
        $j('a', lastBlock).html($j('a', lastBlock).attr('title'));
        maxWidth = 478;
        minWidth = 194; 
    
        $j(".accordionBanner div").each(function(num)
        {
            $j(this).mouseenter(function()
            {
                if ($j(this).width() != maxWidth)
                {
                    $j(lastBlock).animate({ width: minWidth + "px" }, { queue: false, duration: 400 });
                    $j('dt', lastBlock).css({ opacity: 1 }).animate({ opacity: 0 }, { queue: false, duration: 200 });
                    $j('a', lastBlock).html('More');
                    
                    $j(this).animate({ width: maxWidth + "px" }, { queue: false, duration: 400 });
                    $j('dt', this).css({ opacity: 0, display: 'block' }).animate({ opacity: 1 }, { queue: false, duration: 200 });
                    $j('a', this).html($j('a', this).attr('title'));
                    lastBlock = $j(this);
                }
            });
        });


        $j('#DD-rotating').removeClass('hide').innerfade({ 
                                        animationtype: 'fade', 
                                        speed: 'normal', 
                                        timeout: '5000', 
                                        type: 'sequence', 
                                        containerheight: 'auto',
                                        runningclass: 'innerfade' 
                                    }); 

        $j('.gen-dd').click(function() {

            $j('#informationFor').toggle();
        });




    //  =======================
    //  Setup Scoreboard Widget
        
        // Global Variable to be inserted inline
        // var widgetScoreboardURL = ''; // This is being set in the Dal Tigers Page Component (right.jsp)
        
        if ($j('.widget-scoreboard').length > 0)
        {
            $j('.widget-scoreboard').CreateScoreboard({ 
                url: widgetScoreboardURL,
                noGamesError: noGames,
                noMeetsError: noMeets 
            });
            
        }



        
        
        
    //  ==============
    //  Setup Calendar
        if ($j('#datepicker').length > 0) 
        {
            // Months array used to populate the dateString field
            var monthsName = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    
            var href    = location.href,
                newHref = '',
                dateNum = 0,
                dateStr = '',
                dateRef = 'd=',
    
                dateParam   = (href.indexOf(dateRef) < 0) ? null : href.substr(href.indexOf(dateRef), 12),
                selectedDate = null,
                selectedDateArr = null,
                selectedYear,
                selectedMonth,
                defaultDateStr = null;
            
            if (dateParam != null)
            {
                selectedDate = dateParam.replace(dateRef, '');
                selectedDateArr = selectedDate.split("_");
                
                selectedYear = selectedDateArr[2];
                selectedMonth = selectedDateArr[0];
                
                var currentDate = new Date(),
                    currentMonth = currentDate.getMonth() + 1,
                    currentYear = currentDate.getFullYear(),
                    yearDiff = parseInt(selectedYear, 10) - parseInt(currentYear, 10),
                    monthDiff = parseInt(selectedMonth, 10) - parseInt(currentMonth, 10),
                
                    defaultYear = (yearDiff > 0) ? '+' + yearDiff + 'y' : yearDiff + 'y',
                    defaultMonth = (monthDiff > 0) ? '+' + monthDiff + 'm' : monthDiff + 'm';
                
                defaultDateStr = defaultYear + ' ' + defaultMonth;
            }
            
            
            $j('#datepicker').datepicker(
            {
                dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
                defaultDate: defaultDateStr,
                
                /*
                changeYear: true,
                changeMonth: true,
                */
                
                // Function to handle the month or year change
                onChangeMonthYear: function(year, month, inst)
                    {
                       //alert(month);
                    
                    
                       $j('.month-dd option').parent().prev().text(monthsName[month - 1]);
                       $j('.year-dd option').parent().prev().text(year);
                       
                       
                       $j('.month-dd option').each(function(num)
                       {
                           if (num == (month-1))
                           {
                               $j(this).attr('selected', 'selected');
                           }
                       });
                       
                    
                        //alert(year + ":" + month);
                        
                        //alert('here');
                        
                        //$j('select', this).uniform();
                        //alert('here');
                        // Set the dateString field based on the new selection
                        //$j('#dateString').html(monthsName[month - 1] + ' ' + year);
                    },
                    
                onSelect: function(dateText, inst) 
                    {
                        var newDate = dateText.replace(/\//g,"_"); // Change current format MM/DD/YYYY => MM_DD_YYYY
                    
                        if (href.indexOf('?') < 0)
                        {
                            newHref = location.href + '?' + dateRef + '' + newDate;
                            newHref = newHref.replace(/#/, "");
                            window.location = newHref;
                        }
                        else if (href.indexOf(dateRef) < 0)
                        {
                            newHref = location.href + '&' + dateRef + '' + newDate;
                            newHref = newHref.replace(/#/, "");
                            window.location = newHref;
                        }
                        else
                        {
                            dateNum = href.indexOf(dateRef);
                            dateStr = href.substr(dateNum, 12);
                            newHref = href.replace(dateStr, dateRef + '' + newDate);
                            newHref = newHref.replace(/#/, "");
                            window.location = newHref;
                        }
                    }
            });
            
            $j('.month-dd').change(function()
            {
                 var month = parseInt($j('option:selected', this).val()) + 1;
                 var year  = $j('.year-dd option:selected').text();
                 
                 month = (month < 10) ? "0" + month : month.toString();
                 
                 $j('#datepicker').datepicker("setDate", month + "/01/" + year);
            });
            
            $j('.year-dd').change(function()
            {
                 var month = parseInt($j('.month-dd option:selected').val()) + 1;
                 var year  = $j('option:selected', this).text();
                 
                 month = (month < 10) ? "0" + month : month.toString();
                 
                 $j('#datepicker').datepicker("setDate", month + "/01/" + year);
            });
            
            //$j('select', '#datepicker').uniform();
        }
        
    //  ===========
    //  Create Tabs
        if ($j('.tabs-holder').length > 0)
        {
            $j('.tabs-holder').each(function()
            {               
                var id = $j(this).attr('id');
                $j(this).CreateTabs({ tabsID: id });
            });
        }

        
    //  ====================================================
    //  If IE6 setup the header "information for:" drop down
        if ($j.browser.msie && $j.browser.version == "6.0")
        {
            $j('.gen-dd > li').each(function(count)
            {
                $j(this).mouseover(function()
                {
                    $j(this).addClass('hover');
                }).mouseout(function()
                {
                    $j(this).removeClass('hover');
                });
            });
        }
    };
    

    
    initjQuery();
    if (typeof postLoad=="function") {
        postLoad();
    }
{

}
});

var tmrInformationFor;
function hideInformationFor() {
    $j('#informationFor').hide();
}

function setInformationForTimeout() {
    tmrInformationFor = setTimeout('hideInformationFor()',500); // .5 seconds.
}

function clearInformationForTimeout() {
    clearTimeout(tmrInformationFor);
}

// Load kampyle last
$j(window).load(function() {
    $j("#kampyle_button").show();
});

