/*global $, jQuery, document, window, setTimeout, setInterval, clearInterval, google, swfobject */
var OPTIC = OPTIC || {};

OPTIC.VIEWPORT = window;
OPTIC.title = document.title;
OPTIC.hash = window.location.hash.substring(2);
OPTIC.LOCATION = '';

OPTIC.NAV = 'header.primary nav ul a'; 
OPTIC.scrollStatus = false;

OPTIC.pageSelector = '#page';
OPTIC.sectionSelector = '#page > article > section';
OPTIC.sectionFade = 0;

OPTIC.twitter_api_url = 'http://search.twitter.com/search.json';
OPTIC.twitter_user = 'opticnervetv';

OPTIC.videoPath = '/assets/includes/json_videos.php';
OPTIC.players = [];
OPTIC.playerPlaying = false; 
OPTIC.currentPlayer = '';

// Helper Methods
//////////////////////////////////////////////////////////////////////////////
OPTIC.fetchInfo = function(query, request, arr) {
  var info, obj;
  for (var i = 0, len = arr.length; i < len; i++) {
    for (obj in arr[i]) {
      if (arr[i].title === query) {
        info = arr[i][request];
        break;
      }
    }
  }
  return info;
};

OPTIC.loadSection = function (section) {
  var $section = $('#' + section.toLowerCase());
  if ((OPTIC[section].loadStatus === true) || (OPTIC.scrollStatus)) {
    return false;
  } else {
    OPTIC[section].loadStatus = true;
    OPTIC[section].build();
    $section.removeClass('loading');
  }
}; 

// Global Init
//////////////////////////////////////////////////////////////////////////////
OPTIC.initialize = function() {
  // Viewport
  OPTIC.updateViewport();
  
  $.ajaxSetup({ cache: true });
  
  
  $(this.VIEWPORT)
  .bind('resize', this.onViewportResize)
  .bind('scroll', this.onViewportScroll)
  .bind('scroll', function () {
    var section = OPTIC.LOCATION.toUpperCase();
    OPTIC.loadSection(section);
  })
  .one('load', function(){
    $('body').removeClass('loading');
    OPTIC.updateViewport();
  });

  // Navigation
  $(this.NAV).bind('click', this.onNavClick);
  $('a[href='+ this.HOME.selector +']').bind('click', function() {
    OPTIC.goHome();
    return false;
  });
  
  // Are we requesting a section ?
  if ((this.hash.length) && (this.hash != 'home')) {
    var section = this.hash.split('/').slice(0)[0]

    OPTIC.LOCATION = section;

    OPTIC.navToggle($('li').has('a[href=#'+ section +']'), 'open');

    $('#latest').hide();

    $(this.VIEWPORT).one('load', function () {
      OPTIC.loadSection(section.toUpperCase());
    });
  
  
  } else {
    OPTIC.LOCATION = 'home';
    OPTIC.HOME.latestTimeout = 8000;
    $('#latest').show();
    $(this.VIEWPORT)
    .one('load', function(){
      OPTIC.loadSection('HOME');
    });
  }
  
  // External Links
  $('a[rel*=external]').live('click', function(){
    window.open(this.href);
    return false;
  });

  // Overlabel
  if($.support.placeholder === false) {
    $('input.text, textarea').each(function() {
       if($(this).attr('placeholder') !== '') {
         var text = $(this).attr('placeholder'),
             id = $(this).attr('id');
         $(this).before('<label for="'+id+'">'+text+'</label>');
         $(this).parent().find('label').overlabel();  
       }
    });
  }

  // Studio Lightboxes
  $('#studio .slideBlock a').fancybox({
    padding: 0,
    titleShow: false,
    overlayColor: '#000' 
  });
    
};

// Video Player
//////////////////////////////////////////////////////////////////////////////
var Player = function(elem, vid_id, swf_id, vidY, vidX, autoplay) {
  this.elem = elem;
  this.vid_id = vid_id;
  this.swf_id = swf_id;
  this.vidY = vidY;
  this.vidX = vidX;
  this.autoplay = autoplay;
  var that = this;
  that.build();
};

function vimeo_player_loaded(swf_id) {
  var _player = document.getElementById(swf_id);
  _player.api_addEventListener('onPlay', 'vimeo_on_play');
  _player.api_addEventListener('onPause', 'vimeo_on_pause');
}
function vimeo_player_loaded_auto(swf_id) {
  var _player = document.getElementById(swf_id);
  OPTIC.playerPlaying = true;
  OPTIC.currentPlayer = swf_id;
  _player.api_setVolume(80);
  _player.api_play();
}
function vimeo_on_play(swf_id) {
  var _player = document.getElementById(swf_id);
  OPTIC.playerPlaying = true;
  OPTIC.currentPlayer = swf_id;
  _player.api_setVolume(80);
}

function vimeo_on_pause() {
  OPTIC.playerPlaying = false;
}

Player.prototype.play = function() {
  var _player = document.getElementById(this.swf_id);
  
  if(_player) {
    OPTIC.playerPlaying = true;
    _player.api_play();
    
  }

};

Player.prototype.pause = function () {
  var _player = document.getElementById(this.swf_id);
  if(_player) {
    OPTIC.playerPlaying = false;
    _player.api_pause();
  }
};

Player.prototype.stop = function() {
  var _player = document.getElementById(this.swf_id);
  if(_player) {
    OPTIC.playerPlaying = false;
    _player.api_seekTo(0);
    _player.api_pause();
  }
};

Player.prototype.setVol = function(level) {
  var _player = document.getElementById(this.swf_id);
  if(_player) {
    _player.api_setVolume(level);
  }
};

/*
Player.prototype.fadeVol = function() {
  var _player = document.getElementById(this.swf_id),
      start = 80;
  if(_player) {
    var timer = start,
        fade = setInterval(function(){
           timer = timer-1;
           // console.log(timer); 
           
           // _player.api_setVolume(vol) 
        }, 100); 
    // if(timer <= 0) {
    //    alert('done')
    // }  
    // _player.api_setVolume(level)
  }
}; */


Player.prototype.destroy = function() {
  // $('#'+this.swf_id).remove();   
  for (var i = 0, len = OPTIC.players.length; i < len; i++) {
    if (OPTIC.players[i].swf_id === this.swf_id) {
      OPTIC.players.remove(i);
      break;
    }
  }
  OPTIC.playerPlaying = false;
};

Player.prototype.build = function() {
  var loadFn = (this.autoplay === true) ? 'vimeo_player_loaded_auto' : 'vimeo_player_loaded',
      flashvars = {
        clip_id : this.vid_id,
        server : 'vimeo.com',
        color : '#019fff',
        show_title : 0,
        show_byline : 0,
        show_portrait : 0,
        fullscreen : 1,
        js_api : 1,
        js_onLoad : loadFn,
        js_swf_id:  this.swf_id
      }, 
      params = {
        'allowscriptaccess': 'always',
        'allowfullscreen': true,
        'wmode' : 'transparent'
      },
      attributes = {
        'id' : this.swf_id,
        'bgcolor' : '#000000'
      };

  swfobject.embedSWF("http://www.vimeo.com/moogaloop.swf", this.elem, this.vidY, this.vidX, "9.0.28", '', flashvars, params, attributes);
  OPTIC.players.push(this);
  OPTIC.currentPlayer = this.swf_id;
};

// Latest Tweet
//////////////////////////////////////////////////////////////////////////////
OPTIC.getLatest = function() {
  $.getJSON(OPTIC.twitter_api_url + '?callback=?&rpp=1&q=from:' + OPTIC.twitter_user, function(data) {
      $.each(data.results, function(i, tweet) {
        if(tweet.text !== undefined) {
          var date_tweet = new Date(tweet.created_at),
              date_now = new Date(),
              date_diff = date_now - date_tweet,
              hours = Math.round(date_diff/(1000 * 60 * 60)),
              exp_url = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
              text = tweet.text.replace(exp_url,'<a href="$1" rel="external">$1</a>'),
              html = '<p>' + text + '</p><span class="time">' + hours + ' hours ago</span>';
          
          $('#latest')
            .find('.loadstatus')
            .remove()
          .end()
            .find('.inner')
            .append(html)
          .end()
          .show();
        
        } else {
          
          $('#latest, .latest').hide();
        
        }
        return false;
    });
  });   
};

// Viewport Functions
//////////////////////////////////////////////////////////////////////////////

// Resize
OPTIC.onViewportResize = function() {
  OPTIC.updateViewport();
};

// Scroll
OPTIC.onViewportScroll = function() {
  var location = $(OPTIC.sectionSelector + ':in-viewport').attr('id'),
      playerPlaying = OPTIC.playerPlaying;
  
  if(location) {
    
    OPTIC.LOCATION = location;

    OPTIC.updateLocation('#' + location);
    
    // Pause The Slideshow
    OPTIC.cycle.stop();
    
    // Pause the player
    if(playerPlaying) { 
      if($('#'+OPTIC.currentPlayer+':above-the-top').length || $('#'+OPTIC.currentPlayer+':below-the-fold').length) {
        for(var i = 0, len = OPTIC.players.length; i < len; i++) {
          if (OPTIC.players[i].elem === OPTIC.currentPlayer) {
            // OPTIC.players[i].fadeVol();
            OPTIC.players[i].pause(); 
          }
        }
      }
    }

  } else { // Momma im coming home 
    
    OPTIC.resetLocation();
    // Restart The Slideshow where we left off
    var start = $('.slide:visible').index();
    OPTIC.cycle.start(OPTIC.HOME.slideSelector, OPTIC.HOME.slideSelector+' .slide', start,  3000);
  }

};

// Get Dimensions
OPTIC.getViewport = function() {
  return {
    x : $(this.VIEWPORT).width(),
    y : $(this.VIEWPORT).height()
  };
};

// Update Dimensions
OPTIC.updateViewport = function() {
  this.sizeHome();
  this.sizeSection();
  if(OPTIC.LOCATION && $('#'+OPTIC.LOCATION).length) {
    this.goToSection('#'+OPTIC.LOCATION, 0, 0);
  }
};

// Home Slideshow
OPTIC.sizeHome = function() {
  $(this.HOME.selector + ', ' + this.HOME.slideSelector).css({
    height : this.getViewport().y,
    width : this.getViewport().x
  });
  $(this.HOME.slideSelector+' > .slide').css({
    height : this.getViewport().y,
    width : this.getViewport().x
  });
  $(this.pageSelector).css({
    paddingTop : this.getViewport().y
  });
  
  // Size Slideshow
  this.fullBg(this.HOME.slideSelector+' > .slide img');  
};

// Background
OPTIC.fullBg = function(img) {
  var bg = {}, win = {}, ratio = {}, diff = {};
  bg.elem = $(img);

  return (function() {
    bg.x      = bg.elem.width();
    bg.y      = bg.elem.height();
    win.x     = OPTIC.getViewport().x;
    win.y     = OPTIC.getViewport().y;
    ratio.x   = win.x / bg.x;
    ratio.y   = win.y / bg.y;
    diff.x    = ratio.y * bg.x;
    diff.y    = ratio.x * bg.y;
    
    if (diff.y > win.y) {
      bg.elem.css({
        'height' : diff.y,
        'width' : win.x
      });
    } else {
      bg.elem.css({
        'height' : win.y,
        'width' : diff.x
      });
    }
  })(); 
};

// Cycler
//////////////////////////////////////////////////////////////////////////////
OPTIC.cycle = {};
OPTIC.cycleTimer = 0;
OPTIC.cycle.start = function(elem, slide, start, dur) {
  var i = start || 0,
      len = $(slide).length,
      switchSlide = function() {
        if(i == len) {
          i = 0;
        }
        $(slide+':eq('+ i +')').show().siblings().hide();
        i++;
      };

  switchSlide();
  return (function() { OPTIC.cycleTimer = setInterval(switchSlide, dur); })();
};

OPTIC.cycle.stop = function() {
  clearInterval(OPTIC.cycleTimer);
};

OPTIC.sizeSection = function() {
  for (var i = 0, len = $(this.sectionSelector).length; i < len; i++) {
    var section = $(this.sectionSelector+':eq('+ i +')');
    section.removeAttr('style');
    if (section.height() < this.getViewport().y) {
      section.height(this.getViewport().y); 
      
    }
  }
};

// Home Section
//////////////////////////////////////////////////////////////////////////////
OPTIC.HOME = {};
OPTIC.HOME.loadStatus = false;
OPTIC.HOME.selector = '#home';
OPTIC.HOME.slidePath = '/assets/includes/json_home.php';
OPTIC.HOME.slideSelector = '#slideShow';
OPTIC.HOME.slideFadeDur = 0;
OPTIC.HOME.latestTimeout = 0;
OPTIC.HOME.latestSpeed = 500;
OPTIC.HOME.build = function () {
  // Latest
  OPTIC.getLatest();
  setTimeout(function(){
    $('#latest').animate({
      'marginTop' : -367,
      'opacity' : 0
    }, OPTIC.HOME.latestSpeed, function(){
      $(this).show();
      $('a.latest').show();
    });
  }, OPTIC.HOME.latestTimeout);

  $('a.latest').click(function(){
    var latestTop = ($(this).hasClass('open')) ? -367 : 0,
        latestOpacity = ($(this).hasClass('open')) ? 0 : 1,
        toggleText = ($(this).hasClass('open')) ? 'The Latest' : 'Close';

    $(this).toggleClass('open').text(toggleText);

    $('#latest').animate({
      'marginTop' : latestTop,
      'opacity' : latestOpacity
    }, OPTIC.HOME.latestSpeed);
    return false;

  });
  
  // Home Slideshow 
  $(OPTIC.HOME.slideSelector).css('visibility', 'visible').animate({
    'opacity' : 1
  }, OPTIC.HOME.slideFadeDur, function () {
    $.getJSON(OPTIC.HOME.slidePath, function(data){
      for(var i = 0, len = data.length; i < len; i++) {
        $(OPTIC.HOME.slideSelector).append('<div class="slide"><img src="'+ data[i] +'" alt="" /></div>');
      }

      $(OPTIC.HOME.slideSelector).find('img:not(:first)').css('visibility', 'hidden');

      // Wait for last to load and Start Slideshow
      $(OPTIC.HOME.slideSelector).find('img:last').one('load', function(){
        $(OPTIC.HOME.slideSelector).find('img:not(:first)').css('visibility', 'visible');
        OPTIC.updateViewport();
        OPTIC.cycle.start(OPTIC.HOME.slideSelector, OPTIC.HOME.slideSelector+' .slide', 0, 3000);                  
      });
    });
  });
};

// Reel Section
//////////////////////////////////////////////////////////////////////////////
OPTIC.REEL = {};
OPTIC.REEL.loadStatus = false;
OPTIC.REEL.vim_id = 0;
OPTIC.REEL.build = function () {
  var opticReel;
  opticReel = new Player('opticReel', OPTIC.REEL.vim_id, 'opticReel', 800, 450, false);
};


// New Section
//////////////////////////////////////////////////////////////////////////////
OPTIC.NEW = {};
OPTIC.NEW.loadStatus = false;
OPTIC.NEW.gridSelector = '#newGrid';
OPTIC.NEW.data = [];
OPTIC.NEW.player = {};
OPTIC.NEW.build = function() {
  var grid = OPTIC.NEW.gridSelector,
      $grid = $(grid),
      dropHeight = $('#new .optdrop ul').outerHeight(),
      dropDur = (!$.support.htmlSerialize) ? 0 : 250;

  // handle i.e.
  if (!$.support.htmlSerialize) {
    $grid.find('>div .info').css('background', 'url(/assets/img/blueTranny.png)');
  }
  
  // Pornhoverz
  $('> div', $grid).pornhoverz({
    datapath : '/assets/includes/json_pornhoverz.php',
    datatype : 'json',
    image : 'img',
    timeout : 500
  });
  
  // Fetch Our Data
  $.getJSON(OPTIC.videoPath+'?type=new', function (data) {
    OPTIC.NEW.data = data;
  });
  
  // Grid Clicks Adds Video
  $grid.find('>div:not(.now-playing)').live('click', function () {
    OPTIC.NEW.addPlayer(this);
    return false;
  });
  
  // Grid Clicks Adds Video
  $grid.find('>div').bind('mouseover', function(){
    $(this).find('.info').show();
  });

  // Hoverz
  $grid.find('>div').hover(function(){
    // $(this).find('.info').show();
    $(this).find('.info .inner').stop().animate({
      'marginLeft' : 0
    }, 250);
  }, function(){
     $(this).find('.info .inner').stop().animate({
      'marginLeft' : 200
    }, 250, function(){
      $(this).css('marginLeft', -200).parent().stop().fadeTo(150, 0, function () {
        $(this).css('opacity', 1).hide();
      });
    });
  });

  // Dropdown Selector
  $('#new .optdrop ul').css({
    'marginTop': -dropHeight
  });
  
  $('#new .optdrop .selected').click(function () {
    if($(this).hasClass('open')) {
      $(this).removeClass('open');
      $('#new .optdrop ul').stop().animate({
        'marginTop': -dropHeight
      }, dropDur);
    } else {
      $(this).addClass('open');
      $('#new .optdrop ul').stop().animate({
        'marginTop': 0
      }, dropDur); 
    }
    return false;
  });
  
  // Filter Clicks
  $('#new .optdrop ul a').live('click', function () {
    if(!$(this).parent().hasClass('current')) {
      OPTIC.NEW.filter(this);     
    }
    return false;   
  });

};
OPTIC.NEW.addPlayer = function(elem) {
  var query   = $(elem).find('img').attr('alt'),
      vim_id  = OPTIC.fetchInfo(query, 'vim_id', OPTIC.NEW.data),
      title   = OPTIC.fetchInfo(query, 'title', OPTIC.NEW.data),
      client  = OPTIC.fetchInfo(query, 'client', OPTIC.NEW.data),
      time    = OPTIC.fetchInfo(query, 'time', OPTIC.NEW.data),
      info    = OPTIC.fetchInfo(query, 'info', OPTIC.NEW.data),
      html    = '<div id="newPlayerOuter"><div id="newPlayer"></div></div><div id="newPlayerInfo"><h3>'+ title +'</h3> / <span class="client">'+ client +'</span> / <span class="time">'+ time +'</span><a href="#" class="close">Close</a></div><div id="newPlayerExtraInfo"></div>';
    
    if(!$(elem).hasClass('now-playing')) {
      $(elem)
      .addClass('now-playing')
        .siblings()
        .removeClass('now-playing');
      
      if(!$('#newPlayer').length) {
        $(OPTIC.NEW.gridSelector).before(html);
        OPTIC.sizeSection();
      } else {
        $('#newPlayerInfo h3').text(title);
        $('#newPlayerInfo .client').text(client);
        $('#newPlayerInfo .time').text(time);
      }

      if(info.length) {
        $('#newPlayerExtraInfo').show().html(info);
      } else {
        $('#newPlayerExtraInfo').hide().empty();
      }
      
      if(OPTIC.NEW.player.destroy) {
        OPTIC.NEW.player.destroy(); 
      }
      
      if ($('#new .optdrop .selected').hasClass('open')) {
        $('#new .optdrop .selected').trigger('click');
      }
      
      OPTIC.NEW.player = new Player('newPlayer', vim_id, 'newPlayer', 800, 450, true);
      
      OPTIC.goToSection('#new', 300, 0);
      
      $('#newPlayerInfo a.close').bind('click', function() {
         $('#newPlayerOuter, #newPlayerInfo, #newPlayerExtraInfo').remove();
         OPTIC.NEW.player.destroy();
         OPTIC.goToSection('#new', 300, 0);
         return false;
      });
       
    }   
};
OPTIC.NEW.sizeDrop = function(elem) {
  var height = $(elem).outerHeight();
  $(elem).css({
    'marginTop': -height
  });
};
OPTIC.NEW.filter = function(elem) {
  var category = $(elem).attr('class'),
      title = $(elem).text();
  
  $(elem)
  .parent()
  .addClass('current')
    .siblings()
      .removeClass('current'); 
  
      if(category === 'all') {
        $('#new .optdrop .selected').html('Sort By &hellip;');

        $(OPTIC.NEW.gridSelector)
          .find('>div')
          .css('opacity', 1);
      } else {
        $('#new .optdrop .selected').text(title);

        $(OPTIC.NEW.gridSelector)
          .find('>div:not(.'+ category +')')
          .css('opacity', 0.5)
        .end()
          .find('>div.'+ category)
          .css('opacity', 1); 

      }
  $('#new .optdrop .selected').trigger('click');
  
  OPTIC.sizeSection();
};

// Archive 
//////////////////////////////////////////////////////////////////////////////
OPTIC.ARCHIVE = {};
OPTIC.ARCHIVE.loadStatus = false;
OPTIC.ARCHIVE.tableSelector = '#archiveTable';
OPTIC.ARCHIVE.data = [];
OPTIC.ARCHIVE.player = {};
OPTIC.ARCHIVE.build = function() {
  var table = OPTIC.ARCHIVE.tableSelector,
      row = 'tbody tr:not(.player)';
  
  // handle i.e.
  if (!$.support.htmlSerialize) { 
    $(table).attr('cellspacing', 0);
    $('#ARCHIVE.tableSelector tbody tr:odd').css('background', '#EEE');
  }  
  
  $(table).tablesorter();
/*
  
  $(table).find('thead th').click(function(){
    if($(this).hasClass('end')) {
      if($(this).hasClass('headerSortDown')) { 
        $(this).find('span').text('+/-');
      } else {
        $(this).find('span').text('-/+');
      }
    } else {
      if($(this).hasClass('headerSortDown')) { 
        $(this).find('span').text('b/a');
      } else {
        $(this).find('span').text('a/b');
      }
    }
    $(table).find('tbody tr.now-playing').trigger('click');
  });
      */

  $(table).find(row).live('click', function(){
    OPTIC.ARCHIVE.addPlayer(this);
    return false;
  });

  $(table).find(row).hover(function() {
     if(!$(this).hasClass('now-playing')) {
       $(this).addClass('hover');
     }
  }, function() {
     $(this).removeClass('hover');
  });
  
  
  
  // Lets Fetch our data and store it
  $.getJSON(OPTIC.videoPath+'?type=archive', function(data){
    OPTIC.ARCHIVE.data = data;
    $(table).find(row).bind('mouseover', OPTIC.ARCHIVE.addThumb);
    // OPTIC.ARCHIVE.addThumbs();
  });
  
  $('.tableToggle').click(function(){
    
    $(this).toggleClass('thumb');
    $(table).toggleClass('thumb');
    
    if($(table).hasClass('thumb')) {
      $(table).find('thead th.end').text('Thumbs');  
    } else {
      $(table).find('thead th.end').text('Length');  
    }
    
    OPTIC.sizeSection();
  
    return false;
  
  });
  
  $('.tableToggle').bind('click', OPTIC.ARCHIVE.addThumbs);
  
  
  // Genre Select
  dropHeight = $('#archive .optdrop ul').outerHeight(),
  dropDur = (!$.support.htmlSerialize) ? 0 : 250;
  
  $('#archive .optdrop ul').css({
    'marginTop': -dropHeight
  });
  
  $('#archive .optdrop .selected').click(function () {
    if($(this).hasClass('open')) {
      $(this).removeClass('open');
      $('#archive .optdrop ul').stop().animate({
        'marginTop': -dropHeight
      }, dropDur);
    } else {
      $(this).addClass('open');
      $('#archive .optdrop ul').stop().animate({
        'marginTop': 0
      }, dropDur); 
    }
    return false;
  });
  
  
  // Filter by Genre
  $('#archive .optdrop ul a').live('click', function () {

    var selectId = $(this).attr("class");
    var j=1;
    var title = $(this).html();
    
    $('#archive .optdrop .selected').text(title);
    
    if(!$(this).parent().hasClass('current')) {
      
      $(this).parent().siblings().removeClass('current');
      $(this).parent().addClass('current');            
      
      $("#archiveTable tbody tr").each(function(){
      
        $(this).css("background", "#FFF");
  
        if(selectId=='all'){          
          j++;
          $(this).fadeIn();
          if(j%2==0){
            $(this).css("background", "#EEE");
          }        
        }      
        else{      
          var ids = $(this).attr("class").split("_");
          var show;
          for (var i=0, len=ids.length; i<len; ++i){
            if(ids[i] == selectId){
              show = true;
              break;
            }
            else{
              show = false;
            }
          }
          if(!show){
            $(this).fadeOut();
          }
          else{        
            j++;  
            if(j%2==0){
              $(this).css("background", "#EEE");
            }
            $(this).fadeIn();                    
          }      
        }
      });
    }
    return false;   
  });
  
};
OPTIC.ARCHIVE.addThumb = function () {
  var index = $(this).index(),
      thumb = OPTIC.ARCHIVE.data[index].thumb,
      $row =  $(OPTIC.ARCHIVE.tableSelector).find('tbody tr:eq('+ index +')')
      $placeholder = $('.thumbnail.placeholder', $row);
  
  if ($('tr.player').length) {
    var playerIndex = $('tr.player').index();
    if (playerIndex < index) {
      index = index - 1;
    }
  }
  
  if (thumb && $placeholder.length) {
    $placeholder.remove();
    $('td.end', $row).append('<span class="thumbnail loading"><img src="'+ thumb +'" alt="" width="101" /></span>');
    $('td.end .thumbnail img', $row).css('opacity', 0).bind('load', function () {
      $(this).animate({
        'opacity' : 1
      }, 300, function () {
         $(this).parent().removeClass('loading'); 
      });
    })       
  } else {
    $placeholder.show();
  }

  $(this).unbind('mouseover', OPTIC.ARCHIVE.addThumb);
};

OPTIC.ARCHIVE.addThumbs = function () {
  for (var i = 0, len = OPTIC.ARCHIVE.data.length; i < len; i++) {
    var index = i,
        thumb = OPTIC.ARCHIVE.data[index].thumb,
        $row =  $(OPTIC.ARCHIVE.tableSelector).find('tbody tr:eq('+ index +')'),
        $placeholder = $('.thumbnail.placeholder', $row);
    
    if ($('tr.player').length) {
      var playerIndex = $('tr.player').index();
      if (playerIndex < index) {
        index = index - 1;
      }
    } 
    // Add Thumbs
    if (thumb && $placeholder.length) {
      $placeholder.remove();
      $('td.end', $row).append('<span class="thumbnail loading"><img src="'+ thumb +'" alt="" height="60" /></span>');
      $('td.end .thumbnail.loading img', $row).css('opacity', 0).bind('load', function () {
        $(this).animate({
          'opacity' : 1
        }, 300, function () {
           $(this).parent().removeClass('loading'); 
        });
      });
    } else {
      $placeholder.show();
    }
    
    $row.unbind('mouseover', OPTIC.ARCHIVE.addThumb);
  }

  $(this).unbind('click', OPTIC.ARCHIVE.addThumbs);
};
OPTIC.ARCHIVE.getIndex = function(elem) {
  var index = $(elem).index();
  if ($('tr.player').length) {
    if ($(elem).index() > $('tr.player').index()) {
      index = $(elem).index() - 1;
    }
  }
  return index;
};
OPTIC.ARCHIVE.addPlayer = function (elem) {
  var html = '',
      query = $(elem).find('td:eq(2)').text(),
      vim_id = OPTIC.fetchInfo(query, 'vim_id', OPTIC.ARCHIVE.data);

  html += '<tr class="player">';
  html += '<td class="player" colspan="5">';
  html += '<div id="archivePlayer"></div>';
  html += '</td>';
  html += '</tr>';

  if (!$(elem).hasClass('now-playing')) {
    $(elem)
    .removeClass('hover')
    .addClass('now-playing')
      .siblings()
      .removeClass('now-playing')
        .filter('.player')
        .remove()
      .end()
    .end()
    .after(html);
    
    OPTIC.goToSection('tr.player', 300, 130);
    
    OPTIC.sizeSection(); // update the sections incase of bumpdown 
    
    if (OPTIC.ARCHIVE.player.destroy) {
      OPTIC.ARCHIVE.player.destroy(); 
    }
    
    OPTIC.ARCHIVE.player = new Player('archivePlayer', vim_id, 'archivePlayer', 800, 450, true);
    // OPTIC.ARCHIVE.player.play();
  } else {
    OPTIC.ARCHIVE.removePlayer(elem);
  }
};
OPTIC.ARCHIVE.removePlayer = function(elem) {
  $(elem).removeClass('now-playing').next().remove();
  OPTIC.ARCHIVE.player.destroy();
  OPTIC.sizeSection();
};

// Spotlight Section
//////////////////////////////////////////////////////////////////////////////
OPTIC.SPOTLIGHT = {};
OPTIC.SPOTLIGHT.loadStatus = false;
OPTIC.SPOTLIGHT.vim_id = 0;
OPTIC.SPOTLIGHT.build = function () {
  var opticSpotlight;
  opticSpotlight = new Player('opticSpotlight', OPTIC.SPOTLIGHT.vim_id, 'opticSpotlight', 800, 450, false);
};

// About Section
//////////////////////////////////////////////////////////////////////////////
OPTIC.ABOUT = {};
OPTIC.ABOUT.loadStatus = false;
OPTIC.ABOUT.addSlides = function (data) {
  for(var i = 0, len = data.length; i < len; i++) {
    $('#about .slideshow').append('<img src="'+ data[i] +'" height="450" width="800" alt="" />');
  }
  $('#about .slideshow img:last').one('load', function(){
    if(jQuery.fn.cycle) {
      $('#about .slideshow').cycle({
          fx: 'fade'
      });
    }
  });
};
OPTIC.ABOUT.build = function () {
  $.getJSON('/assets/includes/json_about.php', function(data){
    OPTIC.ABOUT.addSlides(data);
  });
};

// Studio Section
//////////////////////////////////////////////////////////////////////////////
OPTIC.STUDIO = {};
OPTIC.STUDIO.loadStatus = false;
OPTIC.STUDIO.addSlides = function (data) {
  for(var i = 0, len = data.length; i < len; i++) {
    for(var j = 0, imageLen = data[i].images.length; j < imageLen; j++) {
      $('#studio .slideBlock:eq('+ i +')').append('<img src="'+ data[i].images[j] +'" alt="" height="'+ data[i].dimensions[0] +'" width="'+ data[i].dimensions[1] +'" />');
    }
  }
  $('#studio .slideBlock img:last').one('load', function(){
    if(jQuery.fn.cycle) {
      $('#studio .slideBlock').cycle({
          fx: 'fade',
          timeoutFn: function() {
            return Math.floor(1000 + Math.random()*10000);
          }
      });
    }
  });
};
OPTIC.STUDIO.build = function () {
  $.getJSON('/assets/includes/json_studio.php', function(data){
    OPTIC.STUDIO.addSlides(data);
  });
};

// Contact
//////////////////////////////////////////////////////////////////////////////
OPTIC.CONTACT = {};
OPTIC.CONTACT.loadStatus = false;
OPTIC.CONTACT.map = {};
OPTIC.CONTACT.map.elem = 'map';
OPTIC.CONTACT.map.lat = 0;
OPTIC.CONTACT.map.lng = 0;
OPTIC.CONTACT.map.build = function(elem) {
  var _latlng = new google.maps.LatLng(OPTIC.CONTACT.map.lat, OPTIC.CONTACT.map.lng),
      opts = {
        zoom: 8,
        center: _latlng,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      },
      _map = new google.maps.Map(document.getElementById(elem), opts),
      marker = new google.maps.Marker({
          position: _latlng,
          map: _map
      }); 
};
OPTIC.CONTACT.ajaxSubmit = function (form) {
  var data = $(form).serialize(),
      url = $(form).attr('action');

  $(form).css('opacity', 0.5);
  $('#contactForm h3').html('sending &hellip;');

  $.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: 'html',
    success: function(data) {
      $('#contactForm h3').text('thank you!');
      $(form).css('opacity', 1);
      $(form).find('input.text, textarea').val('').blur();
    }
  });
  return false;
};

OPTIC.CONTACT.build = function () {
  
  // Validate Contact Form
  $('#contactForm form').validate({submitHandler : OPTIC.CONTACT.ajaxSubmit });
  
  OPTIC.CONTACT.map.build(OPTIC.CONTACT.map.elem);
};

// Navigation
//////////////////////////////////////////////////////////////////////////////
OPTIC.onNavClick = function() {
  var $this = $(this),
      $li = $this.parent(),
      href = $this.attr('href'),
      section = href.substr(1).toUpperCase();

  if ($li.has('ul').length) { // Top Level Nav
    OPTIC.navToggle($li, 'open'); 
  } else { // Children of Top level
    
    
    OPTIC.loadSection(section);
    OPTIC.scrollStatus = true;
    
    $li.parent().parent().siblings().addClass('bypass');
    
    OPTIC.goToSection(href, 500, 0, function(){
      $li.parent().parent().siblings().removeClass('bypass');
      $(OPTIC.NAV+'[href='+ href +']').addClass('current');
      OPTIC.scrollStatus = false;
    });
    
  }
  return false;
};

OPTIC.navToggle = function(elem, className) {
  if (!elem.hasClass(className)) {
    elem.addClass(className).siblings().removeClass(className);
  }
};

OPTIC.navHighlight = function(location) {
  var $navPar = $(OPTIC.NAV+'[href='+ location +']').parent().parent().parent();
  
  $(OPTIC.NAV+'[href='+ location +']')
  .addClass('current')
    .parents('nav')
      .find(':not([href='+ location +'])')
      .removeClass('current');
  if(!$navPar.hasClass('open')) {
    $navPar
    .not('.bypass')
    .addClass('open')
      .siblings()
      .removeClass('open');    
  }
};
OPTIC.navReset = function() {
  $(OPTIC.NAV).removeClass('current').parents('.primary nav').find('.open').removeClass('open'); 
};

// Site Scrolling
OPTIC.goToSection = function(target, dur, padding, callback) {
  var offset = $(target).offset();
  
  $('html, body').addClass('scrolling').animate({
    'scrollTop' : offset.top - padding
  }, dur, callback);

  setTimeout(function(){
    $('html, body').removeClass('scrolling');
  }, dur);
  return false;
};

OPTIC.goHome = function() {
  $(OPTIC.NAV).parent().addClass('bypass');
  this.goToSection('#home', 500, 0, function(){
    OPTIC.resetLocation();
    $(OPTIC.NAV).parent().removeClass('bypass');
    $(OPTIC.ARCHIVE.tableSelector).find('tbody tr.now-playing').trigger('click');
  }); 
};

// Locations
//////////////////////////////////////////////////////////////////////////////
OPTIC.setHash = function(hash) {
  window.location.hash = '/'+hash;
};

OPTIC.setTitle = function(title) {
  var _title = (title !== undefined) ? document.title = OPTIC.title+' | '+title.capitalize() : false;
  return _title;
};

// Location
OPTIC.updateLocation = function(location) {
  this.setHash(location.substring(1));
  this.setTitle(location.substring(1));
  this.navHighlight(location);
};

OPTIC.resetLocation = function() {
  this.navReset();
  this.hash = '';
  this.LOCATION = 'home';
  this.updateLocation(OPTIC.HOME.selector);
};

// Utilities
//////////////////////////////////////////////////////////////////////////////

// Capitalize
String.prototype.capitalize = function(){
 return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

// placeholder support
(function() {
  var i = document.createElement('input');
  jQuery.support.placeholder = 'placeholder' in i;
})(); 

(function($) {
  // Porn Hoverz
  $.fn.pornhoverz = function(options) { 
      var defaults = {
            image : 'img',
            datapath : 'pornhover.php',
            datatype : 'json',
            timeout : 100
          }, 
          opts = $.extend({}, defaults, options),
          $this = $(this),
          _dataStack = [],
          _imageStack = [],
          cycleTimer;
    
      // Request our data
      $.ajax({
        url : opts.datapath,
        dataType : opts.datatype,
        success : function(data) {
          $.fn.pornhoverz.dataPush(data);
          $.fn.pornhoverz.ready();
        }
      });
    
      // Ready
      $.fn.pornhoverz.ready = function() {
        // Bind Our Hovers
        $this.hover(function(){
          var index = $.fn.pornhoverz.getIndex(this),
              len = _dataStack[index].images.length;
          if(len > 1) {
            $.fn.pornhoverz.cycleStart(this, index, 1); 
          }
        }, function() {
          $.fn.pornhoverz.cycleStop(this, $.fn.pornhoverz.getIndex(this), 1);
        });
      };
    
      // Data Pusher
      $.fn.pornhoverz.dataPush = function(data) {
        for(var i = 0, len = data.length; i < len; i++) {
          // Store our data for later
          _dataStack.push(data[i]);
          // Extract The Images
          for(var j = 0, imageLen = data[i].images.length; j < imageLen; j++) {
            _imageStack.push(data[i].images[j]);
          }
        }
      
        // Preload The Images
        // for(var i = 0, len = _imageStack.length; i < len; i++) {
        //   _imageStack[i] = new Image();
        //   _imageStack[i].src = _imageStack[i];
        // }
      };
    
      // Index Utility
      $.fn.pornhoverz.getIndex = function(elem) {
        var index = $(elem).index();
        return index;
      };
    
      // Cycle Start
      $.fn.pornhoverz.cycleStart = function(elem, index, start) {
        var dur = opts.timeout,
            i = start || 0,
            len = _dataStack[index].images.length,
            switchSrc = function() {
              if(i == len) {
                i = 0;
              }
              $(elem).find(opts.image).attr('src', _dataStack[index].images[i]);
              i++;
            };
        
        switchSrc();
        
        return (function(){ cycleTimer = setInterval(switchSrc, dur); })();
      };
    
      // Cycle Stop
      $.fn.pornhoverz.cycleStop = function(elem, index) {
        $(elem).find(opts.image).attr('src', _dataStack[index].images[0]);
        return clearInterval(cycleTimer); 
      };
    
      return this; 
  };
})(jQuery);
