/* SVN FILE: $Id: application-0.0.1.js 93 2009-01-08 19:32:31Z jleveille $ */
/**
 * Main javascript player file
 * @filesource
 * @copyright		Copyright, Video On Location.
 * @version			$Rev: 93 $
 * @modifiedby		$LastChangedBy: jleveille $
 * @lastmodified	$Date: 2009-01-08 14:32:31 -0500 (Thu, 08 Jan 2009) $
 */
var VOLI = function(){

    var count = 0;
    var lastTime = 0;
    var msnPayLoad = null;
    var slideExtension = '.jpg';
    var slideExtensionPattern = /\d{1,4}/; //match between 1 and 4 digits
    var asxDirectory = '/media/';
    
    /**
     * Sets up additional divs for player skin
     * @access private
     */
    function skinPlayer(){
    
        $("div#torso").wrap('<div class="dialog">' +
        '<div class="bd">' +
        '<div class="c">' +
        '<div class="s">' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>');
        
        $('div.dialog').prepend('<div class="hd">' +
        '<div class="c"></div>' +
        '</div>').append('<div class="ft">' +
        '<div class="c"></div>' +
        '</div>');
    }
    
    /**
     * Load include files associated with various sections of the player
     * @access private
     */
    function loadIncludeFiles(){
    
        if (VOLI.config.showHeaderNavBar) {
            $("#head-nav").show().load("core/section-includes/header-navigation.inc.htm?stamp=" + getStamp(), function(){
                styleHeader();
            });
        }
        
        if (VOLI.config.showPlayerNavBar) {
            $("#nav").show();
            $("#nav p").load("core/section-includes/player-navigation.inc.htm?stamp=" + getStamp(), function(){
                setupLiveMessangerChat();
            });
        }
        
        if (VOLI.config.showAgenda) {
            $("#agenda").show();
            
            if (VOLI.config.playerMode == 'l') {
                $("div.in-agenda").load("core/section-includes/meeting-details.inc.htm?stamp=" + getStamp());
            }
            else {
                $("div.in-agenda").load("core/section-includes/meeting-agenda.inc.htm?stamp=" + getStamp(), function(){
                    setUpAgendaNavigation();
                });
            }
            
        }
        
        if (VOLI.config.showResources) {
            $("#resources").show().load("core/section-includes/player-resources.inc.htm?stamp=" + getStamp(), function(){
                loadResourceLinks();
            });
        }
        
        if (VOLI.config.showFooter) {
            $("#footer").show().load("core/section-includes/footer.inc.htm?stamp=" + getStamp(), function(){
                styleFooter();
            });
        }
        
    }
    
    /**
     * Sets up MSN messanger chat application
     * @access private
     */
    function setupLiveMessangerChat(){
    
        if (VOLI.config.chatEnabled && VOLI.config.playerMode == 'l') {
            $('div#viewer').css('position', 'static');
            
            $('a#activate-chat').toggle(function(){
            
                //lazy load msn javascript
                //this payload is only needed if the user actually clicks on the live support link
                if (!msnPayLoad) {
                    msnPayLoad = activateMsnJavascript;
                    msnPayLoad();
                }
                
                $('div#daddy-shoutbox').show();
                $('#activate-chat').html('Close Live Support');
            }, function(){
                $('div#daddy-shoutbox').hide();
                $('#activate-chat').html('Open Live Support');
            });
            
            $('#daddy-shoutbox h2 img#close-live-support').click(function(){
                $('div#daddy-shoutbox').hide();
                $('#activate-chat').html('Open Live Support');
            });
        }
        else {
            $('span.activate-chat').hide();
            $('div#daddy-shoutbox').hide();
        }
    }
    
    /**
     * Activate/load msn javascript
     * @access private
     */
    function activateMsnJavascript(){
    
        //Grab the necessary scripts for live chat
        $.getScript("http://settings.messenger.live.com/controls/1.0/PresenceButton.js", function(){
            $.getScript("http://messenger.services.live.com/users/31457d077f26c997@apps.messenger.live.com/presence?mkt=en-US&cb=Microsoft_Live_Messenger_PresenceButton_onPresence", function(){
                $("div#daddy-shoutbox div.in-shoutbox").load("core/section-includes/live-messanger-chat.inc.htm?stamp=" + getStamp());
                $("div#daddy-shoutbox h2").append('<a target="_blank" id="live-support-window" href="http://settings.messenger.live.com/Conversation/IMMe.aspx?invitee=31457d077f26c997@apps.messenger.live.com&mkt=en-US&useTheme=true&foreColor=333333&backColor=E8F1F8&linkColor=333333&borderColor=AFD3EB&buttonForeColor=333333&buttonBackColor=EEF7FE&buttonBorderColor=AFD3EB&buttonDisabledColor=EEF7FE&headerForeColor=0066A7&headerBackColor=8EBBD8&menuForeColor=333333&menuBackColor=FFFFFF&chatForeColor=333333&chatBackColor=FFFFFF&chatDisabledColor=F6F6F6&chatErrorColor=760502&chatLabelColor=6E6C6C"><img style="border-style: none;" src="http://messenger.services.live.com/users/31457d077f26c997@apps.messenger.live.com/presenceimage?mkt=en-US" width="16" height="16" /></a>');
            })
        });
    }
    
    /**
     * Load resource links associated with a broadcast
     * @access private
     */
    function loadResourceLinks(){
    
        $.ajax({
            type: "GET",
            url: "resources.xml?stamp=" + getStamp(),
            dataType: "xml",
            success: function(xmlData){
                displayResources(xmlData);
            }
        });
    }
    
    /**
     * Display resource links gathered from xml file and associated with a broadcast
     * @access private
     */
    function displayResources(xml){
    
        //iterate over each xml element, starting at the first resource item
        var links = '', title, filename;
        var resources = [];
        
        $(xml).find('resource').each(function(i){ // apply this function to each reminder (index as parameter)
            title = $("title", this).text();
            filename = $("filename", this).text();
            if ($.trim(title) != "" && $.trim(filename) != "") {
                resources[i] = '<li><a href="docs/' + filename + '" target="_blank">' + title + '</a></li>';
            }
        });
        
        //grab the first half of our links
        links = '<ul class="resources">';
        
        if (resources.length == 0) {
            links += '<li>No Resources Available</li>';
        }
        else {
            for (var i = 0, j = Math.floor(resources.length / 2); i < j; i++) {
                links += resources[i];
            }
        }
        
        links += '</ul>';
        
        if (resources.length != 0) {
            //grab the second half of our links
            links += '<ul class="resources">';
            
            for (var i = Math.floor(resources.length / 2), j = resources.length; i < j; i++) {
                links += resources[i];
            }
            
            links += '</ul>';
        }
        
        //append the list of links after the heading of our resources div
        $('#resources h2').after(links);
    }
    
    /**
     * Style player header
     * @access private
     */
    function styleHeader(){
    
        //set properties for header link/text colors
        $('#head p#head-nav a, #head p#head-nav').css("color", VOLI.config.headerLinkColor);
        $('#head p#head-nav a').css("border-color", VOLI.config.headerLinkColor);
        
        //set logo for the player
        $('#logo').html('<img src="player-identity/' + VOLI.config.logo + '" alt="' + VOLI.config.companyTitle + '" height="' + VOLI.config.logoHeight + '" width="' + VOLI.config.logoWidth + '"/>');
    }
    
    /**
     * Style player footer
     * @access private
     */
    function styleFooter(){
    
        //set properties for footer link/text colors
        $('#footer, #footer a').css('color', VOLI.config.footerLinkColor);
        $('#footer a').css('border-color', VOLI.config.footerLinkColor);
		
		//set year in footer
		var d = new Date();
		var year = d.getFullYear();
		$('#footer .footer-year').text(year);
    }
    
    /**
     * Adjust player based on player mode
     * @access private
     */
    function adjustForPlayerMode(){
    
        if (VOLI.config.playerMode == 'a') {
            $('#time').remove();
        }
        
        if (VOLI.dpviAndArchived()) {
            // Add slide control affects
            $('#controls').addClass("hide");
            
            var controls_height = $('#controls').height();
            var slide_height = $('#viewer').height();
            $('#viewer #controls').css('top', slide_height);
            
            $("#viewer").hover(function(){
                $('#controls').addClass("show").removeClass("hide").animate({
                    "top": "-=" + controls_height + "px"
                }, "fast");
            }, function(){
                $("#controls").animate({
                    "top": slide_height + "px"
                }, "fast", function(){
                    $('#controls').addClass("hide").removeClass("show");
                });
            });
        }
        else {
            $('#controls').addClass("hide").removeClass("show");
        }
    }
    
    /**
     * Add player styles based on configuration file
     * @access private
     */
    function styleSite(){
    
        document.title = VOLI.config.companyTitle;
        
        //ensure we are serving the correct stylesheet
        switchStylestyle(VOLI.config.player);
        
        //setup the loading indicator so that it includes the logo
        $('#loading-mask').css('background-color', VOLI.config.bodyBackgroundColor);
        
        $('div.loading-indicator').html('Loading ...');
        
        //set properties for body background
        if (VOLI.config.bodyHasBackgroundImage) {
            cssObj = {
                'background-color': VOLI.config.bodyBackgroundColor,
                'background-image': "url(player-identity/" + VOLI.config.backgroundImage + ")",
                'background-position': "left top",
                'background-repeat': 'repeat-x'
            }
            
            $('body').css(cssObj);
        }
        else {
            $('body').css('background-color', VOLI.config.bodyBackgroundColor);
        }
        
    }
    
    /**
     * Serve stylesheet based on config player selection
     * @param string styleName - The name of player we want to serve (also the title of the css style definition)
     * @access private
     */
    function switchStylestyle(styleName){
       $('link[@rel*=style][@title*=dpv]').each(function(i){
          this.disabled = true;
          if (this.getAttribute('title') == styleName) {
             this.disabled = false;
          }
       });
    }
    
    /**
     * Set up player agenda navigation
     * @return Boolean false to prevent default behavior
     * @access private
     */
    function setUpAgendaNavigation(){
    
        if (VOLI.config.playerMode.toLowerCase() == 'a') {
            $("#asxLinks a[rel*='asx']").click(function(){
            
                var asx = $(this).attr('rel').match(slideExtensionPattern);
                VOLI.currentSlide = asx;
                var image = asx + slideExtension;
                
                VOLI.updateSlideImage(image);
                
                refreshIframe(asx);
                refreshControls();
                return false;
            });
        }
        
    }
    
    /**
     * Refresh slide controls
     * @access private
     */
    function refreshControls(){
    
        if (VOLI.dpviAndArchived()) {
            if ((VOLI.currentSlide == VOLI.config.firstSlide) || (parseInt(VOLI.currentSlide, 10) == (parseInt(VOLI.config.firstSlide, 10) + 1))) {
                $("#viewer-next").html('slide ' + (parseInt(VOLI.currentSlide, 10) + 1) + ' &raquo;');
                $("#viewer-previous").hide();
                $("span.viewer-divider").hide();
            }
            else 
                if (VOLI.currentSlide == VOLI.config.lastSlide) {
                    $("#viewer-next").hide();
                    $("span.viewer-divider").hide();
                }
                else {
                    $("#viewer-previous").show().html('&laquo; slide ' + (parseInt(VOLI.currentSlide, 10) - 1));
                    $("span.viewer-divider").show();
                    $("#viewer-next").show().html('slide ' + (parseInt(VOLI.currentSlide, 10) + 1) + ' &raquo;');
                }
        }
    }
    
    /**
     * Set up slide controls
     * @access private
     */
    function setupSlideControls(){
    
        if (VOLI.dpviAndArchived()) {
        
            refreshControls();
            
            $("#viewer-previous").click(function(){
                var prevSlide = '';
                
                var intPrevSlide = parseInt(VOLI.currentSlide, 10) - 1;
                var stringPrevSlide = intPrevSlide.toString();
                
                //I don't like this, but I'll assume that there will never be more than 999 slides
                if (stringPrevSlide.length < 2) {
                    prevSlide = '00' + stringPrevSlide;
                }
                else 
                    if (stringPrevSlide.length < 3) {
                        prevSlide = '0' + stringPrevSlide;
                    }
                    else {
                        prevSlide = stringPrevSlide;
                    }
                
                var image = prevSlide + slideExtension;
                
                VOLI.currentSlide = prevSlide;
                VOLI.updateSlideImage(image);
                
                refreshIframe(prevSlide);
                refreshControls();
                
                return false;
            });
            
            $("#viewer-next").click(function(){
                var nextSlide = '';
                
                var intNextSlide = parseInt(VOLI.currentSlide, 10) + 1;
                var stringNextSlide = intNextSlide.toString();
                
                //I don't like this, but I'll assume that there will never be more than 999 slides
                if (stringNextSlide.length < 2) {
                    nextSlide = '00' + stringNextSlide;
                }
                else 
                    if (stringNextSlide.length < 3) {
                        nextSlide = '0' + stringNextSlide;
                    }
                    else {
                        nextSlide = stringNextSlide;
                    }
                
                var image = nextSlide + slideExtension;
                
                VOLI.currentSlide = nextSlide;
                VOLI.updateSlideImage(image);
                
                refreshIframe(nextSlide);
                refreshControls();
                
                return false;
            });
            
            $("#viewer-next, #viewer-previous").click(function(){
                $('#controls').addClass("hide").removeClass("show");
            });
        }
        
    }
    
    /**
     * Refresh player iframe
     * @param string asx			asx file identifier
     * @access private
     */
    function refreshIframe(asx){
    
        //access child iframe and disable player in ie6
        //set src for ie6 after a pause
        var player = window.frames['iframePlayer'].document.getElementById('MediaPlayer');
        
        if ($.browser.msie && $.browser.version == '6.0') {
            player.stop();
            
            setTimeout(function(){
                $("#iframePlayer").attr('src', 'player.html?asx=' + asx);
            }, 1000);
        }
        else {
            $("#iframePlayer").attr('src', 'player.html?asx=' + asx);
        }
    }
    
    /**
     * Get time stamp
     * @return Long timestamp
     * @access private
     */
    function getStamp(){
    
        var stamp = new Date();
        return stamp.getTime();
    }
    
    return {
        config: {},
        currentSlide: '',
        firstSlide: '',
        lastSlide: '',
        player: '', //this is only for the sucky ie
        sessionCheck: 'sessionCheck',
        
        /**
         * Main init method
         * @access public
         */
        init: function(){
        
            var passedIeTest = $.browser.msie && (parseInt(jQuery.browser.version) >= 7);
            
            if (VOLI.config.skinPlayer && (passedIeTest || !$.browser.msie)) {
                skinPlayer();
            }
            else {
                $('#container').addClass('noSkin');
                $('#torso').addClass('tBorder');
            }
            
            VOLI.currentSlide = VOLI.config.firstSlide;
            VOLI.player = VOLI.config.player;
            
            styleSite();
            loadIncludeFiles();
            adjustForPlayerMode();
            setupSlideControls();
            
            //check for active session (in live mode)
            if (VOLI.config.playerMode.toLowerCase() == 'l' && VOLI.config.sessionCheckActive) {
                VOLI.sessionCheck = window.setInterval(function(){
                    VOLI.checkForActiveSession()
                }, VOLI.config.sessionCheckInterval);
            }
        },
        
        /**
         * Check for an active session
         * @access public
         */
        checkForActiveSession: function(){
        
            $.ajax({
                type: "GET",
                url: 'core/logic/' + VOLI.config.sessionCheckFile + '?stamp=' + getStamp(),
                dataType: "json",
                success: function(response){
                    if (!response.success) {
                        window.location = VOLI.config.sessionCheckRedirect;
                    }
                },
                error: function(o, errorType, exception){
                    window.clearInterval(VOLI.sessionCheck);
                    
                    //ensure that the main portion of the player is not visible if the session check failed
                    $('#torso').remove();
                    
                    alert('An unexpected error has been encountered. It is required that you reactivate this session.');
                    window.location = VOLI.config.sessionCheckRedirect;
                }
            });
        },
        
        /**
         * Get player type
         * @access public
         */
        getPlayer: function(){
        
            return VOLI.player;
        },
        
        /**
         * Check if dpvi and archived
         * @access public
         */
        dpviAndArchived: function(){
        
            return VOLI.config.playerMode.toLowerCase() == 'a' && VOLI.config.player.toLowerCase() == 'dpvi';
        },
        
        /**
         * With every injection point that is reached in the media, this function is called
         * @param string bstrType			The injection point type
         * @param string bstrParam		   The name given to the injection point
         * @access public
         */
        processData: function(bstrType, bstrParam){
        
            if (VOLI.config.player == 'dpvi') {
                var type = bstrType.toLowerCase();
                var image = null;
                
                if (type == 'page' || type == 'image') {
                    image = bstrParam.match(slideExtensionPattern);
                }
                else {
                    image = VOLI.config.firstSlide;
                    alert('An unexpected error has occured (invalid injection point type).  Please contact technical support.');
                }
                
                var imagex = image + slideExtension;
                
                VOLI.currentSlide = image;
                VOLI.updateSlideImage(imagex);
                refreshControls();
            }
        },
        
        /**
         * Update the slide image
         * @param string image
         * @access public
         */
        updateSlideImage: function(image){
        
            var slide_height = $('#viewer').height();
            
            $('#viewer img').fadeOut("normal", function(){
                $('#viewer img').replaceWith('<img src="slides/' + image + '" />');
                $("#controls").css("top", slide_height + "px");
            });
            
            $('#viewer img').fadeIn("normal");
        },
        
        /**
         * get cookie
         * @param string cookie name
         * @access public
         */
        getCookie: function(name){
        
            var start = document.cookie.indexOf(name + "=");
            var len = start + name.length + 1;
            if ((!start) && (name != document.cookie.substring(0, name.length))) {
                return null;
            }
            if (start == -1) 
                return null;
            var end = document.cookie.indexOf(';', len);
            if (end == -1) 
                end = document.cookie.length;
            return unescape(document.cookie.substring(len, end));
        },
        
        /**
         * set cookie
         * @param string cookie name
         * @param string cookie value
         * @param string expires
         * @param string path
         * @param string domain
         * @param string secure
         * @access public
         */
        setCookie: function(name, value, expires, path, domain, secure){
        
            var today = new Date();
            today.setTime(today.getTime());
            if (expires) {
                expires = expires * 1000 * 60 * 60 * 24;
            }
            var expires_date = new Date(today.getTime() + (expires));
            document.cookie = name + '=' + escape(value) +
            ((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
            ((path) ? ';path=' + path : '') +
            ((domain) ? ';domain=' + domain : '') +
            ((secure) ? ';secure' : '');
        },
        
        /**
         * set cookie
         * @param string cookie name
         * @param string path
         * @param string domain
         * @access public
         */
        deleteCookie: function(name, path, domain){
        
            if (BAI.getCookie(name)) 
                document.cookie = name + '=' +
                ((path) ? ';path=' + path : '') +
                ((domain) ? ';domain=' + domain : '') +
                ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
        }
    };
    
}
();
