var open = 0;
var backgroundImageTimerId = 0;
var videoOutTimerId = 0;
var backgroundImageCounter = 1;
var slideIndex = 0;
var backgroundImageLive = '#arc-background-image-A';
var backgroundImageDead = '#arc-background-image-B';
var newHeight = 0;
var newWidth = 0;
var slideIndexFlag = false;
var data;

function init() {
    resizeSitemap();
    start();
}

function start() {
    showFlash = false;
    lines = document.cookie.split(';');

    for (i = 0; i < lines.length; i++) {
        val = lines[i].split('=');
        // uncomment the following line when intro flash video is launched
        //if (val[0] == 'homeVideoVersion' && val[1] == homeVideoVersion) {
        if (true) {
            $j('#arc-home-swf').hide();
            startBackgroundTimer();
            showFlash = false;
            break;
        }
    }

    if (showFlash) {
        document.cookie = 'homeVideoVersion=' + homeVideoVersion + ';expires='
				+ (new Date(2022, 4, 1)).toGMTString();

        if (swfobject.hasFlashPlayerVersion('10.0.0')) {
            var fn = function() {
                var att = {
                    data: 'http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf',
                    width: '100%',
                    height: '100%',
                    wmode: 'opaque'
                };
                var par = {
                    wmode: 'opaque',
                    movie: 'http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf',
                    allowFullScreen: 'true',
                    allowscriptaccess: 'true',
                    flashvars: 'src=http%3A%2F%2Fosmf.org%2Fvideos%2Fcathy2.flv&amp;controlBarMode=floating&amp;scaleMode=stretch&amp;backgroundColor=000000'

                };

                $j('#arc-home-swf').show();
                $j('#arc-home-swf-wrapper').show();

                swfobject.createSWF(att, par, 'arc-home-swf');
            };

        } else {
            var fn = function() {
                var att = {
                    data: 'expressInstall.swf',
                    width: '600',
                    height: '240'
                };
                var par = {};
                var id = 'arc-home-swf';
                swfobject.showExpressInstall(att, par, id, cancelFunction);
            };
        }
        swfobject.addDomLoadEvent(fn);
    }
}

function cancelInstallFlash() {
    startBackgroundTimer();
}

function startBackgroundTimer() {
    $j('#arc-carousel').show();
    resizeCarousel();
    $j('#arc-carousel-wrapper').show();
    $j(backgroundImageLive).show();
    $j(backgroundImageDead).show();
    backgroundImageTimerId = setInterval(function() {
        fadeImage();
    }, (backgroundImageTimer * 1000));
    $j('#arc-slide-play').hide();
    $j('#arc-slide-pause').show();
}

function setCarouselText() {
    $j('#arc-carousel-logo img').attr('src', data.RotItems[slideIndex].ItemLogo);
    $j('#arc-carousel-title img').attr('src', data.RotItems[slideIndex].ItemHeadlineUrl);
    $j('#arc-carousel-message img').attr('src', data.RotItems[slideIndex].ItemDescImgUrl);

    $j('#arc-carousel-title img').attr('alt', data.RotItems[slideIndex].ItemHeadline);
    $j('#arc-carousel-title p').html(data.RotItems[slideIndex].ItemHeadline);
    $j('#arc-carousel-message p').html(data.RotItems[slideIndex].ItemDesc);

    $j('#arc-carousel-link').attr('href', data.RotItems[slideIndex].ItemDetailUrl);
}

function setVideoInfo() {
//Added by Chris Ellenburg to support brands with no videos
    if (data.RotItems[slideIndex].Videos.length == 0) {
        $j('.arc-video-wrapper').hide();
        return;
    } else {
        $j('.arc-video-wrapper').show();
    }
//


    $j('.arc-video-thumbnail').attr('src', data.RotItems[slideIndex].Videos[0].VideoThumb);
    //NEW
    var $videoNav = $j('.arc-home-video-nav');
    var $videoTitle = $j('.arc-home-video-title');
    
    $videoNav.html("");
    for (var i = 0; i < data.RotItems[slideIndex].Videos.length; i++) {
        $videoNav.append("<li><a href='javascript:void(0);' class='video-link' alt='" + data.RotItems[slideIndex].Videos[i].VideoTitle + "' onmouseover='setCurrentVideo(\"" + data.RotItems[slideIndex].Videos[i].VideoTitle + "\",\"" + data.RotItems[slideIndex].Videos[i].VideoURL + "\",\"" + data.RotItems[slideIndex].Videos[i].VideoThumb + "\")' onclick='loadVideo(\"" + data.RotItems[slideIndex].Videos[i].VideoURL + "\")'>" + data.RotItems[slideIndex].Videos[i].VideoTitle + "</a></li>");
    }
    var currentVideo = data.RotItems[slideIndex].Videos[0];
    setCurrentVideo(currentVideo.VideoTitle, currentVideo.VideoURL, currentVideo.VideoThumb);
    //END
}

function setCurrentVideo(title, link, thumb) {
    var $videoTitle = $j('.arc-home-video-title');
    $videoTitle.text(title);
    $j('.arc-video-thumbnail').attr('src', thumb);
    $j('.arc-video-play').unbind('click').click(function() { loadVideo(link);pageTracker._trackEvent(data.RotItems[slideIndex].Videos[0].GATag, 'Click') });
}

function fadeImage() {
    //Check if video is playing...
    if ($j("#lightbox").is(":visible")) {
        stopBackgroundTimer();
        return;
    }
    
    setBackgroundImageSize();
    $j(backgroundImageLive).animate({
        opacity: 0
    }, 700, function() {
        setBackgroundImages();
    });
    //NEW
    //$j("#arc-carousel-wrapper,#arc-carousel").animate({
    //    opacity: 0
    //}, 700);
}

function setBackgroundImages() {
    //$j("#arc-carousel-wrapper,#arc-carousel").animate({
    //    opacity: 1
    //}, 700);
    clearHighlight();
    $j('#arc-slide-' + (slideIndex + 1)).addClass('arc-highlight');

    backgroundImageCounter++;


    if (backgroundImageCounter % 2 == 0) {
        backgroundImageLive = '#arc-background-image-A';
        backgroundImageDead = '#arc-background-image-B';
    } else {
        backgroundImageLive = '#arc-background-image-B';
        backgroundImageDead = '#arc-background-image-A';
    }

    $j(backgroundImageLive).css('z-index', 1);
    $j(backgroundImageLive).css('opacity', 1);
    $j(backgroundImageDead).css('z-index', 0);
    $j(backgroundImageDead).css('opacity', 1);

    setCarouselText();
    setVideoInfo();
    setLeftBorder(slideIndex);

    slideIndex++;
    if (slideIndex == data.RotItems.length) {
        slideIndex = 0;
    }

    $j('img' + backgroundImageDead).attr('src',
			data.RotItems[slideIndex].ScreenImgUrl);
}

function clearHighlight() {

    $j('#arc-carousel-navigator a').each(function() {
        $j(this).removeClass('arc-highlight');
    });
}

function stopBackgroundTimer() {

    $j('#arc-slide-pause').hide();
    $j('#arc-slide-play').show();
    clearInterval(backgroundImageTimerId);
}

function slide(slideNumber) {
    stopBackgroundTimer();
    clearHighlight();
    $j('#arc-slide-' + slideNumber).addClass('arc-highlight');

    nextSlideIndex = slideNumber;
    if (nextSlideIndex == 4) {
        nextSlideIndex = 0;
    }
    slideIndex = slideNumber - 1;

    if ($j(backgroundImageLive).css('z-index') == 1) {

        $j(backgroundImageLive).attr('src',
				data.RotItems[slideIndex].ScreenImgUrl);

        $j(backgroundImageDead).attr('src',
				data.RotItems[nextSlideIndex].ScreenImgUrl);

    } else {
        $j(backgroundImageDead).attr('src',
				data.RotItems[slideIndex].ScreenImgUrl);

        $j(backgroundImageLive).attr('src',
				data.RotItems[nextSlideIndex].ScreenImgUrl);
    }

    setLeftBorder(slideIndex);
    setCarouselText();
    setVideoInfo();
    setBackgroundImageSize();
}


function setLeftBorder(slideIndex) {
    $j('#arc-carousel-border').removeClass()
                              .addClass(data.RotItems[slideIndex].CSSClass);
}

/*
//This is original function
function setLeftBorder(slideIndex) {

switch (slideIndex) {
case 0:
$j('#arc-carousel-border').css('background-color', '#be4fc5');
break;

case 1:
$j('#arc-carousel-border').css('background-color', '#50abbb');
break;

case 2:
$j('#arc-carousel-border').css('background-color', '#76a92e');
break;

case 3:
$j('#arc-carousel-border').css('background-color', '#e15916');
break;
}
}
*/

function gotoSlide(id) {

    if (id.indexOf('1') > -1) {
        slide(1);
        slideIndexFlag = true;
    } else if (id.indexOf('2') > -1) {
        slide(2);
        slideIndexFlag = true;
    } else if (id.indexOf('3') > -1) {
        slide(3);
        slideIndexFlag = true;
    } else if (id.indexOf('4') > -1) {
        slide(4);
        slideIndexFlag = true;
    } else if (id.indexOf('pause') > -1) {
        stopBackgroundTimer();
    } else if (id.indexOf('play') > -1) {
        if (slideIndexFlag) {
            slideIndex++;
            if (slideIndex == data.RotItems.length) {
                slideIndex = 0;
            }
            slideIndexFlag = false;
        }
        setBackgroundImages();
        startBackgroundTimer();
    }
}

function resizeSitemap() {

    $j('#arc-sitemap').css('top', $j(window).height() - 26);
    $j('#arc-sitemap').css('display', 'block');
}

function resizeCarousel() {

    $j('#arc-carousel-wrapper').css('top', ($j(window).height() - 270));
}

function openSiteMap() {

    $j('#arc-sitemap').animate({
        top: ($j(window).height() - $j('#arc-sitemap').height())

    }, 1000);
    $j('#arc-sitemap-arrow').attr('src', '/common/images/Posturepedic/down-arrow.png');
    open = 1;
}

function closeSiteMap() {

    $j('#arc-sitemap').animate({
        top: ($j(window).height() - 26)

    }, 1000);
    $j('#arc-sitemap-arrow').attr('src', '/common/images/Posturepedic/up-arrow.png');
    open = 0;
}

function resizeBackgroundImage() {

    best = Math.min($j(backgroundImageLive).width() / $j(window).width(), $j(
			backgroundImageLive).height() / $j(window).height());
    newWidth = $j(backgroundImageLive).width() / best;
    newHeight = $j(backgroundImageLive).height() / best;
    setBackgroundImageSize();
}

function setBackgroundImageSize() {

    $j(backgroundImageLive).attr({ 'height': newHeight });
    $j(backgroundImageLive).attr({ 'width': newWidth });

    $j(backgroundImageDead).attr({ 'height': newHeight });
    $j(backgroundImageDead).attr({ 'width': newWidth });
}



jQuery(document).ready(function() {

    /* 
    
    'RotItems': [
    {
    'ScreenImgUrl': 'urlToFullScreenImage1',
    'ActLinkImgUrl': 'urlToActLinkImgUrl1',
    'InactLinkImgUrl': 'urlToInactLinkImgUrl1',
    'VidCtaImgUrl': 'urlToVidCtaImgUrl1',
    'ItemLogo': 'itemLogo1',
    'ItemHeadline': 'itemHeadline1',
    'ItemHeadlineUrl': 'itemHeadlineUrl1',
    'ItemDesc': 'itemDesc1',
    'ItemDescImgUrl': 'itemDescImgUrl1',
    'ItemDetailText': 'itemDetailText1',
    'ItemDetailUrl': 'itemDetailUrl1',
    'VidUrl': 'urlToVid1'
    },
    {
    'ScreenImgUrl': 'urlToFullScreenImage2',
    'ActLinkImgUrl': 'urlToActLinkImgUrl2',
    'InactLinkImgUrl': 'urlToInactLinkImgUrl2',
    'VidCtaImgUrl': 'urlToVidCtaImgUrl2',
    'ItemLogo': 'itemLogo2',
    'ItemHeadline': 'itemHeadline2',
    'ItemHeadlineUrl': 'itemHeadlineUrl2',
    'ItemDesc': 'itemDesc2',
    'ItemDescImgUrl': 'itemDescImgUrl2',
    'ItemDetailText': 'itemDetailText2',
    'ItemDetailUrl': 'itemDetailUrl2',
    'VidUrl': 'urlToVid2'
    }
    ]
    

    */

    $j('div.footer').css('margin-top', 0);
    $j('#noscript').hide();

    request = 'Utility/ImageRotationHttpHandler.ashx'
    $j.ajax({
        url: request,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        success: function(json) {
            data = json;
            $j(backgroundImageLive).attr('src',
						data.RotItems[0].ScreenImgUrl);
            $j(backgroundImageDead).attr('src',
						data.RotItems[1].ScreenImgUrl);
            resizeBackgroundImage();
        }
    });
    setBackgroundImages();


    // Chrome, Safari workaround
    $j(backgroundImageLive).load(function() {

        $j(this).removeAttr('width').removeAttr('height').css({
            width: '',
            height: ''
        });
        resizeBackgroundImage();
    });

    // Events
    $j(window).resize(function() {
        resizeSitemap();
        resizeBackgroundImage();
        resizeCarousel();
    });

    $j('#arc-sitemap-txt-wrapper').click(function() {
        if (open == 1) {
            closeSiteMap();
        } else {
            openSiteMap();
        }
    });


    $j('#arc-sitemap-bar').click(function() {
        if (open == 1) {
            closeSiteMap();
        } else {
            openSiteMap();
        }
    });

    $j('html').keydown(function(event) {
        if (event.keyCode == '38') {
            openSiteMap();
        } else if (event.keyCode == '40') {
            closeSiteMap();
        }
    });

    $j('#arc-carousel-navigator a').each(function() {
        $j(this).click(function() {
            gotoSlide($j(this).attr('id'));
        });
    });

    $j('.arc-video-wrapper').mouseover(function() {
        stopBackgroundTimer();
        $j(this).addClass('active');
        $j('.arc-home-video-title').show();
//Causing problems in IE        
//        $j('.arc-video-play').animate({
//            opacity: .8
//        }, 200);
        $j('.arc-video-play').show();
        $j('.arc-video-icon').hide();
        $j('.arc-home-video-nav').show();
        clearTimeout(videoOutTimerId);
    });

    $j('.arc-video-wrapper').mouseout(function() {
        videoOutTimerId = setTimeout(function() {
            $j('.arc-video-wrapper').removeClass('active');
            $j('.arc-home-video-title').hide();
//            $j('.arc-video-play').animate({
//                opacity: 0
            //            }, 200);
            $j('.arc-video-play').hide();
            $j('.arc-video-icon').show();
            $j('.arc-home-video-nav').hide();
            resizeBackgroundImage();
            startBackgroundTimer();
        }, 700);
    });

    init();

    /*
    $j('a#arc-home-flash-video').fancybox({
    'opacity': true,
    'modal': false,
    'hideOnOverlayClick': true,
    'overlayColor': '#000',
    'overlayOpacity': '0.8',
    'showCloseButton': true,
    'transitionIn': 'none',
    'transitionOut': 'none',
    'padding': '10',
    'margin': '20',
    'url': data.RotItems[0].VidUrl,
    'type': 'swf',
    'swf': "{wmode: 'transparent'}",
    'onStart': function () { stopBackgroundTimer(); }
    });
    */
});

