﻿var closemenu =  new Array(3);
var openmenu =  new Array(3);
var menustatus =  new Array(3);
var menuheight =  new Array(3);
var menuclosedelay = 200;
var menuopendelay = 300;
var mediacontent = null;
var startpage = 1;
var startkey = "";
var glow;
var noglow;
var content;
var contentSlider;
var contentBody;

$(document).ready(function() {
    if (screen.height < 900) {
        $('.PageContainer').css({ position: 'static', margin: '0 auto' });
    }

    menustatus[0] = 'closed';
    menustatus[1] = 'closed';
    menustatus[2] = 'closed';
    $('.Menu').each(function(index) {
        menuheight[index] = $(this).height();
        if ($.browser.name == 'chrome' ||
            $.browser.name == 'safari') {
            menuheight[index] = 200;
            $(this).closest('table').wrap('<div class="ChromeContainer"></div>');
            $('.ChromeContainer').css({ height: 200, overlfow: 'hidden' });
            $(this).parent().css({ verticalAlign: 'top', height: 0, overflow: 'hidden' });
        }
        $(this).css({ height: 0, border: 'none' });
    });


    $('.ListButton').each(function(index) {
        $(this).hover(function() {
            if (closemenu[index] != null) {
                clearTimeout(closemenu[index]);
                closemenu[index] = null;
            }
            var menu = $(this).parent().find('.Menu');
            openmenu[index] = setTimeout(function() { openMenu(menu, index) }, menuopendelay);
        }, function() {
            if (openmenu[index] != null) {
                clearTimeout(openmenu[index]);
                openmenu[index] = null;
            }
            var menu = $(this).parent().find('.Menu');
            closemenu[index] = setTimeout(function() { closeMenu(menu, index) }, menuclosedelay);
        });
    });
    $('.Menu').each(function(index) {
        $(this).hover(function() {
            if (closemenu[index] != null) {
                clearTimeout(closemenu[index]);
                closemenu[index] = null;
            }
            var menu = $(this);
            openmenu[index] = setTimeout(function() { openMenu(menu, index) }, menuopendelay);
        }, function() {
            if (openmenu[index] != null) {
                clearTimeout(openmenu[index]);
                openmenu[index] = null;
            }
            var menu = $(this);
            closemenu[index] = setTimeout(function() { closeMenu(menu, index) }, menuclosedelay);
        });
    });

    if (startpage == 3) {
        BehindTheCushion_Click();
    } else if (startpage == 4) {
        NationalAddy_Click();
    } else if (startpage == 2) {
        $('#MediaContainer').html('<table cellspacing="0" cellpadding="0" border="0"><tr><td style="width: 380px; height: 214px" valign="middle" align="center" class="Loading"><img src="images/loading_dark.gif"><br />LOADING</td><tr></table>');
        if (startkey == "")
            PageMethodWithPath(service, "GetSlideShowContent", ["path", $('.ShowSlideShow.Default').attr('showpath')], switchContent, AjaxError);
        else
            PageMethodWithPath(service, "GetSlideShowContent", ["path", $(".ShowSlideShow[key='" + startkey + "']").attr('showpath')], switchContent, AjaxError);
    } else {
        if (startkey == "")
            loadVideo($('.ShowVideo.Default').attr('video'));
        else
            loadVideo($(".ShowVideo[key='" + startkey + "']").attr('video'));
    }

    $("#BehindTheCushionSlider").slider({
        orientation: 'vertical',
        change: handleChange,
        slide: handleSlide,
        min: -100,
        max: 0,
        animate: true
    });

    $("#NationalAddySlider").slider({
        orientation: 'vertical',
        change: handleChange,
        slide: handleSlide,
        min: -100,
        max: 0,
        animate: true
    });

    $('.ShowVideo').click(function(e) {
        registerWithAnalytics("Episodes", $(this).attr('key'));
        loadVideo($(this).attr('video'));
        if (e) e.preventDefault();
    });

    $('.ShowSlideShow').click(function(e) {
        registerWithAnalytics("Extra-Features", $(this).attr('key'));
        clearMediaContainer();
        $('#MediaContainer').html('<table cellspacing="0" cellpadding="0" border="0"><tr><td style="width: 380px; height: 214px" valign="middle" align="center" class="Loading"><img src="images/loading_dark.gif"><br />LOADING</td><tr></table>');
        PageMethodWithPath(service, "GetSlideShowContent", ["path", $(this).attr('showpath')], switchContent, AjaxError);
        if (e) e.preventDefault();
    });

    $('.ExtraFeatureSlideShow').mouseover(function() {
        mediacontent.cycle('pause');
        $('<div />').html("<img src='images/pause.png' width='32' height='32'/>").addClass('PauseContainer').appendTo('#MediaContainer');
        $(".PauseContainer").css({ marginTop: -214, opacity: .75 });

        var cont = $.browser.name == 'msie' ? ".ExtraFeatureSlideShow" : ".PauseContainer";

        $(cont).mouseleave(function() {
            mediacontent.cycle('resume');
            $(".PauseContainer").remove();
        });
        $(".PauseContainer").show();
    });

    $('#BehindTheCushionContent').mousewheel(handleMouseScroll);
    $('#NationalAddyContent').mousewheel(handleMouseScroll);
    contentBody = $('#BehindTheCushionBody');
    contentSlider = $('BehindTheCushionSlider');

    glow = new Image(754, 690);
    glow.src = imagePath + 'background-addy-glow.jpg';
    noglow = new Image(754, 690);
    noglow.src = imagePath + 'background-addy.jpg';
    $("#NationalAddy").hover(function() {
        //$(".InnerPageContainer").css('backgroundImage', "url('" + glow.src + "')");
        $("#AddyGlow").show();
    }, function() {
        //$(".InnerPageContainer").css('backgroundImage', "url('" + noglow.src + "')");
        $("#AddyGlow").hide();
    });
});
function registerWithAnalytics(section, key) {
    try {
        pageTracker._trackPageview("/" + section + "/" + key + ".aspx");
    }
    catch (err) { }
}
function loadVideo(file) {
    $.fn.media.defaults.flashvars.repeat = 'none';
    $.fn.media.defaults.flashvars.shuffle = 'false';
    $.fn.media.defaults.flashvars.mute = 'false';
    $.fn.media.defaults.flashvars.bufferlength = 10;
    $.fn.media.defaults.width = 380;
    $.fn.media.defaults.height = 214;
    clearMediaContainer();
    $('#MediaContainer').html("<div class='Media' href='" + file + "'></div>");
    $('.Media').media();
    mediacontent = null;
}

function loadAudio(file) {
    $.fn.media.defaults.flashvars.repeat = 'always';
    $.fn.media.defaults.flashvars.shuffle = 'true';
    $.fn.media.defaults.flashvars.mute = 'false';
    $.fn.media.defaults.width = 1;
    $.fn.media.defaults.height = 1;
    $.fn.media.defaults.flashvars.bufferlength = 1;
    $('#MediaContainer').append("<div class='Audio' href='/media/audio/audio.xml'></div>");
    $('.Audio').media();  
    $('#MediaContainer').append("<div class='Speaker' status='playing'><img src='images/unmuted.png' /></div>");

    $('.Speaker').click(function() {
        if ($(this).attr('status') == 'playing') {
            document.getElementById($('.Audio').children(':first-child').attr('id')).sendEvent("MUTE", "true");
            $(this).attr('status', 'paused');
            $(this).children('img').attr('src', 'images/muted.png');
        } else {
            document.getElementById($('.Audio').children(':first-child').attr('id')).sendEvent("MUTE", "false");
            $(this).children('img').attr('src', 'images/unmuted.png');
            $(this).attr('status', 'playing');
        }
    });
}


var slideshowpass = 0;
function switchContent(results) {
    mediacontent = $("#ExtraFeaturesContainer");
    mediacontent.html(results.d);
    slideshowpass = 0;
    checkSlideShowImages();
}
function checkSlideShowImages() {
    var images = mediacontent.children("img");
    var loaded = true;
    for (i = 0; i < images.length; i++) {
        if (!images[i].complete) {
            if (slideshowpass < 5) {
                setTimeout(checkSlideShowImages, 500);
                slideshowpass++;
                loaded = false;
            }
            break;
        }
    }
    if (loaded) displaySlideShow();
}
function displaySlideShow() {
    clearMediaContainer();
    mediacontent.appendTo('#MediaContainer');
    mediacontent.css({ display: 'block' });
    mediacontent.cycle({
        fx: 'fade',
        speed: 2500
    })
    loadAudio();
}

function AjaxError(result) {
    alert("Error: " + result.d);
}


function openMenu(menu, index)
{
    if (menustatus[index] == 'closed' || menustatus[index] == 'closing')
    {
        menustatus[index] = 'opening'
        menu.css({ border: 'solid 1px white' });
        menu.stop().animate({ height: menuheight[index] }, function() { menustatus[index] = 'open'; });
    }
}
function closeMenu(menu, index)
{
    if (menustatus[index] == 'open' || menustatus[index] == 'opening')
    {
        menustatus[index] = 'closing'
        menu.stop().animate({ height: 0 }, function() {
            menustatus[index] = 'closed'; menu.css({ border: 'none' });
        });
    }
    closemenu[index] = null;
}
function clearMediaContainer()
{
    if (mediacontent != null)
    {
        if (mediacontent.cycle) mediacontent.cycle('stop');
        mediacontent.appendTo('#HiddenContent');
    }
    if (document.getElementById($('.Media').children(':first-child').attr('id')) != null) {
        document.getElementById($('.Media').children(':first-child').attr('id')).sendEvent("STOP");
    }
    if (document.getElementById($('.Audio').children(':first-child').attr('id')) != null) {
        document.getElementById($('.Audio').children(':first-child').attr('id')).sendEvent("STOP");
    }
       
    $('#MediaContainer').empty();
}


function BehindTheCushion_Click() {
    clearMediaContainer();
    
    contentSlider = $('#BehindTheCushionSlider');
    contentSlider.slider('value', 0);

    contentBody = $('#BehindTheCushionBody');
    
    mediacontent  = $('#BehindTheCushionContent');
    mediacontent.appendTo('#MediaContainer');
    
    return false;
}

function NationalAddy_Click() {
    clearMediaContainer();
    
    contentSlider = $('#NationalAddySlider');
    contentSlider.slider('value', 0);

    contentBody = $('#NationalAddyBody');
    
    mediacontent  = $('#NationalAddyContent');
    mediacontent.appendTo('#MediaContainer');
    
    return false;
}

function handleChange(e, ui) {
    var maxScroll = contentBody.attr("scrollHeight") - contentBody.height();
    contentBody.attr({ 
        scrollTop: -ui.value * (maxScroll / 100)
    }, 1000);
}

function handleMouseScroll(e, d) {
    var maxScroll = contentBody.attr("scrollHeight") - contentBody.height();
    var dir = d > 0 ? 5 : -5;
    contentSlider.slider('value', contentSlider.slider('value') + dir);
}

function handleSlide(e, ui) {
    var maxScroll = contentBody.attr("scrollHeight") - contentBody.height();

    contentBody.stop().animate({ 
        scrollTop: -ui.value * (maxScroll / 100)   
    });
}





function PageMethod(fn, paramArray, successFn, errorFn) {
    return PageMethodWithPath(window.location.pathname, fn, paramArray, successFn, errorFn);
}
function PageMethodWithPath(path, fn, paramArray, successFn, errorFn) {
    var pagePath = path;

    //Create list of parameters in the form:  
    //{"paramName1":"paramValue1","paramName2":"paramValue2"}  
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    //Call the page method  
    $.ajax({
        type: "POST",
        url: pagePath + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}
