/* BASEHREF **/
/* ------------------------------------------------------------------------ */
var baseHref = (function() {
  var baseHref = document.getElementsByTagName('a')[0].href;
  baseHref = baseHref.substr(0,(baseHref.length-1));
  return baseHref; // http://foobar.com  (notice no trailing slash)
})();
var baseSecureHref = (baseHref.indexOf('localhost') > -1) ? baseHref : baseHref.replace("http:", "https:");

/* Horrible Browser Detection **/
/* ------------------------------------------------------------------------ */
if($.browser.webkit) {
  $('html').addClass('webkit');
} else if($.browser.mozilla) {
  $('html').addClass('mozilla');
} else if($.browser.msie && $.browser.version < 8) {
  $('html').addClass('msie');
}
if(navigator.userAgent.match(/iPad/i)) {
  $('html').addClass('ipad');
}



/* Default Variables **/
/* ----------------------------------------------------------------------- */
var windowW = $(window).width()-300;
var windowH = $(window).height()+160;
var documentH = $(document).height();
var scrollPos = 0;

var offset = 0;
var page = 0;
var loading = 0;

var galY = 0;
var galX = 0;

var formFocus = 0;

var animSpeed = 0;



/* Functions **/
/* ------------------------------------------------------------------------ */

/** Set cookies and prefs **/
function setPref(name,val,days) {
	preferences[name] = val;
	$.post(baseHref + '/account/setPreference', { key: name, value: val });
}
function setCookie(name,val,days) {
	if(days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = '; expires=' + date.toGMTString();
	} else {
		var expires = '';
	}
	document.cookie = name + '=' + val + expires + '; path=/';
}
function readCookie(name) {
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return 0;
}

/** Convert seconds to HMS and back **/
function secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);
    return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s);
}
function hmsToSeconds(time) {
    time = time.toString();
    return (parseInt(time.split(':')[0]*60)+parseInt(time.split(':')[1]));
}

/** Change page title on blur **/
if(readPref('workfriendly')) {
  var pageTitle = $('title').text();
  $(window).blur(function() {
    $('title').html('SV');
  });
  $(window).focus(function() {
    $('title').text(pageTitle);
  });
}

/** Alert box toggle and hide **/
function alertToggle() {
  if(!$('body.browse, body.album').length) {
    setTimeout(function() {
      $('blockquote.alert').not('.end').fadeOut(700,function(){
        $('blockquote.alert').not('.end').remove();
      });
    },7500)
    $('blockquote.alert').not('.end').click(function() {
      $(this).fadeOut(700,function(){
        $(this).remove();
      });
    });
  }
}

/** modal login **/
function modalLogin() {
  window.scrollTo(0,0);
  $('body').addClass('lightbox');
  var local = document.location.toString().split(baseHref).pop();
    // 1. Make screen
    $('<div/>')
        .attr('id','screen')
        .attr('title','Click to close')
        .click(function() {
            $('#screen, #modal').remove();
            $('body').removeClass('lightbox')
        })
        .appendTo($('body'));
    // 2. Make modal login box
    $('<div/>')
        .attr('id','modal')
        .addClass('login')
        .html('<form name="loginform" method="post" action="' + baseSecureHref + '/session/submitLogin"><input type="hidden" name="location" value="' + local + '" /> <table id="loginmodal" cellspacing="0" cellpadding="0"><tr valign="top"><th class="joiner"><h4>New to SkinVideo?</h4></th><th class="joiner"><h4>Member login:</h4></th></tr><tr valign="top"><td class="joiner"><div class="features"> <ul> <li>DVD quality <b>WMV</b>, <b>H.264</b>, <b>Flash</b> and <b>MP4</b> file formats</li> <li><b>40,000+</b> videos&mdash;<b>Over 6,000</b> hours of video!</li> <li><b>100,000+</b> photos!</b></li> <li>Top Studios, Behind the Scenes, and Amateur Video</li> <li>Hourly Updates</li> <li><b>No DRM!</b></li> </ul></div></td><td><label>Username: <input class="inputbox" type="text" tabindex="40" name="username" value=""/></label> <label>Password: <span class="forgot">(<a href="' + baseSecureHref + '/support/accountFinder">Forgot your password?</a>)</span> <input class="inputbox" type="password" tabindex="41" name="password" value=""/></label></td></tr><tr><th class="joiner"><a href="' + baseSecureHref + '/join" id="joinBannerPop">Join Now!</a></th><th><input type="submit" name="loginbutton" value="Login" class="submit" tabindex="42" /></th></tr></table><a href="#" id="modalClose" onclick="$(\'#screen, #modal\').remove(); $(\'body\').removeClass(\'lightbox\'); return false;" title="Click to close">x</></form>')
        .appendTo($('body'));
}

/** Hover Menu **/
function hoverMenu(obj) {
  if($('body.guest').length || readPref('hovermenu') || ($(obj).is('.noHover'))) {
    return false;
  }

  if ($(obj).find("div.piemenu").length > 0) {
    return;
  }

  var url = $(obj).find('a').slice(0,1).attr('href');

  var watchUrl = url.split('watch/');
  if (watchUrl.length > 1) {
    var videoID = watchUrl[1].split('/')[0];
    var source = $(obj).find('div.info a:last').attr('href');

    $(obj).append('<div class="piemenu"><ul><li class="fav"><a href="'
        + url + '" title="' + videoID + '">Add Favorite</a></li> <li class="playlist"><a href="'
        + url + '" title="' + videoID + '">Add to Playlist</a></li> <li class="download"><a href="'
        + source + '">Download</a></li> <li class="info"><a href="' + url
        + '">Info</a></li> <li class="popout"><a href="' + url + '" onclick="newwindow=window.open(\''
        + url + '#pop\',\'pop\',\'location=1,status=1,scrollbars=0,width=452,height=300\'); return false;" target="pop">Play in new window</a></a></ul></div><a href="#" class="close" onclick="$(\'.thumb.playlist, .thumb.download, .thumb.info\').removeClass(\'playlist download info\'); return false;">x</a>');

    // Add fav
    $(obj).find('div.piemenu .fav a').click(function() {
      var obj = $(this);
      var videoID = $(obj).attr('title');

      var favurl = baseHref + '/favorite/' + videoID;
      if($(obj).parents('.thumb').is('.favorite')) {
          favurl = favurl + '?_method=delete';
      }

      $.post(favurl, function() {
        $(obj).parents('.thumb').toggleClass('favorite')
      });

      return false;
    }).mouseover(function() {
      $('.thumb').removeClass('info');
    });

    // Add to playlist
    $(obj).find('div.piemenu .playlist a').click(function() {
      var obj = $(this);
      var thumb = $(this).parents('.thumb')
      var videoID = $(obj).attr('title');

      $(thumb).addClass('playlist');
      $('.thumb.playlist').not(thumb).removeClass('playlist download info');

      $('#form_playlist').clone(true).addClass('open').appendTo($(thumb));
      if(!$('#form_playlist .list').length) {
        $('#form_playlist').addClass('newplaylist');
        $('#form_playlist .newlist input').focus();
      }
      $(thumb).find('input.submit').val('Add video');

      return false;
    }).mouseover(function() {
      $('.thumb').removeClass('info');
    });

    // Download video
    $(obj).find('div.piemenu .download a, div.piemenu .popout a').click(function() {
      /**var obj = $(this);
      var thumb = $(this).parents('.thumb')
      var videoID = $(obj).attr('title');
      var url = $(thumb).find('a').slice(0,1).attr('href');

      $(thumb).addClass('download');
      $('.thumb.download').not(thumb).removeClass('playlist download info');

      if(!$(thumb).find('.downloadwrap').length) {
        $('<div/>')
          .addClass('downloadwrap')
          .load(url + ' #download a')
          .appendTo($(thumb));
      }

      return false;**/
    }).mouseover(function() {
      $('.thumb').removeClass('info');
    });

    // Show info
    $(obj).find('div.piemenu .info a').mouseover(function() {
      var obj = $(this);
      var thumb = $(this).parents('.thumb')
      var videoID = $(obj).attr('title');
      var url = $(thumb).find('a').slice(0,1).attr('href');

      $(thumb).addClass('info');
      $('.thumb.info').not(thumb).removeClass('playlist download info');

      return false;
    });
    }
}


/** Photo lightboxer **/
function lightboxer(photo) {
  scrollTo(0, 1);
  $('#form_playlist, #lightbox a.playlist').removeClass('open newplaylist');
  // 0. Get vars
  var downloadURL = $(photo).attr('href');
  var opus = $(photo).find('img').attr('alt');

  var obj = $('.thumbs img[alt=' + opus + ']').slice(0,1).parent('a');//$(".thumbs a[href='" + downloadURL + "']:first");
  //alert($(obj).length);

  var authorLink = '';
  if($(obj).parent().find('span.author').length) {
    authorLink = '<span class="author">' + $(obj).parent().find('span.author').html() + '</span>';
  }

  if($('body.usenetPhotos, body.album, body.playlist, body.favorites').length) {
    downloadURL = $(obj).find('img').attr('longdesc');
  }

  $(obj).addClass('selected');
  $('.thumbs a.selected').not(obj).removeClass('selected');

  var thumbURL = $(obj).find('img').attr('src');
  if($('body.photos, body.usenetPhotos').length) {
    var bigURL = $(obj).attr('href');//thumbURL;
  } else {
    var bigURL = $(obj).attr('href');//thumbURL.substr(0,(thumbURL.length-4)) + '-b' + thumbURL.substr(-4); // hack
  }
  var photoID = $(obj).find('img').attr('alt');
  var isFav = ($(obj).is('.isfav'))?' isfav':'';
  var favText = ($(obj).is('.isfav'))?'Add Favorite':'Remove Favorite';
  var prev = $('.thumbs a.selected').prev('a');
  var next = $('.thumbs a.selected').next('a');
  if($('body.photos, body.usenetPhotos, body.search, body.front').length) {
    prev = $('.thumbs a.selected').parents('div.thumb').prev().find('a.img');
    next = $('.thumbs a.selected').parents('div.thumb').next().find('a.img');
  }
  if($('body.usenetPhotos').length && !$(next).length && $('.top a.next').length) {
    next = $('.top a.next').attr('href',$('.top a.next').attr('href')+'#lb0');
  }
  if($('body.usenetPhotos').length && !$(prev).length && $('.top a.prev').length) {
    prev = $('.top a.prev').attr('href',$('.top a.prev').attr('href')+'#lb1');
  }

  // 1. Check if body is primed
  if(!$('body.lightbox').length) {
    $('body').addClass('lightbox');
    $('body').append('<div id="lightbox"></div>');
  }

  $('#lightbox').html('<div class="wrap"><u class="close" title="Click to close" onclick="$(\'body\').removeClass(\'lightbox\'); $(\'#lightbox\').remove(); return false;">x</u> <a href="#" onclick="$(\'#lightbox a.next\').click(); return false;" style="background-image: url(\'' + thumbURL + '\');" class="big"><img src="' + bigURL + '" /></a><a href="' + baseHref + '/favorite/' + photoID + '" class="addfav'+isFav+'" onclick="var obj = $(this); favurl = $(this).attr(\'href\'); if($(this).is(\'.isfav\')) { favurl += \'?_method=delete\' } $.post(favurl, function(data) { $(obj).toggleClass(\'isfav\'); $(\'img[alt=' + photoID + ']\').parent(\'a\').toggleClass(\'isfav\'); $(\'body.photos img[alt=' + photoID + ']\').parents(\'span\').remove() }); return false;">&hearts;</a> <a href="#" class="playlist" onclick="/**if(!$(\'#form_playlist\').length) { $(\'#form_playlist\').clone(\'true\').appendTo($(\'#lightbox .wrap\')); }**/ $(\'#form_playlist, #lightbox a.playlist\').toggleClass(\'open\'); if(!$(\'#form_playlist .list\').length) { $(\'#form_playlist\').addClass(\'newplaylist\'); $(\'#form_playlist .newlist input\').focus(); } return false;">+</a> <a href="' + downloadURL + '" class="download">Download</a>' + authorLink + '</div>');
  $(prev).clone(true).addClass('prev').appendTo($('#lightbox .wrap'));
  $(next).clone(true).addClass('next').appendTo($('#lightbox .wrap'));
  return false;
}


/* BEGIN DOCUMENT READY **/
/* ------------------------------------------------------------------------ */
//$(document).ready(function() {
/* ------------------------------------------------------------------------ */



/* body.* Stuff for all pages **/
/* ------------------------------------------------------------------------ */

/** Hide alerts on click/timeout **/
if($('blockquote.alert').length) {
  alertToggle();
}

/** Category drop **/
$('#menu a.catdrop').bind('click mouseover', function() {
  var menuItem = $(this).parent();
  var menuClass = $(menuItem).find('a:first').attr('href').split('/').pop();
  
  if($(menuItem).is('.open')) {
    //$(menuItem).removeClass('open');
  } else {
    $(menuItem).addClass('open');
  }

  $('#menu .open').not($(menuItem)).removeClass('open');
  
  if(!$(menuItem).find('div.listing').length) {
    $('#categories div.listing').clone(true).appendTo($(menuItem));
    $(menuItem).find('div.listing a').each(function() {
      $(this).attr('href',$(this).attr('href').replace(/all/,menuClass));
    });
  }
  
  $('<div id="cathide"/>')
    .appendTo($('body'))
    .bind('mousemove',function() {
      $(this).remove();
      $(document).trigger('resize');
    });
  
  return false;
});
$('#usermenu, #menu a.t').bind('mouseover',function() {
  if(!$(this).parent('.open').length) {
    $(document).trigger('resize');
  }
});

$('#content').click(function() {
  $('#menu .open').removeClass('open');
});
$(document).bind('resize scroll', function() {
  $('#menu .open, .videoMenu .open').removeClass('open');
});

/** Lock forms on submit **/
$('body.simple form, body.join form').submit(function(e) {
  $('form :input').attr('readonly','readonly').fadeTo('fast',.5);
  $('form :submit').attr('disabled','disabled').fadeTo('fast',.5);
});

/** Form focus 
$('input').focus(function() {
	formFocus = 1;
});
$('input').blur(function() {
	formFocus = 0;
});**/

/** Mobile site toggler **/
$('#footer li.userface').after('<li class="mobile"><a href="#" onclick="document.location=\'' + baseHref + '/?mobile=1\'; return false;">Mobile site</a></li>');

/** User drop menus **/
$('#menu .drop').bind('click', function() {
  $('#menu .open').not($(this).parent()).removeClass('open');
  $(this).parent().toggleClass('open');
  return false;
});
$('#menu .drop').bind('mouseover', function() {
  $('#menu .open').not($(this).parent()).removeClass('open');
  $(this).parent().toggleClass('open');
  
  $('<div id="cathide"/>')
    .appendTo($('body'))
    .bind('mousemove',function() {
      $(this).remove();
      $(document).trigger('resize');
    });
});


/** Guests need to login or signup **/
$('body.guest #form_playlist legend, body.guest #form_favorite, body.guest li.screenshots a, body.guest #download a, body.guest.album .thumbs.album a, body.album.guest h2 a, body.guest a.login').click(function() {
  modalLogin();
  return false;
});

if($('body.guest.browse .scenes').length) {
/** faux download link **/
    var joinLink = $('#userface a:first').attr('href');
    $('<a/>')
      .attr('href',joinLink)
      .addClass('download')
      .text('Download these videos now!')
      .appendTo($('.top h2'));
}

/** Dynamic tabs **/
if($('#lovelyTabs a.active').length < 1) {
  $('#lovelyTabs a').slice(0,1).addClass('active');
}
$('#content .tabbed').slice(1).hide();

$('#lovelyTabs a').click(function() {
  var target = $(this).attr('href');
  $(this).addClass('active')
  if (target.indexOf("#") == -1) {
    window.location = target;
  } else {
    $('#lovelyTabs a.active').not($(this)).removeClass('active');

    var linkAndFragment = target.split('#');

    if (document.location.href.indexOf(linkAndFragment[0]) > -1) {
      $('#' + linkAndFragment[1])
        .show()
        .siblings('.tabbed').hide();
    } else {
      document.location.href = target; 
    }
  }
});

var thisPage = window.document.location.toString();
if($('#lovelyTabs').length > 0 && thisPage.indexOf('#') > 0) {
  var target = $('#'+thisPage.split('#')[1]);
  if(target.size() > 0) {
    $('.tabbed').hide();
    target.show();
    // Show right tab
    $('#lovelyTabs li a').removeClass('active');
    var tabtarget = '#' + thisPage.split('#')[1] + '';
    $('#lovelyTabs li a[href=' + tabtarget + ']').addClass('active');
  }
}

/** Country toggle **/
$('#form_country').change(function() {
  var country = $(this).val();
  if(country == 'us') {
    $('#form_state').parent().parent().show();
    $('#form_province').parent().parent().hide();
  } else {
    $('#form_state').parent().parent().hide();
    $('#form_province').parent().parent().show();
  }
});
$('#form_country').change();



/* body.loggedin **/
/* ------------------------------------------------------------------------ */
if($('body.loggedin').length) {
/* ------------------------------------------------------------------------ */

/** Make sure photos are marked as favourites **/
$('body.favorites.photos .thumbs a').addClass('isfav');

/** Move and hide #form_playlist **/
$('body.album #form_playlist, body.usenetPhotos #form_playlist, body.usenetVideos #form_playlist, body.photos.favorites #form_playlist, body.photos.playlist #form_playlist, body.search #form_playlist, body.videos.favorites #form_playlist, body.videos.playlist #form_playlist, body.browse #form_playlist, body.search #form_playlist').appendTo($('body'));

/** Saved Searches **/
if($('.top h2').length) {
  var secTitle = $('.top h2').text();
  $('body.loggedin .top h2')
    .append(
      $('<a/>')
        .attr('href','#')
        .text('Save this search')
        .one('click', function() {
          $(this).html('<i>Saving...</i>');
          var bookmark = document.location.toString().replace(/&page=\d+/, '');
          bookmark += ((bookmark.indexOf("?") > -1) ? "&" : "?") + "page=1";

          $.post(baseHref + '/savedSearch',
            { url: bookmark, name: secTitle },
            function(searchID) {
              $('.savedSearches ul').append('<li class="fav videos"><a href="' + bookmark + '" title="' + searchID + '" class="ready">' + secTitle + '</a></li>');
              $('.top h2 a').html('<i>Saved!</i>');
              setTimeout(function() {
                  $('.top h2 a').fadeOut('fast');
                  $('<a />')
                    .addClass('delete')
                    .attr('href','#')
                    .attr('title','Click to delete this search')
                    .text('x')
                    .insertAfter($('.savedSearches ul li.ready'))
                    .click(function() {
                      var delVid = confirm('Are you sure you want to remove this?');
                      if(delVid) {
                        var url = $(this).attr('title');
                        var ref = $(this).parent();
                        $.post(baseHref + '/savedSearch/' + searchID + '/?_method=delete', function(data) {
                            $(ref).hide('fast',function() { $(ref).remove(); });
                        });
                      } else {
                        //$('#progress').remove();
                      }
                      return false;
                    });
              },1500);
            }
          );

          return false;
        })
    );
}

$('.savedSearches li a').each(function() {
  var searchID = $(this).attr('title');
  $('<a />')
    .addClass('delete')
    .attr('href','#')
    .attr('title','Click to delete this search')
    .text('x')
    .insertAfter($(this))
    .click(function() {
      var delVid = confirm('Are you sure you want to remove this?');
      if(delVid) {
        var url = $(this).attr('title');
        var ref = $(this).parent();
        $.post(baseHref + '/savedSearch/' + searchID + '/?_method=delete', function(data) {
            $(ref).hide('fast',function() { $(ref).remove(); });
        });
      } else {
        //$('#progress').remove();
      }
      return false;
    });
});


/** Add Favorite **/
$('#form_favorite').click(function() {
  // 0. Get values
  var val = $('#fav').val();
  var videoID = $('h2:first').attr('title');
  
  // 1. Set loading...
  $('#form_favorite label').addClass('loading').html('<input type="radio" name="listid" value="fav" id="fav" disabled="disabled"> Processing...');

  //add fav
  var favurl = baseHref + '/favorite/' + videoID;// + '&format=js';
  var isfav = 0;
  if($('body').is('.favorite') || $("#playlists input#fav").text() == 'Remove Favorite') {
      favurl = favurl + '?_method=delete';
      isfav = 1;
  }

  $.post(favurl, function(data) {
      $('body').toggleClass('favorite');
      if(!isfav) {
          $('#form_favorite label').html('<input type="radio" name="listid" value="fav" id="fav" disabled="disabled"> Added Favorite!');
          setTimeout(function() {
              $('#form_favorite label').addClass('isfav').removeClass('loading').html('<input type="radio" name="listid" value="fav" id="fav"> Remove Favorite');
          },1500);
      } else {
          $('#form_favorite label').removeClass('isfav').html('<input type="radio" name="listid" value="fav" id="fav" disabled="disabled"> Removed Favorite!');
          setTimeout(function() {
              $('#form_favorite label').removeClass('loading').html('<input type="radio" name="listid" value="fav" id="fav"> Add Favorite');
          },1500);
      }
  });
    
});

/** Add to playlist **/
$('#form_playlist legend').click(function() {
  $('.open').not('#form_playlist').removeClass('open');
  $('#form_playlist').toggleClass('open');
  $('video').toggleClass('hidden');
  if(!$("#form_playlist input[name='listid']").length) {
    $('#form_playlist').addClass('newplaylist');
    $('#form_playlist .newlist input').focus();
  }
});
$('#form_playlist label.newlist').click(function() {
  $('#form_playlist').addClass('newplaylist');
  $('#form_playlist .newlist input').focus();
});
$('body.loggedin li.download a:first').click(function() {
  $('.open').not($(this).parent()).removeClass('open');
  $(this).parent().toggleClass('open');
  return false;
});
$('body.loggedin li.screenshots a').click(function() {
  $('body').removeClass('share');
  $('.open').not($(this).parent()).not('#montage').removeClass('open');
  $(this).parent().toggleClass('open');
  $('#montage').toggleClass('open');
  
  flow.pause();
  
  return false;
});
$("#form_playlist")
    .bind('click', function(e) {
      var labelList = $(e.target).closest('label.list');
      if($(labelList).length) {
        // 0. Get values
        var val = $(labelList).find('input').eq(0).val();
        var videoID = $('h2:first').attr('title');
        if($('body.album').length) {
          videoID = $('.thumbs .selected img:first').attr('alt');
        }
        if(!videoID) {
          var url = $(labelList).parents('.thumb').find('a').slice(0,1).attr('href');
          videoID = url.split('watch/')[1].split('/')[0];
        }
        var parentForm = $(labelList).parents('form');

        // 1. set loading
        $(parentForm).removeClass('open').addClass('loading');
        $('video').removeClass('hidden');
        $(parentForm).find('legend span').html('Processing...');

        // 2. add to list
        $.post(baseHref + '/playlist/' + val + '/opus/' + videoID, function() {
          $(parentForm).find('legend span').html('Added!');
          setTimeout(function() {
            $(parentForm).removeClass('loading');
            $(parentForm).find('legend span').html('Add to playlist');
            $('#lightbox .open').removeClass('open');
            $('.thumb.playlist').removeClass('playlist');
          },1500);
        });
      }
    })
    .submit(function(e) {
      e.preventDefault();
      var obj = $(this);
      // 0. Get values
      if($(obj).find('.newlist input').val().length > 0) {
        playlistName = $(obj).find('.newlist input').val();
      } else {
        playlistName = 'New playlist';
      }
      var videoID = $('h2:first').attr('title');
      if($('.thumbs.album, .thumbs.photos').length) {
        videoID = $('.selected img').slice(0,1).attr('alt');
      }
      if($('.thumb.hover').length) {
        videoID = $('.thumb.hover .piemenu .fav a').slice(0,1).attr('title');
      }

      // 1. set loading
      $(obj).removeClass('open').addClass('loading');
      $('video').removeClass('hidden');
      $(obj).find('legend span').html('Processing...');

      $.ajax({
          type: 'POST',
          url:  baseHref + '/playlist?name=' + playlistName + '&opusId=' + videoID + '&format=js',
          success: function(newPlaylistID) {
            // Deselect radio buttons
            //$(obj).find(':radio').attr('checked', false);
            
            // Append new playlist to menu bars
            $(obj).find("div").prepend('<label class="list"><input type="radio" name="listid" value="' + newPlaylistID + '"> ' + playlistName + '</label>');
            if($('body.watch').length) {
              $("#userFavorites li.fav:eq(0)").after('<li class="p"><a href="' + baseHref + '/playlist/' + newPlaylistID + '">' + playlistName + '</a></li>');
            } else if($('body.model').length) {
              $("#userFavorites li.fav:eq(1)").after('<li class="p"><a href="' + baseHref + '/playlist/' + newPlaylistID + '">' + playlistName + '</a></li>');
            } else {
              $("#userFavorites").append('<li class="p"><a href="' + baseHref + '/playlist/' + newPlaylistID + '">' + playlistName + '</a></li>');
            }
            
            videoPlaylists[newPlaylistID] = playlistName;
            
            $(obj).find('legend span').addClass('hasPlaylists').html('Added!');
            
            setTimeout(function() {
              $(obj).find('.newlist input').val('');
              $(obj).removeClass('loading newplaylist');
              $(obj).find('legend span').html('Add to playlist');
              $('#lightbox .open').removeClass('open');
              $('.thumb.playlist').removeClass('playlist');
            },1500);
            
          }
        });
    });
    

/** AJAX comments **/
$('form#comment').submit(function(e) {
    // 0. Prevent default
    e.preventDefault();

    if($('body.guest').length) {
        modalLogin();
        return false;
    }

    // 1. Validate
    var url = $(this).attr('action');
    var bodyText = $(this).find('textarea').val();
    var thumbPreview = $(this).find('.thumbPreview input').val();
    if(thumbPreview) {
     bodyText += ' ['+thumbPreview+']';
    }
    var thisForm = $(this);

    // 2. Disable form, add status
    $(this).find('textarea,input').attr('disabled','disabled');
    $(this).find('input:submit').val('Processing...');

    // 3. Post comment
    $.post(url, { body: bodyText }, function(newCommentID) {
        // 3. Clear textarea
            if($(thisForm).is('#commentinline')) {
                var targetCommentID = $(thisForm).find("input[name='commentID']").val();
                if(!$('#comment' + targetCommentID).next('ol.commentTree').length) {
                    $('#comment' + targetCommentID)
                        .after('<ol class="commentTree"></ol>');
                }
                $(thisForm).slideUp('fast',function() { $(this).remove(); });
                var appendNode = $('#comment' + targetCommentID).next('ol.commentTree:first');
            } else {
                $(thisForm).find('textarea,input').removeAttr('disabled');
                $(thisForm).find('textarea').val('');
                $(thisForm).find('input:submit').val('Add Comment');
                if(!$('#comments ol.commentTree').length) {
                    $('#comments').prev('h3').find('a').text('1 Comment');
                    $('#comments').html('<ol class="commentTree"></ol>');
                }
                var appendNode = $('#comments ol.commentTree:first');
            }

        // 4. Append result
            $('<li/>')
                .attr('id','comment' + newCommentID)
                .addClass('comment')                
                .append('<a href="' + baseHref + '/user" class="usericon"><img src="' + $('#userface img.usericon').attr('src') + '" alt="me" /></a>')
                .append('<p><b>' + $('#userface legend b').text() + '</b> ' + bodyText + '</p>')
                .append('<ul class="footer"><li clss="datetime"><span title="Seriously, just this very moment.">just now</span></li><li class="delete"><a href="#" onclick="$(this).html(\'<i>Deleting...</i>\'); $.post(baseHref + \'/comment/' + newCommentID + '?_method=delete\', function() { $(\'#comment' + newCommentID + '\').slideUp(\'fast\'); }); return false;">Delete?</a></li></ul>')
                .hide()
                .prependTo($(appendNode));

        // 5. Scroll to comment
            //$(window).scrollTo($('#comments'));
            if($('#comments:hidden').length) {
              $('#comments')
                .slideDown('fast')
                .prev('h3')
                .removeClass('closed');
            }
            $('#comment' + newCommentID).slideDown('slow');

    });

    return false;
});

/** inline replies **/
$('#comments a.delete').click(function() {
  var newCommentID = $(this).nextAll('a').text();
  $(this).html('<i>Deleting...</i>');
  $.post(baseHref + '/comment/' + newCommentID + '?_method=delete', function() {
    $('#comment' + newCommentID).slideUp('fast');
  });
  return false;
});
$('#comments li.reply a').click(function() {
    $('#commentinline').remove();
    // 1. Get comment id
    var commentID = $(this).attr('title');
    var insertNode = $(this).parent().parent();

    // 2. clone comment form
    $('form#comment')
        .clone(true)
        .attr('id','commentinline')
        .attr('action', baseHref + '/comment/' + commentID)
        .append('<input type="hidden" name="commentID" value="' + commentID + '" />')
        .hide()
        .insertAfter($(insertNode));

    // 3. slide in
    $('#commentinline').slideDown('fast');
    $('#commentinline textarea').focus();
    //$(window).scrollTo($('#comment' + commentID));

    return false;
});

$('#comments p').each(function() {
    if($(this).text().indexOf('[') > 0) {
        var timestamp = $(this).text().match(/\[[0-9]+:[0-9]+\]/);
        
        var time = hmsToSeconds(timestamp.toString().substr(1,(timestamp.toString().length-2)));
        
        var fulltime = hmsToSeconds($('div.header span.time').text().split(' ')[4]);
        
        var montageNum = $('#links a').length;
        var thisThumb = Math.floor(time*montageNum/fulltime);
        var img = '<a href="#flow" class="thumbstamp" onclick="flow.seek(' + time + ');"><img src="' + $('#links a').eq(thisThumb).attr('href') + '" /></a>';
    
        $(this).html($(this).text().replace(timestamp, img));
    }
});



/* ------------------------------------------------------------------------ */
}
/* end body.loggedin */



/* thumbnails **/
/* ------------------------------------------------------------------------ */
if($('.thumbs.scenes').not('.usenet, .usenette').length) {
/* ------------------------------------------------------------------------ */

  function thumbHover(obj) {
      $(obj).addClass('hover');
      $('.thumb').not(obj).removeClass('playlist download info hover');
  }
  function thumbMouseover(obj) {
      var imgUrl = $(obj).find('img').attr('src');
      $(obj).parent().css({ backgroundImage: "url('" + imgUrl + "')"});
      $(obj).attr('style', $(obj).attr('longdesc'));
  }
  function thumbMousemove(obj, e) {
      $(obj).addClass('hover').removeClass('static');
      var offsetX = $(obj).offset().left;
      var mouseX = e.pageX;
      var thumbSize = (!$('.thumbs.list').length)?16:48;
      var thumbWidth = (!$(obj).hasClass('hdd'))?151:207;
      var backgroundPos = Math.floor((offsetX-mouseX)/thumbSize)*thumbWidth;
      $(obj).stop().css({backgroundPosition: backgroundPos + 'px 0px'}, 100);
  }

  var thumbs = $('.thumbs.scenes .thumb').not('.usenet, .usenette')
    .hover(function() {
        thumbHover($(this));
    },
    function() {
      $(this).removeClass('hover');
    });

  thumbs.one('mouseover', function() {
      hoverMenu(this);
    })
    .find('a.img')
    .one('mouseover',function() {
        thumbMouseover($(this));
    })
    .bind('mousemove',function(e) {
        thumbMousemove($(this), e);
    });

$('body.browse .thumbs.dvd .scenes a')
    .one('mouseover',function() {
      var imgUrl = $(this).find('img').attr('src');
      $(this).find('img').css('visibility','hidden');
      $(this).css({ backgroundImage: "url('" + imgUrl + "')"});
      $(this).attr('style', $(this).attr('longdesc'));
    })
    .bind('mousemove',function(e) {
      var offsetX = $(this).offset().left;
      var mouseX = e.pageX;
      var thumbSize = 16;
      var thumbWidth = 113;
      var backgroundPos = Math.floor((offsetX-mouseX)/thumbSize)*thumbWidth;
      $(this).stop().css({backgroundPosition: backgroundPos + 'px 0px'}, 100);
    });

/* ------------------------------------------------------------------------ */
}
/* end thumbnails */


/* Usenet thumbnails **/
/* ------------------------------------------------------------------------ */
if($('.thumb.usenet').length) {
/* ------------------------------------------------------------------------ */
$('.thumb.usenet a.img').unbind('mousemove');
$('body.usenetVideos .thumbs .thumb, body.watch.usenet .thumbs .thumb, body.search .thumbs.usenette.scenes .thumb, body.videos.favorites .thumbs .thumb.usenet, body.videos.playlist .thumbs .thumb.usenet').hover(function() {
    var img = $(this).find('img');
    var src = img.attr('src');
    var anim = img.attr('longdesc');
    
    $(this).addClass('hover');
    $('.thumb').not(this).removeClass('playlist download info hover');

    img.attr('src',anim).attr('longdesc',src);
  },
  function() {
    var img = $(this).find('img');
    var src = img.attr('src');
    var anim = img.attr('longdesc');

    $(this).removeClass('hover');

    img.attr('src',anim).attr('longdesc',src);

  }).one('mouseover', function() {
    hoverMenu(this);
  });
/* ------------------------------------------------------------------------ */
}
/* end usenet thumbnails */


/* body.browse **/
/* ------------------------------------------------------------------------ */
if($('body.browse').length) {
/* ------------------------------------------------------------------------ */

/** Floating filter **/
var gallery = $('.thumbs.scenes, .thumbs.dvd').not('.usenette');
if(gallery.length > 0) {
    // 1. Calculate gallery size
    $(window).resize(function() {
      windowW = $(window).width()-300;
      windowH = $(window).height()+160;
      documentH = $(document).height();
      scrollPos = $(window).scrollTop();

      galY = $(gallery).offset().top;
      galX = $(gallery).offset().left;
    });
    $(window).scroll(function(e) {
      $(window).resize();
      // Check positions of things
      if($('#filter').is('.sticky')) {
        return;
      }
      if(scrollPos > (galY-14)) {
        $('#filter')
          .addClass('floating')
          .css({
            position: 'fixed',
            top: '6px',
            left: (galX-188) + 'px'
          });
        $('#search_term').slideDown('fast');
      } else {
        $('#filter')
          .removeClass('floating')
          .css({
            position: 'absolute',
            top: '0',
            left: '-188px'
          });
        $('#search_term').hide();
      }
    });
}

/** Filter list toggle **/
$('#filter .list h3').click(function() {
  $('#filter .open').removeClass('open');
  $(this).next('ul, #advanced').addClass('open');
  var sec = $(this).text();
  setPref('filterMenu', sec, 14);
});
var sec = (readPref('filterMenu'))? readPref('filterMenu') :'Popular';
$("#filter .list h3:contains('" + sec + "')").next('ul, #advanced').addClass('open');


/** Filter menu **/
if(!$('#filter .open, .superfilter').length) {
  $('#filter h3 a:first').addClass('open');
}
$('#filter').after(
  $('<a/>')
    .text('Toggle')
    .attr('href','#top')
    .attr('id','hideFilter')
    .click(function() {
      $('html').toggleClass('hideFilter');
      preferences['hideFilter'] = ($('html').is('.hideFilter'))?'1':'0';
      setPref('hideFilter',preferences['hideFilter'],14);
      return false;
    })
);

/* Tag filters */
$('#filters_tags').bind('click', function(e) {
  var required = $(e.target).closest('label.required');
  var filtered = $(e.target).closest('label.filtered');
  var tag = $(e.target).closest('label');
  var input = $(tag).find('input');
  var tagText = $(input).val();

  var more = $(e.target).closest('a.more');

  if(more.length) {
    var url = $(more).attr('href');
    $(more).html('<i>Loading...</i>');

    /**$(more)
      .after(
        $('<div/>')
          .load(url, function() {
            $('a.more').hide();
          })
      );**/

    return false;
  }

  $('#filter').addClass('refresh');

  if(required.length) {
    $(tag)
      .removeClass('required')
      .addClass('filtered')
      .html('<input type="checkbox" class="checkbox" name="tags" checked="checked" value="-' + tagText + '" /> ' + tagText);
      input.checked = 1;
      //.attr('name',"tagFilter[]");
      return false;
  } else if(filtered.length) {
    $(tag)
      .removeClass('filtered')
      .html('<input type="checkbox" class="checkbox" name="" value="' + tagText.substr(1) + '" /> ' + tagText.substr(1));
      input.checked = 0;
      return false;
  } else {
    $(tag)
      .addClass('required')
      .html('<input type="checkbox" class="checkbox" name="tags" checked="checked" value="' + tagText + '" /> ' + tagText);
      input.checked = 1;
      //.attr('name',"tagRequired[]");
      return false;
  }

});

$('#filter .superfilter label, #filters label').bind('click',function() {
  $('#filter').addClass('refresh');
});

$('#search_term input:first').bind('keyup',function() {
  $('#filter, #menu form').addClass('refresh');
  $('#search input:first').val($('#search_term input:first').val());
});
$('#search input:first').bind('keyup',function() {
  $('#filter, #menu form').addClass('refresh');
  $('#search_term input:first').val($('#search input:first').val());
});
$('#search input:first').val($('#search_term input:first').val());
$('#search input.submit').val('');

$('#filters_tags a.more').click(function() {
  $(this).toggleClass('open');
  if(!$('#filters_tags #alltags').length) {
    $('<div/>')
      .attr('id','alltags')
      .load(baseHref + '/tags.gsp', function() {
        $('#alltags').show();
      })
      .appendTo($('#filters_tags'));
  }
  $('#alltags').toggle();

  return false;
});


/** Sort toggle **/
//$('#sortBy option[value=' + readPref($('input[name=focus]').val() + '_sort') + ']').attr('selected','selected');
$('#sortBy').change(function() {
  $('#filter').addClass('refresh');
  
  var name = $('input[name=focus]').val() + '_sort';
  var val = $(this).val();
  preferences[name] = val;
	$.post(baseHref + '/account/setPreference', { key: name, value: val }, function() {
    //if($('body.usenetVideos #sortBy, body.usenetPhotos').length) {
      $('#filter').submit();
    //}
  });
});

/** Show covers **/
$('input[name=showCovers]').click(function() {
  $('#filter').addClass('refresh');
  
  //$(this).clone().attr('type','hidden').appendTo($('#filter'));

  var name = $(this).attr('name');
  var val = ($(this).is(':checked'))?'1':'0';
  $('#resultsPerPageVal').attr("disabled", "disabled");
  preferences[name] = val;
	$.post(baseHref + '/account/setPreference', { key: name, value: val }, function() {
    $('#filter').submit();
  });
});

/** filterTiny clips **/
//$('#filter input[name=filterTiny]').checked = readPref('filterTiny');
$('#filter input[name=filterTiny]').click(function() {
  $('#filter').addClass('refresh');

  var name = $(this).attr('name');
  var val = $(this).is(':checked');
  preferences[name] = val;
	$.post(baseHref + '/account/setPreference', { key: name, value: val }, function() {
    $('#filter').submit();
  });
});

/** results per page **/
  $('#resultsPerPageVal').change(function() {
    $('#filter').addClass('refresh');

    var val = $(this).val();
    var name = ($('.showCovers input:checked').length)?'resultsPerPageDVD':'resultsPerPage';
    preferences['resultsPerPage'] = val;
    $.post(baseHref + '/account/setPreference', { key: name, value: val }, function() {
      //if($('body.usenetVideos #resultsPerPage, body.usenetPhotos').length) {
        $('#filter').submit();
      //}
    });
  });


/** Views toggle **/
$('#view').removeClass('thumbnails details list montage').addClass(readPref('thumbsize'));
$('#view .' + readPref('thumbsize') + '').addClass('selected');
$('#view label').bind('click',function() {
  var name = $(this).find('input').attr('name');
  var val = $(this).find('input').val();

  if(name == 'thumbsize') {
    $(this).addClass('selected');
    $(this).siblings().removeClass('selected');

    $('div.thumbs').removeClass('thumbnails details list montage').addClass(val);
    $('#view').removeClass('thumbnails details list montage').addClass(val);
  }
  if(name == 'scrollforever') {
    val = $(this).find('input').is(':checked');
      $('#content div.thumbs')
        .toggleClass('scrollforever')
    $('.top, .jumppagination, #moreunseen').toggle();
  }
  if(name == 'thumbsize' && val == 'list') {
    $('.thumbs.scenes a.img').each(function() {
      $(this).attr('style', $(this).attr('longdesc'));
    });
  }
  if(name == 'thumbsize' && val == 'montage') {
    $('.thumbs.scenes img').each(function() {
      var url = $(this).attr('src').replace('-m','m');
      $(this).parents('div.thumb').attr('style', 'background-image: url(' + url + ') !important');
    });
  }

  if ((name == 'thumbsize') && $('.showCovers input:checked').length) {
    name = 'thumbsizeDVD';
  }

  setPref(name,val,14);
});

$('body.models #filters fieldset.filter :checked').parent().addClass('selected');
$('body.models #filters fieldset.filter input').bind('change',function() {
  $(this).parent().toggleClass('selected');
});

if ($('.showCovers input:checked').length && readPref('thumbsizeDVD')) {
  $("#view label." + readPref('thumbsizeDVD') + " input").attr('selected','selected').parent().click();  
} else if(readPref('thumbsize')) {
  $("#view label." + readPref('thumbsize') + " input").attr('selected','selected').parent().click();
}
if(readPref('scrollforever') === 'true' && $('#view label.scrollforever').length) {
  $("#view label.scrollforever input").checked = true;
  $("#view label.scrollforever input").attr('checked','checked');

  $('body.browse.unseen .thumbs a.img, body.browse.unseen .thumbs h3 a').attr('target','_blank');

  $('#content div.thumbs').addClass('scrollforever');
  $('.top, .jumppagination, #moreunseen').hide();
}

  /**$('body.browse.unseen #content div.thumbs, body.browse.all #content div.thumbs, body.browse.dvds #content div.thumbs, body.browse.amateur #content div.thumbs, body.browse.photos #content div.thumbs')
    .scrollForever();**/

/** Filter reset **/
$('#filter .reset').click(function(e) {
  e.preventDefault();

  var reset = confirm('Are you sure you want to start over?');
  if(reset) {
    $('#filter').append('<input type="hidden" name="reset" value="somethingorother" />');
    $('#filter').submit();
  }

  return false;
});


/** Tag cloud wraps **/
$('.thumbs').bind('click',function(e) {
    var filterTag = $(e.target).closest('a.filter');
    if(filterTag.length) {
      var tag = $(filterTag).attr('href').split('tags=-')[1];
      // 1. Toggle tag to be filtered (or Prepend to browse menu)
      $("#filters_tags label:contains('" + tag + "')").remove();
      $('<label/>')
        .addClass('filtered')
        .html('<input type="checkbox" class="checkbox" name="tags" checked="checked" value="-' + tag + '" /> ' + tag)
        .prependTo($('#filters_tags'));

      // 2. slide-fade-hide-remove all videos that contain this tag
      $(".thumbs .tagcloud a:contains('" + tag + "')").parents('div.thumb').hide('fast', function() { $(this).remove(); });

      // 3. If not "unseen" page, refresh results from page one
      if(!$('body.unseen').length) {
        $('#filter').submit();
      } else {
        // But, if we are on the unseen page, we need to pass the filtered tags
        var queryTags = '';
        $('#filters_tags :checked').each(function() {
            queryTags += $(this).val() + ',';
        });
        $.post($('#moreunseen').attr('action'), {
          hash: $("#moreunseen input[name='hash']").val(),
          timestamp: $("#moreunseen input[name='timestamp']").val(),
          tags: queryTags
        });

      }

      return false;

    }
});


/* ------------------------------------------------------------------------ */
}
$('html').removeClass('pending');
/* end body.browse */




/* body.watch **/
/* ------------------------------------------------------------------------ */
if($('body.watch').length) {
/* ------------------------------------------------------------------------ */
/** Skip to time and play **/
var skipTime = 0;
if(document.location.toString().indexOf('#t=') > 0) {
    var fulltime = document.location.toString().split('#t=')[1];
    skipTime = hmsToSeconds(fulltime);
}

/** Lightsout **/
$('body.watch li.lights a').click(function() {
  $('body').toggleClass('lightsout');
  return false;
});
if(readPref('lightsout')) {
  $('body.watch li.lights a').click();
}

/** Montage toggle **/
$('#montage #links a').click(function() {
  scrollTo(0, 1);
  if(!$('body.lightbox').length) {
    $('body').addClass('lightbox');
    $('body').append('<div id="lightbox"></div>');
  }
  
  var thumbNo = ($(this).text()-1);
  
  var downloadURL = $(this).attr('href');

  var prev = $('#links a:eq(' + (thumbNo-1) + ')');
  var next = $('#links a:eq(' + (thumbNo+1) + ')');
  
  $('#lightbox').html('<div class="wrap"><u class="close" title="Click to close" onclick="$(\'body\').removeClass(\'lightbox\'); $(\'#lightbox\').remove(); return false;">x</u> <a href="#" onclick="$(\'#lightbox a.next\').click(); return false;" class="big"><img src="' + downloadURL + '" /></a> <a href="' + downloadURL + '" class="download">Download</a></div>');
  $(prev).clone(true).addClass('prev').appendTo($('#lightbox .wrap'));
  $(next).clone(true).addClass('next').appendTo($('#lightbox .wrap'));
  
  return false;
});

/** iPad HTML5 player **/
if(navigator.userAgent.match(/iPad/i)) {
  var h264url = $("#download a:last").attr('href');
  $('body.loggedin #flow').html('<video src="' + h264url + '" height="400" width="700" controls="controls"></video>');
}
/** End iPad **/

  /** Popout view **/
  if(document.location.toString().indexOf('#pop') > 0) {
    $('body').addClass('popout');
    $('style').remove();
    preferences.autoplay = 0;
  }

  /** Toggle sections **/
  var hidden = readPref('hideme');
  if(hidden) {
    $(hidden).hide();
    hideArr = hidden.split(',');
    for(var i=0; i<(hideArr.length-1); i++) {
      $("h3 a[href='" + hideArr[i] + "']").addClass('closed');
    }
  }

  $('a.toggle').click(function() {
    var target = $(this).attr('href');
    
    $(this).toggleClass('closed');
    $(target).slideToggle('fast');

    hiddenArr = '';
    $('h3 a.closed').each(function() {
      hiddenArr += $(this).attr('href') + ',';
    });
    setPref('hideme',hiddenArr,14);

    return false;
  });
  
  /** Watch page video widget **/
  $('#flowplayer').not('.sample')
    .append(
      $('<div id="clipswidget"></div>')
      .append(
        $('<h3/>')
          .html('Recommended videos:')
          .click(function() {
            $('#flowplayer').toggleClass('hideClips');
            if(!$('#flowplayer.hideClips').length) {
              setPref('clipswidget', 1,14);
            } else {
              setPref('clipswidget', 0,-14);
            }
          })
      )
      .append($('#recommendedvideos').clone(true).show().removeAttr('id'))
    );
    if($('#dvdscenes').length) {
      $('#clipswidget')
        .append('<h3>Scenes from this DVD</h3>')
        .append($('#dvdscenes').clone(true).show().removeAttr('id'))
    }
    
    if(!readPref('clipswidget')) {
      $('#flowplayer').addClass('hideClips');
    }
    
    $('#clipswidget .thumb').click(function() {
      var url = $(this).find('a:first').attr('href');
      document.location = url;
    });
    
    if(!$('#recommendedvideos').length) {
      $('#clipswidget').remove();
      $('#flowplayer').addClass('hideClips');
    }

  /** Guest inline sign up **/
  if(($('body.guest').length && readCookie('p') && readCookie('p') == '0') || (navigator.userAgent.match(/iPad/i) && $('body.guest').length)) {
    $('#download, #clipswidget, #promobanner').hide();
    flowThumb = $('link[rel=image_src]:first').attr('href');
    var promoCopy = (navigator.userAgent.match(/iPad/i))?'Join Now to watch porn on your iPad!':'You have watched all your free previews';
    $('#flow').addClass('signup')
      .html('<img src="' + flowThumb + '" id="promothumb" /><form method="post" action="' + baseHref + '/session/submitJoin" target="_top"><input type="hidden" name="partial" value="1" /><h2>' + promoCopy + '</h2><p>Sign up now and get <b>unlimited access</b> to over 40,000+ videos, HD movies, photo galleries and more!</p><label>Username: <input type="text" id="form_username" name="username" value=""/></label><label>Email:<input type="text" id="form_email" name="email" value=""/></label><label>Password: <input type="password" id="form_password" name="password" value=""/></label><label>Password (again): <input type="password" id="form_passwordAgain" name="passwordAgain" value=""/></label><input type="submit" class="submit" value="Join!" /></form>');
  } else {

    /** Video Focus 
    var state = 0;
    setInterval(function() {
      if(flow) {
        var currentState = flow.getState();
        var time = flow.getTime();
          
        // Set play point
        if(state !== currentState && currentState == 3 && time > 1) {
          state = currentState;
          //$('#search input').val('Started @ ' + time);
        }
        // Set pause/stop point
        if(state !== currentState && currentState >= 4 && time > 1) {
          state = currentState;
          //$('#search input').val('Stopped @ ' + time);
        }
        
      }
    }, 300);
    /** End Video Focus **/
    function flowTracking(flow) {
      var time;
      var id = $('#content h2:first').attr('title');

      flow
        .onStart(function(clip) {
          time = flow.getTime();
          $.get(baseHref + '/player/event', 
            { event: 'start', id: id, ts: time });
            
          if(skipTime > 0) {
            flow.seek(skipTime);
          }
          
        })
        .onPause(function(clip) {
          time = flow.getTime();
          $.get(baseHref + '/player/event', 
            { event: 'pause', id: id, ts: time });
        })
        .onResume(function(clip) {
          time = flow.getTime();
          $.get(baseHref + '/player/event',
            { event: 'resume', id: id, ts: time });
        })
        .onFinish(function(clip) {
          time = flow.getTime();
          $.get(baseHref + '/player/event', 
            { event: 'finish', id: id, ts: time });
        })
        .onBeforeSeek(function(clip) {
          time = flow.getTime();
          $.get(baseHref + '/player/event',
            { event: 'beforeSeek', id: id, ts: time });
        })
        .onSeek(function(clip, time) {
          $.get(baseHref + '/player/event', 
            { event: 'seek', id: id, ts: time });
          setTimeout(function() {
            $('#share input:checkbox').triggerHandler('click');
          }, 100);
        })
    }

    var flow = 0;
      
    if (document.getElementById("flow")) {
      if (!readPref('autoplay')) {
        flow = $f("flow", { src: flowSwf, w3c: true, cachebusting:$.browser.msie}, flowSrc);
        flowTracking(flow);

      } else if (readPref('buffer')) {
        flowSrc.clip.autoPlay = false;
        flowSrc.clip.autoBuffering = true;
        flow = $f("flow", { src: flowSwf, w3c: true, cachebusting:$.browser.msie}, flowSrc);
        flowTracking(flow);

      } else {
        flowSrc.clip.autoPlay = false;
        $('<a/>')
          .html('<img src="' + flowMontage + '" id="hdpromothumb" /><span class="playicon"></span>')
          .click(function() {
            $(this).hide();
            flowSrc.clip.autoPlay = true;
            var flow = $f("flow", { src: flowSwf, w3c: true, cachebusting:$.browser.msie}, flowSrc);
            flowTracking(flow);
            return false;
          })
          .prependTo($('#flowplayer'));
      }
    }
  }

/** Share **/
var originalUrl = $('#share input:first').val();
var originalEmbed = $('#share textarea').val();

$('li.share a').click(function() {
  $('body').toggleClass('share');
  $('.open').removeClass('open');
  $('#flowplayer').addClass('hideClips');
  
    var time = flow.getTime();
    $('#share input[name=startTime]').val(secondsToHms(time));

  return false;
});
$('#share input, #share textarea').bind('click', function() {
  $(this).focus().select();
});
$('a.facebook').click(function() {
  var url = $(this).attr('href');
  var popup = window.open(url, 'popup', 'toolbar=0,scrollbars=0,location=1,statusbar=1,menubar=0,resizable=1,width=700,height=300');
  return false;
});

$('#share').append('<h3>Start time</h3>');
$('<label><input type="checkbox" value="1" name="togglestart" class="checkbox" /> Start video at:<label> <label><input name="startTime" disabled="disabled" value="0:00" /></label>')
    .appendTo($('#share'))
    .find('input:checkbox')
    .bind('click', function() {
        if($(this).is(':checked')) {
            $('#share input[name=startTime]').removeAttr('disabled');
            var time = flow.getTime();
            $('#share input[name=startTime]').val(secondsToHms(time));
            $('#share input:first').val(originalUrl + '#t='+secondsToHms(time));
            
            $('#share textarea').val(originalEmbed.replace("' quality","%26t%3D" + time + "' quality"));
        } else {
            $('#share input:first').val(originalUrl);
            $('#share input[name=startTime]').attr('disabled','disabled');
            
            $('#share textarea').val(originalEmbed);
        }
        
        $('#share input[name=startTime]')
        .keydown(function(e) {
            var time = $(this).val();
            
            $('#share input:first').val(originalUrl + '#t='+time);
        });
    });
    
/** Comment timestamp thing **/
$('#form_body').one('keydown', function() {
    var time = flow.getTime();
    var fulltime = $('div.header span.time').text().split(' ')[4];
    fulltime = hmsToSeconds(fulltime);
    var montageNum = $('#links a').length;
    var thisThumb = Math.floor(time*montageNum/fulltime);
    var displayTime = secondsToHms(time);
    
    $('<label class="thumbPreview"></label>')
        .append('<img src="' + $('#links a').eq(thisThumb).attr('href') + '" />')
        .append('<input name="timestamp" value="' + displayTime + '" />')
        .insertAfter('#comment input.submit');
    
    $('#comment .thumbPreview input')
        .keydown(function(e) {
            var time = hmsToSeconds($('#comment .thumbPreview input').val());
            var fulltime = $('div.header span.time').text().split(' ')[4];
            fulltime = hmsToSeconds(fulltime);
            var montageNum = $('#links a').length;
            var thisThumb = Math.floor(time*montageNum/fulltime);
            var displayTime = secondsToHms(time);
            
            $('#comment .thumbPreview img').attr('src', $('#links a').eq(thisThumb).attr('href'));
        });
});
   

/* ------------------------------------------------------------------------ */
}
/* end body.watch */




/* body.playlist, body.favorites **/
/* ------------------------------------------------------------------------ */
if($('body.playlist, body.favorites').length) {
/* ------------------------------------------------------------------------ */

/** Removal icon **/
$('.thumbs a.img').each(function() {
  //var videoID = $(this).attr('title');//$(this).attr('href').split('/').slice(-2).shift();
  var url = $(this).slice(0,1).attr('href');
  var videoID = ($('.thumbs.scenes').length)? url.split('watch/')[1].split('/')[0] : $(this).attr('title') ;
  var url = baseHref + '/favorite/' + videoID;

  if($('body.playlist').length) {
    var playlistID = $('#content h2 a').attr('href').split('/').pop();
    url = baseHref + '/playlist/' + playlistID + '/opus/' + videoID;
  }

  $(this).after(
    $('<u/>')
      .addClass('delete')
      .attr('title',url)
      .html('x')
      .click(function() {
        //$('body').append('<div id="progress">Removing item from List</div>');
        var delVid = confirm('Are you sure you want to remove this?');
        if(delVid) {
          var url = $(this).attr('title');
          var ref = $(this).parent();
          $.post(url + '?_method=delete&format=js', function(data) {
              $(ref).hide('fast',function() { $(this).remove(); });
          });
        } else {
          //$('#progress').remove();
        }
        return false;
      })
  );
});

/** Delete playlist **/
$('#content h2 a.delete').click(function() {
  var url = $(this).attr('href');

  var delPlaylist = confirm('Are you sure you want to delete this playlist?');
  if(delPlaylist) {
    $.post(url + '?_method=delete&format=js', function(data) {
        $('.thumbs').html('<blockquote class="alert">Playlist deleted!</blockquote>');
        setTimeout(function() {
            document.location = $('h1 a').attr('href');
        },2000);
    }, "json");
  }

  return false;
});


/* ------------------------------------------------------------------------ */
}
/* end body.playlist, body.favorites */



/* body.album, body.usenetphotos **/
/* ------------------------------------------------------------------------ */
if($('body.album, body.usenetPhotos, .thumbs.album, body.photos').length) {
/* ------------------------------------------------------------------------ */

$('.thumbs.album a, body.photos .thumbs.photos a, body.usenetPhotos .thumbs a').not("[href*='/join'],[href*='/account']").bind('click', function() {
  lightboxer($(this));
  return false;
});

if(document.location.toString().indexOf('#lb1') > 0) {
  $('body.usenetPhotos .thumbs a.img').eq(-1).click();
}
if(document.location.toString().indexOf('#lb0') > 0) {
  $('body.usenetPhotos .thumbs a.img').eq(0).click();
}


/* ------------------------------------------------------------------------ */
}
/* end body.playlist, body.favorites */




/* body.listing **/
/* ------------------------------------------------------------------------ */
if($('body.listing').length) {
/* ------------------------------------------------------------------------ */

  $('#content table th').click(function() {
    if($(this).is('.sort')) {
      $(this).toggleClass('reverse');
    }
    $(this).addClass('sort').siblings().removeClass('sort reverse');
  });
  
  $.getScript(baseHref + '/static/js/jquery.tablesorter.min.js', function() {
    $('#content table').tablesorter({
      textExtraction: function(node) {
        var title = node.getAttribute("title");
        if (title) {
          return title;
        } else if(node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
          return node.childNodes[0].innerHTML;
        } else {
          return node.innerHTML;
        }
      },
      headers: {
        1: {
          sorter: "digit"
        },
        2: {
          sorter: "digit"
        },
        3: {
          sorter: "digit"
        },
        4: {
          sorter: "digit"
        }
      }
    });
  });

/* ------------------------------------------------------------------------ */
}
/* end body.listing */





/* body.promo **/
/* ------------------------------------------------------------------------ */
if($('#promoClip').length) {
/* ------------------------------------------------------------------------ */

  flowSrc.clip.autoPlay = true;
  flowSrc.clip.autoBuffering = true;
  //var flow = $f("flow", { src: flowSwf, w3c: true, cachebusting:$.browser.msie}, flowSrc);
  $('<a/>')
    .attr('rel', 'nofollow')
    .html('<img src="' + flowThumb + '" id="hdpromothumb" /><span class="playicon"></span>')
    .click(function() {
      $(this).remove();
      flowSrc.clip.autoPlay = true;
      $('#flow').html('');
      var flow = $f("flow", { src: flowSwf, w3c: true, cachebusting:$.browser.msie}, flowSrc);
      return false;
    })
    .prependTo($('#flow'));

/* ------------------------------------------------------------------------ */
}
/* end body.promo */





/* body.search **/
/* ------------------------------------------------------------------------ */
if($('body.search.loggedin').length) {
/* ------------------------------------------------------------------------ */


  $('<a/>')
    .attr('href','#')
    .text('Save this search')
    .addClass('more save')
    .click(function() {
      $(this).html('<i>Saving...</i>');
      var bookmark = $(this).prev('a').attr('href').replace(/&page=\d+/, '');
      bookmark += ((bookmark.indexOf("?") > -1) ? "&" : "?") + "page=1";

      var query = document.location.toString().split('?q=')[1].split('&')[0];
      var section = $(this).parent('h2').find('a:first').text().split(' matching ')[1];

      var secTitle = "'" + query + "' " + section;

      var obj = $(this);
      obj.text(secTitle);

      $.post(baseHref + '/savedSearch',
        { url: bookmark, name: secTitle },
        function(searchID) {
          $('.savedSearches ul').append('<li class="fav videos"><a href="' + bookmark + '" title="' + searchID + '" class="ready">' + secTitle + '</a></li>');
          $(obj).html('<i>Saved!</i>');
          setTimeout(function() {
              $(obj).fadeOut('fast');
          },1500);
        }
      );

      return false;
    })
    .insertAfter($('body.search h2 a.more'));

/* ------------------------------------------------------------------------ */
}
/* end body.search */





/* body.account **/
/* ------------------------------------------------------------------------ */
if($('body.account').length) {
/* ------------------------------------------------------------------------ */

$('#sec_browse').submit(function(e) {
  e.preventDefault();
  
  // 0. Saving...
  $('#sec_browse input.submit').val('Saving...').addClass('pending');
  
  // 1. Cycle through elements, set cookies
  $('#sec_browse input:checkbox, #sec_browse select').each(function(i) {
    var cookie = $(this).attr('name');
    var value = ($(this).is(':checkbox'))? $(this).is(':checked') : $(this).val();
    value = (!value)? 0 : value ;
    //var days = (value)? 14 : -14;
    //setPref(cookie, value, days);
    preferences[cookie] = value;
  });

  var encodedSettings = JSON.stringify(preferences);
  $.post(baseHref + '/account/setPreference', { json: encodedSettings }, function() {
    $('#sec_browse input.submit').val('Saved!');
    setTimeout(function() {
      $('#sec_browse input.submit').val('Update Options').removeClass('pending');
    }, 1000);
  });
  
  return false;
});
if($('#sec_browse').length) {
  $('#sec_browse input:checkbox, #sec_browse select').each(function() {
    var cookie = $(this).attr('name');
    var value = readPref(cookie);
    if($(this).is(':checkbox') && value == 'true') {
      $(this).attr('checked','checked');
    } else {
      $(this).find("option[value='" + value + "']").attr('selected','selected');
    }
  });
}


/* ------------------------------------------------------------------------ */
}
/* end body.account */





/* body.thanks **/
/* ------------------------------------------------------------------------ */
if($('body.thanks').length) {
/* ------------------------------------------------------------------------ */

$('input:checkbox').click(function() {
    var cookie = $(this).attr('name');
    var value = ($(this).is(':checkbox'))? $(this).is(':checked') : $(this).val();
    value = (!value)? 0 : value ;
    preferences[cookie] = value;

    var encodedSettings = JSON.stringify(preferences);
    $.post(baseHref + '/account/setPreference', { json: encodedSettings }, function() {
      $('#sec_browse input.submit').val('Saved!');
      setTimeout(function() {
        $('#sec_browse input.submit').val('Update Options').removeClass('pending');
      }, 1000);
    });
});

/* ------------------------------------------------------------------------ */
}
/* end body.thanks */





/* body.index **/
/* ------------------------------------------------------------------------ */
if($('body.index').length) {
/* ------------------------------------------------------------------------ */

/** Carousal moving **/
  setInterval(function() {
    $('#carousel a:first')
      .css({ position: 'absolute' })
      .fadeOut('fast', function() {
        $(this)
          .css({ position: 'static' })
          .appendTo($('#carousel'))
          .show();
      });
  }, 6000);

/* ------------------------------------------------------------------------ */
}
/* end body.index */





/* body.signup **/
/* ------------------------------------------------------------------------ */
//if($('body.index').length) {
/* ------------------------------------------------------------------------ */

/** body.accountCheck toggler **/
$('body.accountCheck #content #comboplans label').click(function() {
  $(this).parent().siblings().find('label').removeClass('active')
  $(this).addClass('active');
}).find('input:checked').parents('label').click();
$('body.accountCheck #content .upgradeOptions label').click(function() {
  if($(this).find('input:checked').length) {
    $(this).addClass('active');
  } else {
    $(this).removeClass('active');
  }
}).find('input:checked').parents('label').click();


$('#form_cvv2').next('a').click(function() {
  var target = $(this).attr('href');
  $(target).slideToggle('fast');
  return false;
});

/** Form validation **/
var errors = 0;
$('body.accountCheck #content form').submit(function(e) {
  errors = 0;
  // 1. Check obvious errors
    if($('#content input.error:visible').length) {
      e.preventDefault();
      errors = 1;
    }

  // 2. Check simple fields
  $('#form_name, #form_number, #form_cvv2, #form_address, #form_city, #form_zip, #recaptcha_response_field, #form_state:visible').each(function() {
    if($(this).val().length < 1) {
      ++errors;
      e.preventDefault();
      $(this).parent().addClass('error');
    } else {
      $(this).parent().removeClass('error').find('p.error').remove();
    }
  });

  // 3. Check email
  $('#form_email').each(function() {
    var email = $(this).val();
    if(email.length < 3) {
      $('#form_email').parent().find('p.error').remove();
      $('#form_email').parent().addClass('error').append('<p class="error">You must enter a valid email.</p>');
    } else if(email.indexOf('@') < 1) {
      $('#form_email').parent().find('p.error').remove();
      $('#form_email').parent().addClass('error').append('<p class="error">This is not a valid email.</p>');
    } else {
      $('#form_email').parent().removeClass('error').find('p.error').remove();
    }
  });

  // 4. Alert on errors
  if(errors) {
    alert('There were some errors in the form.  Please make sure you\'ve entered everything correctly.');
  }

  // 4. No errors?  Post form
  if(!errors) {
    return true;
  } else {
    $('#content :input').removeAttr('disabled').removeAttr('readonly').fadeTo('fast',1);
    return false;
  }
});

$('body.accountCheck').find('#form_email, #form_name, #form_number, #form_cvv2, #form_address, #form_city, #form_zip, #recaptcha_response_field, #form_expirationMonth, select[name=expirationYear], #form_state:visible, #form_province:visible').focus(function() {
  if($(this).parent().is('.error')) {
    $(this).one('blur',function() {
      if($(this).val().length < 1) {
        ++errors;
        e.preventDefault();
        $(this).parent().addClass('error');
      } else {
        $(this).parent().removeClass('error').find('p.error').remove();
      }
    });
  }
});

$('body.accountCheck #form_username').focus(function() {
  $(this).one('blur',function() {
    $('#form_username').parent().removeClass('error').find('p.error').remove();
    var username = $(this).val();
    $('#form_username').parent().find('p.error').remove();
    if(username.length < 2) {
        $('#form_username').parent().addClass('error').append('<p class="error">That usename is too short.</p>');
    } else {
        $('#form_username').parent().removeClass('error');
        $.getJSON(baseHref + '/session/checkUsername?username=' + username, function(data) {
          $('#form_username').parent().removeClass('error').find('p.error').remove();
          if(data.length) {
            $('#form_username').parent().addClass('error').append('<p class="error">That usename is already in use. How about one of these:</p>');
            var pp = $('#form_username').parent().find('p.error');
            $.each(data, function(i,name){
              $('<a/>')
                .text(name)
                .click(function() {
                  $('#form_username').val($(this).text());
                  $('#form_username').parent().removeClass('error').find('p.error').remove();
                })
                .appendTo($(pp));
            });
          } else {
            $('#form_username').parent().removeClass('error').find('p.error').remove();
          }
        });
    }
  });
});

$('body.accountCheck #form_passwordAgain').focus(function() {
  $(this).one('blur',function() {
    if($(this).val() !== $('#form_password').val()) {
      $('#form_password').parent().find('p.error').remove();
      $('#form_password').parent().addClass('error').append('<p class="error">Your passwords don\'t match!</p>');
      $('#form_passwordAgain').parent().addClass('error');
    } else if($(this).val().length < 2) {
      $('#form_password').parent().find('p.error').remove();
      $('#form_password').parent().addClass('error').append('<p class="error">Your password is too short!</p>');
      $('#form_passwordAgain').parent().addClass('error');
    } else {
      $('#form_password, #form_passwordAgain').parent().removeClass('error').find('p.error').remove();
    }
  });
});


$('#comboplans input, #trialoffer label').click(function() {
   $('#comboplans label.selected, #trialoffer label.selected').not($(this)).removeClass('selected');
   $(this).addClass('selected');
});
$('#comboplans input:checked, #trialoffer input:checked').parents('label').addClass('selected');


$("body.accountCheck input[name='paymentPlan']").click(function() {
  var thisPlan = $(this).parents('fieldset').find('div.options');
  $(thisPlan).slideDown('fast');
  $('div.options').not(thisPlan).slideUp('fast');
});
$("input[name='paymentPlan']:checked").click();

$('body.accountCheck.apply.join legend label').click(function() {
  $(this).parents('fieldset').siblings('fieldset').find('div, table').slideUp('fast');
  $(this).parents('fieldset').find('div, table').slideDown('fast');
})
$("input[name='paymentMethodString']:checked").click();

/* ------------------------------------------------------------------------ */
//}
/* end body.signup */





/* body.favorites.front **/
/* ------------------------------------------------------------------------ */
if($('body.favorites.front').length) {
/* ------------------------------------------------------------------------ */

/**
Re-ordering, to be added someday
**/
if(readPref('listorder')) {
  var listArr = readPref('listorder').split(' ');
  
  for(var i=0; i < listArr.length; i++) {
    //$('#'+listArr[i]).insertBefore($('#myfavs li').eq(i));
    $('#'+listArr[i]).appendTo($('#myfavs'));
  }
}
$.getScript(baseHref + '/static/js/jquery.listreorder.js', function() {
    var unordered = $('#myfavs').ListReorder();
    $('#myfavs').bind('listorderchanged',function() {
      var listorder = '';
      $('#myfavs li').each(function() {
        listorder += $(this).attr('id') + ' ';
      });
      setPref('listorder',listorder.trim(),14);
    });
});

$('#myfavs a[href*=usenet]').each(function() {
  var link = $(this).html().split('.');
  link[link.length-2] = '<b>'+link[link.length-2]+'</b>';
  link[link.length-1] = '<b>'+link[link.length-1]+'</b>';
  var splitText = link.join('.&#x200B;');
  $(this).html(splitText);
});

$('#myfavs')
  .bind('click', function(e) {
  
    var favlist = $(e.target).closest('a');
    if($(favlist).length) {
      window.scrollTo(0,0);
      // Get link info
      var title = $(favlist).text();
      var url = $(favlist).attr('href');
      $(favlist).addClass('active');
      $('#myfavs a').not(favlist).removeClass('active');

      var filterH = $('#filter').height()+100;
      $('#content').css({ minHeight: filterH + 'px'});

      // Set loading
      if(!$('#content .sec').length) {
          $('<div class="sec loading"><i>Loading...</i></div>')
              .appendTo($('#content'));
      } else {
          $('#content .sec').html('<i>Loading...</i>').addClass('loading');
      }

      // Push to #content
      $('#content .sec').load(url + ' #content div.thumbs', function() {
          $('#content .sec')
              .removeClass('loading')
              .prepend('<h2><a href="' + url + '">' + title + '</a><a href="' + url + '" class="more">See all</a></h2>');

          if(readPref('resultsPerPage') && $('div.thumbs .thumb').length == readPref('resultsPerPage')) {
              $('#content .sec')
                  .append('<a href="' + url + '" class="seeall">See all</a></h2>');
          }
          
          $(this).parent()
            .find('#cams a')
            .click(function() {
                var cam = $(this).attr('href');
                document.location = $('.sec h2 a').attr('href') + '#cam=' + cam;
                return false;
            });

          $(this).parent()
            .find('.thumbs.scenes')
            .removeClass('list details montage')
            .addClass('thumbnails');

          $(this).parent()
            .find('.thumbs.scenes').not('.usenette, .album.usenet').find('.thumb')
            .not('.usenet').find('a.img')
              .one('mouseover',function() {
                $(this).attr('style', $(this).attr('longdesc'));
              })
              .bind('mousemove',function(e) {
                $(this).addClass('hover').removeClass('static');
                var offsetX = $(this).offset().left;
                var mouseX = e.pageX;
                var thumbSize = (!$('.thumbs.list').length)?16:48;
                var thumbWidth = (!$(this).hasClass('hdd'))?151:207;
                var backgroundPos = Math.floor((offsetX-mouseX)/thumbSize)*thumbWidth;
                $(this).stop().css({backgroundPosition: backgroundPos + 'px 0px'}, 100);
              });
          $(this).parent().find('.thumbs.usenette .thumb, .thumbs.scenes .thumb.usenet').hover(function() {
              var img = $(this).find('img');
              var src = img.attr('src');
              var anim = img.attr('longdesc');

              img.attr('src',anim).attr('longdesc',src);
            },
            function() {
              var img = $(this).find('img');
              var src = img.attr('src');
              var anim = img.attr('longdesc');

              img.attr('src',anim).attr('longdesc',src);
            }
          );


          $(this).parent()
            .find('.thumbs.scenes').not('.album.usenet').find('.thumb')
            .one('mouseover', function() {
              hoverMenu(this);
            })
            .hover(function() {
              $(this).addClass('hover');
              $('.thumb').not(this).removeClass('playlist download info hover');
            },
            function() {
              $(this).removeClass('hover');
            })

          //lightboxer(photo)
          $(this).parent()
            .find('.thumbs.album a, .thumbs.photos a').bind('click', function() {
              lightboxer($(this));
              return false;
            });

      });

      return false;
      
    }
    
  }).find('a').slice(0,1).click();

/* ------------------------------------------------------------------------ */
}
/* end body.index */





/* body.cams **/
/* ------------------------------------------------------------------------ */
if($('body.cams').length) {
/* ------------------------------------------------------------------------ */

/** Cam toggle **/
$('#cams').bind('click', function(e) {
    var camLink = $(e.target).closest('a');
    
    if(camLink.length > 0) {
      var modelId = $(camLink).attr('title');

      if(!$('#chat.active').length) {
          $(camLink).addClass('active');
          $('#chat')
              .attr('src',$(camLink).attr('href'))
              .addClass('active').slideDown('fast');
      } else if($(camLink).not('.active').size() > 0) {
          $(camLink).addClass('active');
          $('#cams a').not($(camLink)).removeClass('active');
          chat.camShow.joinRoom(modelId);
      }
    }
    
    return false;
});

/** Document location check **/
if(document.location.toString().indexOf('#cam=')) {
  var girlId = document.location.hash.match(/\d{3,}/);

  if (girlId) {
    $("#cams a[href*='" + girlId[0] + "']").click();
  }
}

/** Auto refresh cam girls every 60 seconds **/
setInterval(function() {
    $('#cams').load(document.location.toString() + ' #cams li');
}, 60000);

/* ------------------------------------------------------------------------ */
}
/* end body.index */

if (typeof onLoad === 'function') {
  $(function() {
    onLoad();
  });
}

if ((typeof svgOnLoad == 'object') && svgOnLoad.length) {
  $(function() {
    var i = 0;

    for (i = 0; i < svgOnLoad.length; i++) {
      svgOnLoad[i]();
    }
  })
}

/* END DOCUMENT READY **/
/* ------------------------------------------------------------------------ */
//});

