// clears search's input onfocus
function clearText(thefield){
    if (thefield.defaultValue==thefield.value)
        thefield.value = ""
} 

// homepage callout panel switcher
function panelSwitch(currentPanel){
    $('.callouthome').addClass('hide');
    $('#panel'+currentPanel).removeClass('hide');
}

function printPage(){
    if (navigator.userAgent.indexOf("Safari") != -1 )
        alert("Safari does not support this feature, please choose print from the 'File' menu.");
    else
        window.print();
}

function refreshNav(){
    var secondaryNav = $('#navSide');
    if(secondaryNav.length > 0){
        var distanceToNav = $(secondaryNav).offset();
        var currentHeight = $(secondaryNav).height();
        var footerPosition = $('#footer').offset();
        var primaryColumn = $('#primary').height();
        if(primaryColumn <= currentHeight){
            // if the secondary nav is overlapping the footer
            $('#primary').height(currentHeight + 15);
        }
    }
}

/*----
jQuery Plugin: externalInterface: Version 1.0
Copyright (c) 2010 David Comeau (http://www.davecomeau.net), Licensed jointly under the GPL and MIT licenses.
----*/
(function($) {
    $.fn.externalInterface = function(args) {
        this.each(function() {
            if (typeof (args.method) != 'undefined') {
                try {
                    if (typeof (args.args) != 'undefined') {
                        var data = this[args.method](args.args);
                    } else {
                        var data = this[args.method]();
                    }

                    if (typeof (args.success) != 'undefined') {
                        args.success(data);
                    }
                } catch (error) {
                    if (typeof (args.error) != 'undefined') {
                        args.error(error);
                    }
                }
            }
        });
        return this;
    };
})(jQuery);


/**
    *  Function:		openWindow / popupWindow
    *
    *  Version History:	?
    *
    *  Description:	Use this function to open/popup a new window to display a link in.
    *
    *  Special Notes:	none
    *
    *  Syntax:		openWindow(url, w, h)
    *
    *  Parameters:		url: (input) target link
    *			w: (input) width of the popup window in pixels
    *			h: (input) height of the popup window in pixels
    *
    *  Returns:		void
*/

function openWindow(url, w, h) {
    var options  = "width=" + w + ",height=" + h + ",";
        options += "resizable=yes,scrollbars=yes,status=yes,";
        options += "menubar=yes,toolbar=yes,location=yes,directories=no";
    var newWin = window.open(url, 'newWin', options);
    newWin.focus();
}


/*---
    Homepage Banner
    ---*/
// customize delay between and length of fade of the brand title
var autoRotateDelay = 3000;
var fadeLength = 500;

var allTiles;
var allLinks;
var firstClick = true;
var previousItem = 0;
var currentItem = -1;
var mouseOverTiles = false;
var tilesChanging = false;

var tileTimer;

// swap tile on function
function changeTile() {

    // if the mouse is not over the tiles and the tiles are not currently changing
    if (!tilesChanging) {
    	if (!mouseOverTiles) {
            tilesChanging = true;
            $(allLinks).parent().removeClass('selected');
            //$(allTiles[currentItem]).css('z-index', 0); Causing the last div to show up.
            //$(allTiles[currentItem]).css('opacity', 1);
            previousItem = currentItem;
            currentItem++;

            if (currentItem >= allLinks.length) {
                currentItem = 0;
            }           
            
            $(allLinks[currentItem]).parent().addClass('selected');
            if(!firstClick)
            {
                var flashObject = $(allTiles[currentItem]).find('object, embed');
                if (flashObject.length > 0) {
                    $(flashObject).externalInterface({ method: 'restartMovie' });
                }              
            }           
            $(allTiles[currentItem]).css('z-index', 10).animate({ opacity: 1 }, fadeLength, function() {
                if(currentItem != -1)
                {
                     $('div.brandtile div.left').removeClass('initialLoad');
                }
                
                if(currentItem == 0)
                {
                    var flashObject = $(allTiles[currentItem]).find('object, embed');
                    if (flashObject.length > 0) {
                        $(flashObject).externalInterface({ method: 'restartMovie' });
                    }                   
                }                 

                if (!firstClick) {

                    $(allTiles[previousItem]).css('z-index', 0);
                    $(allTiles[previousItem]).animate({ opacity: 0 }, 0);
                }
                tilesChanging = false;
                firstClick = false;
            });
        }
    }
}

$(document).ready(function() {
    // store all brand tiles for use
    allTiles = $('div.contentRefresh div.brandtile div.left > div');
    allLinks = $('div.contentRefresh div.brandtile div.right ul li a');
    // if all brand tiles exist
    if (allTiles.length > 0) {
        //$('div.brandtile div.left').removeClass('initialLoad');
        $(allTiles).animate({ opacity: 1 }, 0);
        $(allLinks).click(function() {
            if (!tilesChanging) {
				if($(allLinks).index($(this)) != currentItem) {
					tilesChanging = true;
					if (currentItem == -1)
						currentItem = 1;
					$(allLinks).parent().removeClass('selected');
					$(this).parent().addClass('selected');
					previousItem = currentItem;
					currentItem = $(allLinks).index($(this));
					$(allTiles).css('z-index', 0);
					$(allTiles[previousItem]).css('z-index', 1);
					var flashObject = $(allTiles[currentItem]).find('object, embed');
					if (flashObject.length > 0) {
						$(flashObject).externalInterface({ method: 'restartMovie' });
					}
					$(allTiles[currentItem]).css('z-index', 2).animate({ opacity: 1 }, fadeLength, function() {
						if (!firstClick) {
							$(allTiles[previousItem]).animate({ opacity: 0 }, 0);
						}
						tilesChanging = false;
						firstClick = false;
					});
				}
            }
			return false;
        });
        // set interval for changing tile automatically
        tileTimer = setInterval("changeTile()", autoRotateDelay);
    }

    // on hover of the brand tiles disable tiles rotating
    $('div.contentRefresh div.brandtile').hover(function() {
        mouseOverTiles = true;
    }, function() {
        mouseOverTiles = false;
    });
});

/*---
    Homepage News Feed
    ---*/
// customize delay between and length of movement of the news ticker
var newsAutoRotateDelay = 8000;
var dateAnimationSpeed = 1000;

var newsDateWidth = 110;
var newsItemWidth = 270;
var allNewsDates;
var allNewsContent;
// easing equation
var dateEasingType = 'easeInOutQuad';

// How many images each click will change on click
var datePerClickShiftIncrement = 1;
// prevent double clicks
var sliderMoving = false;

var newsTimer;

function prevNewsItem() {
    if (!sliderMoving) {
        sliderMoving = true;
        // clone the last element and place it at the beginning
        $('div.newsBucket div.newsnav div.absolute').prepend($(allNewsDates[allNewsDates.length - 1]).clone());
        $('div.newsBucket div.news div.absolute').prepend($(allNewsContent[allNewsContent.length - 1]).clone());
        // rebuild thumbnail list
        allNewsDates = $('div.newsBucket div.newsnav p');
        allNewsContent = $('div.newsBucket div.news p');
        // slide the new cloned element to the left of the list of sliding elements absolutely by its width
        $(allNewsDates[0]).css('position', 'absolute').css('left', -newsDateWidth);
        $(allNewsContent[0]).css('position', 'absolute').css('left', -newsItemWidth);

        // animate the slider right
        $('div.newsBucket div.newsnav div.absolute').animate({ left: newsDateWidth }, dateAnimationSpeed, dateEasingType, function() {
            // remove the last thumbnails
            $(allNewsDates[allNewsDates.length - 1]).remove();
            // reset the position of the first element
            $(allNewsDates[0]).css('position', 'static').css('left', 0);
            // reset the position of the slider
            $('div.newsBucket div.newsnav div.absolute').css('left', 0);
            // rebuild the thumbnail list
            allNewsDates = $('div.newsBucket div.newsnav p');
        });

        // animate the slider right
        $('div.newsBucket div.news div.absolute').animate({ left: newsItemWidth }, dateAnimationSpeed, dateEasingType, function() {
            // remove the last thumbnails
            $(allNewsContent[allNewsContent.length - 1]).remove();
            // reset the position of the first element
            $(allNewsContent[0]).css('position', 'static').css('left', 0);
            // reset the position of the slider
            $('div.newsBucket div.news div.absolute').css('left', 0);
            // rebuild the thumbnail list
            allNewsContent = $('div.newsBucket div.news div.absolute p');
            sliderMoving = false;
        });
    }
}

function nextNewsItem() {
    if (!sliderMoving) {
        sliderMoving = true;

        // clone the first element and place it at the end
        $('div.newsBucket div.newsnav div.absolute').append($(allNewsDates[0]).clone());
        $('div.newsBucket div.news div.absolute').append($(allNewsContent[0]).clone());

        // rebuild thumbnail list
        allNewsDates = $('div.newsBucket div.newsnav div.absolute p');
        allNewsContent = $('div.newsBucket div.news div.absolute p');

        // animate the slider left
        $('div.newsBucket div.newsnav div.absolute').animate({ left: -newsDateWidth }, dateAnimationSpeed, dateEasingType, function() {
            // remove the first thumbnails
            $(allNewsDates[0]).remove();
            // reset the position of the slider
            $('div.newsBucket div.newsnav div.absolute').css('left', 0);
            // rebuild the thumbnail list
            allNewsDates = $('div.newsBucket div.newsnav div.absolute p');
            sliderMoving = false;
        });
        // animate the slider left
        $('div.newsBucket div.news div.absolute').animate({ left: -newsItemWidth }, dateAnimationSpeed, dateEasingType, function() {
            // remove the first thumbnails
            $(allNewsContent[0]).remove();
            // reset the position of the slider
            $('div.newsBucket div.news div.absolute').css('left', 0);
            // rebuild the thumbnail list
            allNewsContent = $('div.newsBucket div.news div.absolute p');
            sliderMoving = false;
        });
    }
}

$(document).ready(function() {
    allNewsDates = $('div.newsBucket div.newsnav p');
    allNewsContent = $('div.newsBucket div.news p');


    if (allNewsContent.length > 0) {
        $('div.newsnav div.absolute').width(newsDateWidth * (allNewsDates.length + 1));
        $('div.news div.absolute').width(newsItemWidth * (allNewsContent.length + 1));
        $(allNewsContent).show();

        // on click of previous button
        $('div.newsnav a.prev').click(function() {
            prevNewsItem();
            return false;
        });
        // on click of the next button
        $('div.newsnav a.next').click(function() {
            nextNewsItem();
            return false;
        });

        $('div.refresh div.newsBucket').hover(function() {
            clearInterval(newsTimer);
        }, function() {
            newsTimer = setInterval("nextNewsItem()", newsAutoRotateDelay);
        });

        // news timer interval
        newsTimer = setInterval("nextNewsItem()", newsAutoRotateDelay);
    }

    // Section Listing Image Fade-Ins
    $('a.fade').hover(function() {
        $('> .second', this).fadeIn(290);

    }, function() {
        $('> .second', this).fadeOut(220);
    });

    // when I click the top level list item
    $('div#navSide ul > li.expandable > a').click(function() {
        $(this).parents('li').toggleClass('expanded');
        $(this).siblings('ul').slideToggle(250);
        return false;
    });
    $('div#navSide ul > li.expandable a.categoryTitle').click(function() {
        return false;
    });
});


/*---
Homepage Display Ads
---*/

$(document).ready(function () {
    var animationSpeed = 300;
    var easingEffect = "easeOutCirc";

    $("div#displayAds > ul > li").hover(function () {
        $(this).addClass("hover");
        $(this).children("div").css("height", "0").animate({ height: "221px" }, animationSpeed, easingEffect);
    }, function () {
        $(this).children("div").animate({ height: "0" }, animationSpeed, easingEffect, function () {
            $(this).parent().removeClass("hover");
        });
        if ($(this).children("div").size() === 0)
            $(this).removeClass("hover");
    });
});

/*---
Homepage News Ticker
---*/

var newsTickerTimer;
var newsTickerAnimationSpeed = 300;
var newsTickerIntervalSpeed = 5000;
var newsTickerMaxCharacters = 75;

$(document).ready(function () {
    $("div#newsTicker > ul > li > a").each(function () {
        var title = $.trim($(this).html());
        title = title.replace(/\s+/g, " ");

        if (title.length > newsTickerMaxCharacters)
            $(this).html(title.substring(0, newsTickerMaxCharacters) + "...");
    });

    NewsTicker_Start();

    $("div#newsTicker").hover(function () {
        clearInterval(newsTickerTimer);
    }, function () {
        NewsTicker_Start();
    });

    $("div#newsTicker a.previous").click(function () {
        clearInterval(newsTickerTimer);

        var listItems = $("div#newsTicker > ul > li");
        var currentIndex = listItems.index(listItems.filter("li.active"));
        var newIndex = currentIndex - 1 >= 0 ? currentIndex - 1 : listItems.size() - 1;

        NewsTicker_MoveToIndex(newIndex);
    });

    $("div#newsTicker a.next").click(function () {
        clearInterval(newsTickerTimer);

        var listItems = $("div#newsTicker > ul > li");
        var currentIndex = listItems.index(listItems.filter("li.active"));
        var newIndex = currentIndex + 1 < listItems.size() ? currentIndex + 1 : 0;

        NewsTicker_MoveToIndex(newIndex);
    });
});

function NewsTicker_Start() {
    if ($("div#newsTicker > ul > li").size() > 0)
    {
        newsTickerTimer = setInterval(function() {
            var listItems = $("div#newsTicker > ul > li");
            var currentIndex = listItems.index(listItems.filter("li.active"));
            var newIndex = currentIndex + 1 < listItems.size() ? currentIndex + 1 : 0;

            NewsTicker_MoveToIndex(newIndex);
        }, newsTickerIntervalSpeed);
    }
}

function NewsTicker_MoveToIndex(newIndex) {
    var listItems = $("div#newsTicker > ul > li");
    var currentIndex = listItems.index(listItems.filter("li.active"));

    listItems.eq(currentIndex).fadeOut(newsTickerAnimationSpeed, function() {
        $(this).removeClass("active");

        if (listItems.eq(newIndex).hasClass("important"))
            $("div#newsTicker h4").addClass("important");
        else
            $("div#newsTicker h4").removeClass("important");   

        listItems.eq(newIndex).fadeIn(newsTickerAnimationSpeed, function () {
            $(this).addClass("active");               
        });
    });
}
