var TRACKED_SLIDESHOW = false;

$(document).ready(function() {
  
  var dlgSizeLg = { width: 820, height: 760 };
  var dlgSizeSm = { width: 820, height: 704 };
  
  var openDialog = function (large) {
    var size = large ? dlgSizeLg : dlgSizeSm;
    lightbox.dialog('option', 'height', size.height)
      .dialog('option', 'width', size.width)
      .dialog('open');
  };
  var resetDialog = function () {
    // stop any currently running slideshow timer
    $(document).stopTime("slideshow-refresh"); 
    // clear out content, this helps ie6 as it will keep the old flash
    // instances sticking around otherwise
    $('#lightbox_content_container').html('');   
  };
  
  // set up the light box
  var lightbox = $('#dialog');
  lightbox.dialog({ 
      autoOpen: false, 
      bgiframe: true, 
	  zIndex: 5000,
      width: dlgSizeLg.width,
      height: dlgSizeLg.height, 
      modal: true,
      open: function(e) {
        if($.browser.msie && $.browser.version == "6.0")
          $('.expected_weather form .styled').hide();
      },
      beforeclose: function (e) {
        resetDialog();
        if($.browser.msie && $.browser.version == "6.0")
          $('.expected_weather form .styled').show();
        $.address.value('');
      }
    }).find('a.close').click(function() {
      lightbox.dialog('close');
		  return false;
	  });

  // collect a list of potential deep-link widgets
  var legitTabIds = [];
  $('.lightbox_container .lightbox_header ul.navigation li').each(function (index, content) { 
    if (content.className != '')
      legitTabIds.push(content.className) 
  });
  // for the non-featured destination page, we have no lightbox tabbed navigation
  if (legitTabIds.length == 0)
    legitTabIds.push('map');
  var legitDetailIds = [];
  $('ul.left_nav li').each(function (index, entry) { 
    legitDetailIds.push(entry.id); 
  });
  
  // PNG FIX
  $('.dropped').pngfix();
  
  // NON-FEATURED SLIDESHOW

  var slideImages = $('ul.slideshow_pics li img');
  var lastSlideImage = 0;
  var updateSlideImage = function (image) {
    $('.destination_slideshow .slideshow_indicator span').html((image+1)+' / '+(slideImages.length));
    if (image != lastSlideImage) {
      $('.destination_slideshow').hide()
          .css('background', 'url('+slideImages[image].src+') no-repeat center center')
        .fadeIn('fast');
      lastSlideImage = image;
    }
  };
  $('.destination_slideshow a').css('outline', 'none');
  $('.destination_slideshow a.next').click(function (e) {
    updateSlideImage((lastSlideImage + 1) % slideImages.length);
    return false;
  });  
  $('.destination_slideshow a.previous').click(function (e) {
    updateSlideImage((lastSlideImage || slideImages.length) - 1);
    return false;
  });
  if (slideImages.length > 0)
    updateSlideImage(lastSlideImage);

  // NON-FEATURED AT-A-GLANCE 

  var glancePages = $('.at_a_glance .feed div').hide();
  var lastGlancePage = 0;
  var updateGlance = function (page) {
    $(glancePages[lastGlancePage]).hide();
    $(glancePages[page]).fadeIn('fast');
    lastGlancePage = page;

    var spacer = $('.at_a_glance .controls span');
    
    var btnPrev = $('.at_a_glance .controls a.previous');
    if (page == 0) { btnPrev.hide(); } else { btnPrev.show(); }

    var btnNext = $('.at_a_glance .controls a.next');
    if (page == glancePages.length-1) { btnNext.hide(); } else { btnNext.show(); }
    
    if (page == 0 || page == glancePages.length-1) {
      spacer.hide();
    } else {
      spacer.show();
    }
  };
  $('.at_a_glance .controls a.next').click(function (e) {
    updateGlance((lastGlancePage + 1) % glancePages.length);
    return false;
  });
  $('.at_a_glance .controls a.previous').click(function (e) {
    updateGlance((lastGlancePage || glancePages.length) - 1);
    return false;
  });
  if (glancePages.length > 0) {
    updateGlance(lastGlancePage);    
  }
  if (glancePages.length == 1) $('.at_a_glance .controls').hide();  
  
  // JQUERY ADDRESS
  
  // set up deep links for the lightbox tabs, featured destination 
  // widgets, detail info tabs and non-featured destination map lightbox
  $('.lightbox_container .lightbox_header ul.navigation li a, '
    +'.featured_destinations .featured_widget a, '
    +'ul.left_nav li a, a#overview-map, '
    +'#lightbox_content_container .slideshow-image a').address();
  
  // init deep linking
  var dispatcher = function(e) {
    // calling reset dialog on each access so we have an opportunity
    // to clean things up on navigation change.
    resetDialog();
    
    if (e.pathNames.length > 0) { 
      var loc = e.pathNames[0];
      var disptached = false;

      var has_video = function(str) {
        return str == "video";
      }

      var has_slideshow = function(str) {
        return str == "photo";
      }
      
      var has_pdf_viewer = function(str) {
        return str.match(/(tour|itineraries|map)/) != null;
      }
      
      var selectable = function(str) {
        return str.match(/(video|map|photo|tours|itineraries)/) != null;
      }

      var clear_selections = function() {
        var container = $('.lightbox_container');
        $('.detail_map .thumbnail,'
          +'.overview_map .thumbnail,'
          +'.video .thumbnail,'
          +'.photo .thumbnail,'
          + '.tours ul li a,'
          + '.itineraries ul li a', container).removeClass('selected');        
      }
      
      var set_selection = function(action, param) {
        if (action == 'maps') {         
          $('.lightbox_container .' + param + '_map .thumbnail').addClass('selected');
        }
        else if (action == 'video') {
          $('.lightbox_container li.video div.thumbnail').addClass('selected');
        }
        else if (action == 'photo') {
          $('#photo-thumb-'+param).addClass('selected');
        }
        else if (action == 'tours') {
          $(".lightbox_header .tours a[rel*='address:/"+action+"/"+param+"']").addClass('selected');
        }
        else if (action == 'itineraries') {
          $(".lightbox_header .itineraries a[rel*='address:/"+action+"']").addClass('selected');
        }
      }
      
      var data_for = function(address) {
        return $.map($(".lightbox_header a[rel*='address:/" + address + "']").slice(1),
          function(el) {
            return {
              title:    $(el).attr('title'),
              filename: $(el).attr('href')
            }
          }
        );
      }

      // are we looking for lightbox content?
      for (var i = 0; i < legitTabIds.length; i++) {
        if (legitTabIds[i] == loc) {
          if (e.pathNames[1] != 'static') {
            selectLightboxContent(e.pathNames);

            clear_selections();

            if (selectable(loc)) {
              set_selection.apply(this, e.pathNames);
            }

            if (has_pdf_viewer(loc)) 
            {
              var el = $(".lightbox_header a[rel*='address:/" + e.pathNames.join('/') + "']");
              var title = el.attr('title');
              var trackableTitle = $.prepareOmnitureText(title);
              var filename  = el.attr('href');
              var add_to_planner = $('span.add.'+e.pathNames.join('.')).html();
              showViewer(title, filename, add_to_planner);

              if (e.pathNames[0] == 'tours')
                $.omnitureTracking('WalkingTours', trackableTitle);
              else if (e.pathNames[0] == 'maps')
                $.omnitureTracking(((e.pathNames[1] == 'overview') ? 'OverviewMap' : 'DetailMap'));
              else if (e.pathNames[0] == 'itineraries')
                $.omnitureTracking('Itineraries');
            }
            else if (has_video(loc))
            {
              showVideo(data_for(loc), e.pathNames[2] || "0");
              $.omnitureTracking('VideoInsights');
            }
            else if (has_slideshow(loc)) 
            {
              showSlideshow(data_for(loc), Number(e.pathNames[1])-1, e.pathNames.length >= 3 && e.pathNames[2] == 'auto');

              if (!TRACKED_SLIDESHOW) {
                $.omnitureTracking('PhotoGallery');
                TRACKED_SLIDESHOW = true;
              }
            }
            
          } else {
            openDialog(false);
          }
          disptached = true;
        }
      }
      if (!disptached) {
        // are we looking for detail content?
        for (var i = 0; i < legitDetailIds.length; i++) {
          if (legitDetailIds[i] == loc+'-tab') {
            selectDetailContent(e.pathNames);
            dispatched = true;
          }
        }        
      }
    }
  };
  $.address.change(dispatcher);
  
  // HANDLERS //

  // toggle and select for 
  var currentLightboxContentId = 'video';
  var selectLightboxContent = function (path) {
    openDialog(true);
    if (currentLightboxContentId != null && currentLightboxContentId != path[0]) {
      var target = $('.lightbox_container .lightbox_header');
      if (target.hasClass(currentLightboxContentId))
        target.removeClass(currentLightboxContentId);
      target.addClass(path[0]);
      currentLightboxContentId = path[0];
    }
  };
  var showVideo = function(data, duration) {
    $('div#lightbox_content_container').html('<div class="lightbox_content"><h1 class="title">'+(data[0].title || 'Video Insights')+'</h1></div><div class="lightbox_media"><div id="VideoPlayer"></div></div>');
    swfobject.embedSWF(
      "/swf/VideoPlayer.swf", 
      "VideoPlayer", 
      "800", "600",
      "9.0.0",
      null,
      { 
        title:    data[0].title,
        filename: data[0].filename,
        duration: duration
      },
      null,
      null
    );
  };
  var loadedImages = {};
  var preloadImage = function (filename) {
    if (!loadedImages[filename]) {
      var loadImage = new Image();
      loadImage.src = filename;
      loadedImages[filename] = true;      
    }
  };
  var showSlideshow = function(data, starting_index, automatic) {
    var previous_index = (starting_index <= 0 ? (data.length-1) : (starting_index-1));
    var next_index = (starting_index >= (data.length-1) ? 0 : (starting_index+1));
    $('div#lightbox_content_container')
      .html($('<p/>').append(data[starting_index].title))
        .append($('<div/>')
          .attr('class', 'slideshow-image')
          .css('background', 'url('+data[starting_index].filename+') no-repeat top center')
            .append('<a href="'+data[previous_index].filename+'" rel="address:/photo/'+(previous_index+1)+'" class="previous"><span class="slideshow dropped"></span></a>')
            .append('<a href="'+data[next_index].filename+'" rel="address:/photo/'+(next_index+1)+'" class="next"><span class="slideshow dropped"></span></a>')
            .append('<br class="clear"/>'))
      .hide().fadeIn('fast');
    $('div#lightbox_content_container .slideshow-image a').address();
    $('.slideshow.dropped').pngfix();
    // if this is an automatic slideshow, lets keep it going
    if (automatic) {
      $(document).oneTime(12000, "slideshow-refresh", function () {
        $.address.value("/photo/"+(next_index+1)+"/auto");
      });
    }
    preloadImage(data[next_index].filename);
  }
  var showViewer = function(title, filename, add_to_planner) {
    $.pdf_viewer = $('div#lightbox_content_container').pdf_viewer(
      title, filename, add_to_planner);
  };
  
  // set the default tab, this cannot be hardcoded like the lightbox because
  // we cannot be sure which tab will be present/be the first
  var currentDetailContentId = null;
  if ($('ul.left_nav li').length > 0) {
    currentDetailContentId = $('ul.left_nav li')[0].id.replace('-tab', '');
    $('#'+currentDetailContentId).show();
    $('#'+currentDetailContentId+'-tab').addClass('selected');    
  }
  
  var omnitureNav = {
    'introduction' : 'Introduction',
    'essential-info' : 'EssentialInfo',
    'local-voices' : 'LocalVoices',
    'poi' : 'POI',
    'see' : 'See',
    'eat' : 'Eat',
    'sleep' : 'Sleep',
    'night' : 'Night',
    'shop' : 'Shop',
    'events' : 'Events',
    'activities' : 'Activities',
    'fast-facts' : 'FastFacts',
    'money' : 'Money',
    'transport' : 'Transport'
    }
  var selectDetailContent = function (path) {
    if (currentDetailContentId != path[0]) {
      if (currentDetailContentId != null)
        $('#'+currentDetailContentId).hide();
      $('#'+path[0]).slideDown('fast');
      
      if (currentDetailContentId != null)
        $('#'+currentDetailContentId+'-tab').removeClass('selected');
      $('#'+path[0]+'-tab').addClass('selected');
      
      // Scroll to content, but only if we've scrolled down past it.
      var scrollTo = $('#'+path[0]).position().top - 10;
      if (window.pageYOffset > scrollTo)
          window.scrollTo(0, scrollTo);
          
      currentDetailContentId = path[0];
      var navName = omnitureNav[currentDetailContentId] || currentDetailContentId;
      ctn_rmaction('US:Travel:DestinationGuideNav:'+navName,'click>'+DESTINATION_TITLE);
    }
  };
  $('.addall').click(function (e) {
    ctn_rmaction('US:Travel:MyPlanner:All','add>'+DESTINATION_TITLE);
    return false;
  });  
  $('.add').click(function (e) {
    // Grab the Omniture id from the enclosing div class.
    var navId = $(e.target).closest('div[id]')[0].id;
    var navName = omnitureNav[navId] || navId;
    ctn_rmaction('US:Travel:MyPlanner:'+navName,'add>'+DESTINATION_TITLE);
    return false;
  });  
  
});

