var $j = jQuery;
var api_key = 'f2cd69d2f227d11c';
var the_data = null;
var videos = {};
var $container;


$j(document).ready(function() {
   $container = $j('#vp_videos_container');
   // var tags = parseSID().join(',');
   //var tags = parseSID().join('-') + "%2B";
   //var tags = parseSID().join('-') + "%2B";
   var tags = videosjs_varOriginalPart.toLowerCase();
   if (tags.lastIndexOf("%2B") < 0) {
      tags += "%2B";
   }

   fetchVideos(tags, function(_data) {
      var data = _data[1];
      var videos = data.results;

      if (data.total == 0) return;

      // Listing page or item page?
      if (document.location.href.match(/viewitem\.aspx|item\.html/i) || (videosjs_viewtype && videosjs_viewtype == "item")) {
         var video = videos[0];

         // Insert the node in the main horizontal thumbnail strip
         var node = createThumbnail(video);
         $j('#divlargerView_thumbs').prepend(node);

         // Put the video into the left thumbnail strip in the lightbox
         var $thumbnail_container = $j('#divLargerImage_ImageBox > div:eq(0)');
         var left_node = $j(
        '<div style="margin-bottom:3px;width:70px;float:left;margin-right:3px;">\
         <a href="#">\
         <img src="' + video.thumbnail + '" height="70" width="70" border="0"></a>\
         </div>');
         left_node.click(function() {
            return showVideo(video);
         })
         $thumbnail_container.prepend(left_node);

         // Handle click to display lightbox
         $j('a', node).click(function() {
            return showVideo(video);
         })

      } else if (document.location.href.match(/listing\.aspx|listing\.html/i) || (videosjs_viewtype && videosjs_viewtype == "listing")) {
         // Handle Listing Page

         // If videos were fetched, show the container
         if (data.total > 0) {
            $container.show();
         }

         $j(data.results).each(function(i, video) {
            // Create a video
            $container.append(createThumbnail(video));
         });

         // Give the last video no right margin
         $j('.vp_video:last', $container).css({ marginRight: 0 });
      }

      if (VIDEOS_JS_blnResizeSnippetDescription) {
         $container = $j('#vp_videos_container');
         var minHeight = $container.height() + 50;
         $('.cart_fullDescription').css("min-height", minHeight + "px");
      }
   });

   ShowImage = function(strImageName) {
      var imageInBox = document.getElementById('divLargerImage_ImageBox_Image');
      imageInBox.style.display = '';
      imageInBox.src = "/storeimages/600x600/" + strImageName;

      // Hide the embed
      $j(imageInBox).siblings('iframe').remove();

      ToggleLargerImageBox(true);
   };
});

function showVideo(video) {
  var $img_wrapper = $j('#divLargerImage_ImageBox > div:eq(1) > div:eq(0)');
  // Hide the image
  $j('img', $img_wrapper).hide();
  // Delete an existing iframe
  $j('iframe', $img_wrapper).remove();
  // Draw the embed
  $img_wrapper.append(video.autoplay_embed);

  //Add video title to window
  $('#divLargerImage_ImageBox_ProductTitle').text(cleanupTitle(video));
  
  
  ToggleLargerImageBox(true);
  
  return false;
}

function parseSID() {
  var m = document.location.href.toLowerCase().match("[ps]id=(.+)");

  if (m) {
     return m[1].split('&')[0].split('-');
  } else {
    return [];
  }
}

function fetchVideos(tags, callback) {
   var url = 'http://api.vodpod.com/v2/my/videos.jsonp?api_key=f2cd69d2f227d11c&tags=' + tags + '&tag_mode=all&per_page=5&callback=?';
  var data = null;
  
  $j.getJSON(url, callback);
}

function createThumbnail(video) {
  var node = $j('<div class="vp_video" video_id="' + video.key + '">\
                 <a href="#"><img src="' + video.thumbnail + '" width="100" height="75" class="thumb"/><img src="/i/video-play.png" class="play"/></a>\
                 <a href="#" class="vp_video_title">' + cleanupTitle(video) + '</a>\
                 </div>');
  
  // Handle click to display lightbox
  $j('a', node).click(function() {
   return showVideo(video);
  })
                            
  // $j('a', node).click(function() {
  //   var $vp_embed = $j('#vp_embed', $container);
  //   
  //   $vp_embed.html(video.autoplay_embed);
  //   $vp_embed.animate({height: 300});
  //   
  //   return false;
  // });
  
  return node;
}

function cleanupTitle(video) {
  // Strip red truck/leland branding from video title
  var title = video.title;
  title = title.replace(/ - Leland Fly Fishing Outfitters$/i, '');
  title = title.replace(/ - Red Truck Fly Fishing$/i, '');
  
  return title;
}


// $('#divLargerImage_ImageBox > div:eq(1) > div > img').size()
