var form;
var categorySelect;
var subcategorySelect;
var subCategoryClone;
var subCategoryClonedOptions;

// Browser and feature tests to see if there is enough W3C DOM support
var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_mac = (agt.indexOf("mac") != -1);

//choose a category, and populate sub category object
function chooseCategory(value, categoryName, subcategoryName, changeSteps) {
  if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) {
    categorySelect = $(categoryName);
    subcategorySelect = $(subcategoryName);
    if (changeSteps == 1) {
      if (value==0) {
        helper_gotoStep(1);
      } else {
        helper_gotoStep(2);
      }
    }
    var pattern1 = /( |^)(select)( |$)/;
    var pattern2 = new RegExp("( |^)(" + categorySelect.options[categorySelect.selectedIndex].value + ")( |$)");
    emptySelect(subcategorySelect);
    for (var i = 0; i < subCategoryClonedOptions.length; i++) {
      if (subCategoryClonedOptions[i].className.match(pattern1) || subCategoryClonedOptions[i].className.match(pattern2) || (subCategoryClonedOptions[i].className=='active' && value!=0)) {
        subcategorySelect.appendChild(subCategoryClonedOptions[i].cloneNode(true));
      }
    }
  }
}

//choose a subcategory
function chooseSubCategory(value) {
  if (value != 0) {
    helper_gotoStep(3);
  } else {
    helper_gotoStep(2);
  }
}

//empty this select object from all options
function emptySelect(selectObject) {
  while (selectObject.options.length) {
    selectObject.options[0] = null;
  }
}

//store all subcategories in memory and then empty it
function storeSubCategories() {
  subCategoryClone = subcategorySelect.cloneNode(true);
  subCategoryClonedOptions = subCategoryClone.getElementsByTagName("option");
  emptySelect(subcategorySelect);
}

////////////////////////////////////////////

var versionListRowColorOn = '#fff';
var versionListRowColorOff = '#e3f2ff';


function changeVersionListRowColor(id,status) {
  if (status==1) {
    $('version_list_row_'+id).style.backgroundColor=versionListRowColorOn;
  } else {
    $('version_list_row_'+id).style.backgroundColor=versionListRowColorOff;
  }
}

var foldableInfoRowColorOn = '#fff';
var foldableInfoRowColorOff = '#f6f8fb';
function changeFoldableInfoRowColor(id,status) {
  if (status==1) {
    $('track_row_'+id).style.backgroundColor=foldableInfoRowColorOn;
  } else {
    $('track_row_'+id).style.backgroundColor=foldableInfoRowColorOff;
  }
}

var foldableInfoState = 0;
function openFoldableInfo() {
  Effect.toggle('foldableInfoContent', 'slide', { duration: 0.5 });
  new Effect.Fade('foldable_button_'+foldableInfoState, { duration: 0.25, queue: {position:'front', scope: 'foldableButtonScope'} });
  foldableInfoState = (foldableInfoState+1)%2;
  new Effect.Appear('foldable_button_'+foldableInfoState, { duration: 0.25, queue: {position:'end', scope: 'foldableButtonScope'} });
}

var unfoldedTitleVersions = new Array();
function toggleVersionListCovers(id,cover_ids,cover_thumbs, internalBannerSrc) {
  if ($('version_list_row_'+id+'_covers_div').style.display=='none') {
    $('version_list_covers_row_'+id).style.display = '';
    new Effect.Fade('version_list_expander_'+id+'_0', { duration: 0.25, queue: {position:'front', scope: 'version_list_expander_'+id+'Scope'} });
    new Effect.Appear('version_list_expander_'+id+'_1', { duration: 0.25, queue: {position:'end', scope: 'version_list_expander_'+id+'Scope'} });
    new Effect.BlindDown('version_list_row_'+id+'_covers_div', {duration: 0.5});

    //if this is the first time opening this one, load the thumbnails into it.
    if (typeof cover_ids != "undefined" && !unfoldedTitleVersions[id] && cover_ids.length > 0 && cover_thumbs.length > 0) {
      unfoldedTitleVersions[id] = true;
      var cover_ids_array = cover_ids.split(",");
      var cover_thumbs_array = cover_thumbs.split(",");
      for (i = 0; i < cover_ids_array.length; i++) {
        $("cover_image_"+cover_ids_array[i]).src = cover_thumbs_array[i];
      }
      //load banner
      if (typeof internalBannerSrc != "undefined") {
        $('listVersions_internal_banner_'+id).src = internalBannerSrc;
        $('listVersions_internal_banner_'+id).style.display = '';
      }
    }
  } else {
    new Effect.Fade('version_list_expander_'+id+'_1', { duration: 0.25, queue: {position:'front', scope: 'version_list_expander_'+id+'Scope'} });
    new Effect.Appear('version_list_expander_'+id+'_0', { duration: 0.25, queue: {position:'end', scope: 'version_list_expander_'+id+'Scope'} });
    new Effect.BlindUp('version_list_row_'+id+'_covers_div', {duration: 0.5, afterFinish: function(){$('version_list_covers_row_'+id+'').style.display='none'}});
  }
}

function openNewsItem(id) {
  if ($('foldableNewsContent_'+id).style.display=='none') {
    new Effect.Fade('news_expander_'+id+'_0', { duration: 0.25, queue: {position:'front', scope: 'news_expander_'+id+'Scope'} });
    new Effect.Appear('news_expander_'+id+'_1', { duration: 0.25, queue: {position:'end', scope: 'news_expander_'+id+'Scope'} });
    new Effect.BlindDown('foldableNewsContent_'+id, {duration: 0.5});
  } else {
    new Effect.Fade('news_expander_'+id+'_1', { duration: 0.25, queue: {position:'front', scope: 'news_expander_'+id+'Scope'} });
    new Effect.Appear('news_expander_'+id+'_0', { duration: 0.25, queue: {position:'end', scope: 'news_expander_'+id+'Scope'} });
    new Effect.BlindUp('foldableNewsContent_'+id, {duration: 0.5});
  }
}

function openPopupWindow(width, height, url, name) {
  var windowleft = (screen.width-width)/2;
  var windowtop = (screen.height-height)/2;
  window.open(url, name, 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width='+width+',height='+height+',left = '+windowleft+',top = '+windowtop);
}

function set_indicator_status(status,id) {
  if (id == null) {
    id = 'load_indicator';
  }
  if (status) {
    new Effect.BlindDown(id, { duration: 0.2, queue: {position:'end', scope: 'indicator_'+id+'_Scope'} });
  } else {
    new Effect.BlindUp(id, { duration: 0.2, queue: {position:'end', scope: 'indicator_'+id+'_Scope'} });
  }
}

function roll_toggle(id,status) {
  if (typeof status == 'undefined') {
    if ($(id).style.display=='none') {
      status = 1;
    } else {
      status = 0;
    }
  }
  if (status) {
    new Effect.BlindDown(id, { duration: 0.2 });
  } else {
    new Effect.BlindUp(id, { duration: 0.2 });
  }
}

function setSelections(name, newstatus) {
  d = document.getElementsByName(name);
  for (i = 0; i < d.length; i++) {
    if (d[i].type == "checkbox") {
      d[i].checked = newstatus;
    }
  }
}

function selectTopDataSpan(selectedSpan, unselectedSpan, containerId) {
  selectedSpanDivName = containerId+'_'+selectedSpan+'_table';
  unselectedSpanDivName = containerId+'_'+unselectedSpan+'_table';
  if ($(selectedSpanDivName).style.display=='none') {
    $(selectedSpan+'ButtonContainer_'+containerId).className = 'selectedTimespan';
    $(unselectedSpan+'ButtonContainer_'+containerId).className = 'unselectedTimespan';
    new Effect.BlindUp (unselectedSpanDivName, { duration: 0.45, queue: {position:'front', scope: 'topCoversSpan'} });
    new Effect.BlindDown (selectedSpanDivName, { duration: 0.45, queue: {position:'end', scope: 'topCoversSpan'} });
  }
  return false;
}

function escapeDots(inputString) {
  outputString = inputString.replace(/\./g,'__dot__');
  return outputString;
}

searchPhraseFocusGained = false;
function searchPhraseFocus(input) {
  if (searchPhraseFocusGained == false) {
    searchPhraseFocusGained = true;
    input.value='';
    input.className='';
  }
}

function searchBarRewrite(form, url, searchphrase, category) {
  searchphrase = trimString(searchphrase);
  searchphrase = encodeURIComponent(searchphrase);
  if (searchphrase.length>2 && category.length>0) {
    if (category == 'tv' || category == 'software') {
      url = 'http://www.findcdcovers.com/search.html?cx=008840417851475310060%3Akdtdmmsbbk8&cof=FORID%3A11&q=__search_phrase__';
      newWindow = true;
    } else {
      newWindow = false;
    }
    newUrl = url;
    newUrl = newUrl.replace('__search_phrase__',searchphrase);
    newUrl = newUrl.replace('__category_name__',category);
    if (newWindow) {
      window.open(newUrl);
    } else {
      form.action = newUrl;
      location.href = newUrl;
    }
    return false;
  } else {
    alert('Please enter a search phrase at least 3 letters long.');
    return false;
  }
}

function ttPagerLoadThumbs(id) {
  if ((typeof toolTipsThumbs[id].from) == 'string' && toolTipsThumbs[id].from.length>5) {
    $('pgr_fr_'+id).src = toolTipsThumbs[id].from;
  }
  if ((typeof toolTipsThumbs[id].to) == 'string' && toolTipsThumbs[id].to.length>5) {
    $('pgr_to_'+id).src = toolTipsThumbs[id].to;
  }
}

function showTopTable(selectedTable) {
  selectedContainerId = 'statsContainer_'+selectedTable;
  if ($(selectedContainerId).style.display == 'none') {
    availableOptions = new Array('topUsers', 'topUploaders', 'topDownloads');
    for (var i = 0; i < availableOptions.length; i++) {
      containerId = 'statsContainer_'+availableOptions[i];
      if ($(containerId).style.display != 'none') {
        new Effect.BlindUp (containerId, { duration: 0.45, queue: {position:'front', scope: 'topTablesSpan'} });
      }
      if (selectedTable != availableOptions[i]) {
        linkId = availableOptions[i]+'Link';
        $(linkId).className = '';
      }
    }
    new Effect.BlindDown (selectedContainerId, { duration: 0.45, queue: {position:'end', scope: 'topTablesSpan'} });
    linkId = selectedTable+'Link';
    $(linkId).className = 'selectedTableType';
  }
}

function showRelatedTable(selectedTable) {
  selectedContainerId = 'relatedContainer_'+selectedTable;
  if ($(selectedContainerId).style.display == 'none') {
    availableOptions = new Array('relatedTitles', 'relatedTitlesForUser');
    for (var i = 0; i < availableOptions.length; i++) {
      containerId = 'relatedContainer_'+availableOptions[i];
      if ($(containerId).style.display != 'none') {
        new Effect.BlindUp (containerId, { duration: 0.45, queue: {position:'front', scope: 'topTablesSpan'} });
      }
      if (selectedTable != availableOptions[i]) {
        linkId = availableOptions[i]+'Link';
        $(linkId).className = '';
      }
    }
    new Effect.BlindDown (selectedContainerId, { duration: 0.45, queue: {position:'end', scope: 'topTablesSpan'} });
    linkId = selectedTable+'Link';
    $(linkId).className = 'selectedTableType';
  }
}

function updateRequestCount(json, countObjectId) {
  newRequestCount = json.new_request_count;
  new Effect.Opacity(countObjectId, { duration: 0.25, from: 1, to: 0.01, queue: {position:'front', scope: 'updateRequestCountSpan'}});
  setTimeout("$('"+countObjectId+"').innerHTML = "+newRequestCount+";new Effect.Opacity('"+countObjectId+"', { duration: 1, from: 0.01, to: 1, queue: {position:'end', scope: 'updateRequestCountSpan'}});", 250);
}

function getImageUrl(sMd5) {
  return '/image_system/images/'+sMd5.substr(0,1)+'/'+sMd5.substr(1,1)+'/'+sMd5+'.jpg'
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

Array.prototype.inArray = function (value) {
  var i;
  for (i=0; i < this.length; i++) {
    if (this[i] === value) {
      return true;
    }
  }
  return false;
};

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ';', len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+'='+escape( value ) +
    ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
    ( ( path ) ? ';path=' + path : '' ) +
    ( ( domain ) ? ';domain=' + domain : '' ) +
    ( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + '=' +
      ( ( path ) ? ';path=' + path : '') +
      ( ( domain ) ? ';domain=' + domain : '' ) +
      ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function getSpyItemsInQueue() {
  return $('spiedItemsQueue').getElementsByClassName('spiedItemLine');
}
function getSpyItemsInDisplay() {
  return $('spiedItemsDisplay').getElementsByClassName('spiedItemLine');
}

function updateSpyDisplay()
{
  //first make sure spy display hasn't been closed.
  if (document.getElementById('spiedItemsQueue') == null) { return false; };

  //check if updates have been paused
  if (updatesPaused) {
    setTimeout('updateSpyDisplay()', (1000*iSecondsToNextVisualUpdate));
    return false;
  }

  itemsInQueue = getSpyItemsInQueue();
  iItemsInQueueCount = itemsInQueue.length;
  //if there are items in the queue move the bottom one here
  if (iItemsInQueueCount>0) {
    itemToMove = itemsInQueue[(itemsInQueue.length-1)];
    itemToMove.style.display = 'none';
    $('spiedItemsDisplay').insertBefore(itemToMove, $('spiedItemsDisplay').firstChild);
    new Effect.Appear(itemToMove, { duration: 0.5 });

    itemsInDisplay = getSpyItemsInDisplay();
    //gradually fade out the last few entries
    if (typeof(itemsInDisplay[iMaxItemsInDisplay-4])!='undefined') {
      new Effect.Fade(itemsInDisplay[iMaxItemsInDisplay-4], { duration: 0.25, from: 1.0, to: 0.8 });
    }
    if (typeof(itemsInDisplay[iMaxItemsInDisplay-3])!='undefined') {
      new Effect.Fade(itemsInDisplay[iMaxItemsInDisplay-3], { duration: 0.25, from: 0.8, to: 0.6 });
    }
    if (typeof(itemsInDisplay[iMaxItemsInDisplay-2])!='undefined') {
      new Effect.Fade(itemsInDisplay[iMaxItemsInDisplay-2], { duration: 0.25, from: 0.6, to: 0.4 });
    }
    if (typeof(itemsInDisplay[iMaxItemsInDisplay-1])!='undefined') {
      new Effect.Fade(itemsInDisplay[iMaxItemsInDisplay-1], { duration: 0.25, from: 0.4, to: 0.25 });
    }
    if (typeof(itemsInDisplay[iMaxItemsInDisplay])!='undefined') {
      itemsInDisplay[iMaxItemsInDisplay].style.display = 'none';
    }
    //now physically remove even older nodes from the DOM
    if (typeof(itemsInDisplay[iMaxItemsInDisplay+2])!='undefined') {
      $('spiedItemsDisplay').removeChild(itemsInDisplay[iMaxItemsInDisplay+2]);
    }

    iSecondsToNextVisualUpdate = iSecondsBetweenQueueUpdates / iItemsInQueueCount;
  } else {
    iSecondsToNextVisualUpdate = iSecondsBetweenQueueUpdates / 2;
  }

  if (iSecondsToNextVisualUpdate<iMinSecondsBetweenVisualUpdates) {
    iSecondsToNextVisualUpdate = iMinSecondsBetweenVisualUpdates;
  }
  setTimeout('updateSpyDisplay()', (1000*iSecondsToNextVisualUpdate));
}

//UCwords
String.prototype.ucwords = function(){
     return this.toLowerCase().replace(/\S+/g,function(s){
          return s.charAt(0).toUpperCase() + s.substr(1);
     })
}

//slide_in code
addLoadEvent(function() {
  if ($('bgWrapperSlideIn')) {
    var slideinCookieName = $('bgWrapperSlideIn').getAttribute('cookiename');
    var slideinCookieContents;
    slideinCookieContents = getCookie(slideinCookieName);
    if (null === slideinCookieContents) {
      setCookie(slideinCookieName, 0, 30, '/', '', '');
    }
    if (slideinCookieContents != 1) {
      var top_slidein_timeout=setTimeout("new Effect.SlideDown('bgWrapperSlideIn', {duration: 1});", 1000);
    }
  }
});

/*------------------*/
/* START addthis.js */
var  addthis_url   = '';
var  addthis_title = '';

function addthis_click(obj, str){

 var aturl  = 'http://www.addthis.com/bookmark.php';
 aturl += '?v=1';
 aturl += '&pub='+addthis_pub;
 aturl += '&url='+encodeURIComponent(addthis_url);
 aturl += '&title='+encodeURIComponent(addthis_title);

 window.open(aturl,'addthis','scrollbars=yes,menubar=no,width=620,height=520,resizable=yes,toolbar=no,location=no,status=no,screenX=200,screenY=100,left=200,top=100');


 return false;
}
/* END addthis.js */
/*----------------*/