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/';   
   
   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>');
   }
   
   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();                                                                     
         });   
      }
      
   }
   
   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();
      }
   }
   
   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>');                                                                                                                                                                                   
         })
      });   
   }
      
   function loadResourceLinks() {
      
      $.ajax({
         type: "GET",
         url: "resources.xml?stamp=" + getStamp(),
         dataType: "xml",
         success: function(xmlData)
         {
            displayResources(xmlData);
         }
      });      
   }
   
   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 + '">' + 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);
   }
   
   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 + '"/>');
   }
   
   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);
   }
   
   function adjustForPlayerMode() {
      
      if(VOLI.dpviAndArchived())
      {         
         // Add slide control affects
         $('#controls').addClass("hide");
         $('#time').remove();
         
         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");
      }
      
   }
   
   function styleSite() {
      document.title = VOLI.config.companyTitle;
      
      //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);
      }
                  
   }
   
   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;
         });
      }
      
   }
   
   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;');  
         }
      }
   }
   
   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");
         });
      }
      
   }
   
   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);
      }

   }         
   
   function getStamp() {
      var stamp = new Date();
      return stamp.getTime();   
   }
   
   return {
      config : {},
      currentSlide : '',
      firstSlide : '',
      lastSlide : '',
      player : '', //this is only for the sucky ie

      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();
      },
      
      getPlayer : function() {
         return VOLI.player;
      },
      
      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
      *   @bstrType (string) The injection point type, @bstrParam (string) The name given to the injection point
      */
      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
      */
      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");
      },
      
      /***
      Thank you Dustin Diaz for these cookie functions
      ***/
      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 ) );
      },
   
      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' : '' );
      },
   
      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';
      }
            
   };
   
}();
