/*
 *
 * FAIR WARNING
 * The ImageView for content below took me forever to get right.
 * Alter it carefully and at your own risk. Do not keep any sharp implements nearby.
 *
 * Wes Bryant
 */

$(document).ready(function() {
	$('#contentNav .first').click(function () { changePage(0); });
	$('#contentNav .prev').click(pageUp);
	$('#contentNav .next').click(pageDown);
});

// toggle between list and image views
function changeContentView(type)
{
  if(type == null || type.length == 0)
  {
    if($('#contentList:visible').length==0)
      type = 'image';
    else
      type = 'list';
  }
  nCurrPage = nNextPage = 0;
  $('#contentSlides div,#contentList div').remove();
  $('.slidePrevBtn,.slideNextBtn').hide();
  $('#contentSlidesBtn,#contentListBtn').removeClass('activeView');
  if(type == 'image')
  {
    $('#contentList').hide();
    $('#contentWindow').animate({height:'510px'},300);
    $('.slidePrevBtn,.slideNextBtn').show();
    // it will fade in naturally.
    $('#contentSlidesBtn').addClass('activeView');
  }
  else
  {
    $('#contentSlides,.slidePrevBtn,.slideNextBtn').hide();
    $('#contentList').show();
    $('#contentWindow').animate({minHeight:'550px'},300,function(){$('#contentWindow,#contentList').css('height','auto');});
    //$('#contentNav').html('<a href="javascript:void(0);" onclick="pageUp();">&lt; Prev</a> <a href="javascript:void(0);" onclick="pageDown();">Next &gt;</a>');
		getPageNav();
    $('#contentListBtn').addClass('activeView');
  }
  getTags(aContentList.slice(0,Math.min(aContentList.length,4)));
}


var aFilterTags = new Array();
var aFilterTypes = new Array();
var sSort = '';

var lastTypeFilterText,lastTagFilterText;
var nCurrPage = 0;
var nNextPage = 0;
var ixnay = false;

function changeSort(sNewSort)
{
  switch(sNewSort)
  {
    case 'age':
      $('#contentSort a').css('font-weight','normal');
      $('.sortAge').css('font-weight','bold');
      sSort = sNewSort;
      break;
    case 'relevance':
      $('#contentSort a').css('font-weight','normal');
      $('.sortRelevance').css('font-weight','bold');
      sSort = sNewSort;
      break;
    case 'popularity':
      $('#contentSort a').css('font-weight','normal');
      $('.sortPopularity').css('font-weight','bold');
      sSort = sNewSort;
      break;
  }
  getNewTags();
}
function filterContent()
{
  ixnay = false;
  sFilterTags = '';
  sFilterTypes = '';
  if($('#topicsFilter .checked').text() != lastTagFilterText || $('#typesFilter .checked').text() != lastTypeFilterText)
  {
    lastTagFilterText = $('#topicsFilter .checked').text();
    lastTypeFilterText = $('#typesFilter .checked').text();
    $('#topicsFilter input:checked').each(function(){
      sFilterTags += '|'+$(this).attr('name');
    });
    $('#typesFilter input:checked').each(function(){
      sFilterTypes += '|'+$(this).attr('name').substring(0,$(this).attr('name').length-1).toLowerCase();
    });

    aFilterTags = sFilterTags.substring(1).split('|');
    aFilterTypes = sFilterTypes.substring(1).split('|');
    getNewTags();
  }
}


function getNewTags()
{
  if(ixnay == false)
  {
    $('#loadingImg').show();
    $('#loadingImg').fadeTo(50,0.5);
    aPath = encodeURI(window.location.pathname);
    $.get(aPath.replace(/[#\?].*$/i,'') + '&sort=' + sSort +
      '&filterTags=' + aFilterTags.join(',').replace(/[^,a-z0-9_-]/i, '') +
      '&filterTypes=' + aFilterTypes.join(',').replace(/[^,a-z0-9_-]/i, ''),
      function(data){
        aContentList = data.split(',');
        changeContentView();
    });
  }
}

// shortcuts to move the page incrementally
function pageUp() {changePage(nCurrPage - 1);}
function pageDown() {
  if(ixnay == false)
  {
    if(nNextPage == aContentList.length - 1)
    {
      changeContentView('image');
      return false;
    }
    else
    {
      changePage(nCurrPage + 1);
      return false;
    }
  }
}

/**
 * changePage()
 * Reloads the next set of content
 *
 */
function changePage(nNewPage)
{
  // inxay indicates that we are already waiting on a call to get a set of data
  if(ixnay == false && aContentList.length > 1)
  {
    if(nNewPage >= 0)
    {
      if($('#contentList:visible').length > 0)	// reloading list
      {
        if(aContentList.length > 4)
        {
          if(nNewPage-nCurrPage == 1 || nNewPage-nCurrPage == -1)
          {
            nNewPage *= 4;
            getTags(aContentList.slice(Math.max(0,nNewPage), Math.min(aContentList.length, Math.max(nNewPage+4,4))));
            nNextPage = nNewPage / 4;
          }
          else
          {
            nNewPage *= 4;
            getTags(aContentList.slice(nNewPage, nNewPage + 4));
            nNextPage = nNewPage / 4;
          }
        }
      }
      else	// reloading slideshow
      {
        $('#contentSlides .contentPreview').fadeTo(10,0.3);
        if(nNewPage - nCurrPage == 1)
        {
          nNewPage = parseInt(aContentList.indexOf($('#contentSlides .contentPreview:last').attr('id').replace(/[^0-9]/g,''))) + 1;
          getTags(aContentList.slice(nNewPage, nNewPage+1));
          $('#contentSlides .contentPreview:eq(1)').fadeTo(50,1,function(){
              if (document.all) $('#contentSlides .contentPreview:eq(1)').css('filter',''); // IE opacity fix
          });
          nNextPage = aContentList.indexOf($('#contentSlides .contentPreview:first').attr('id').replace('content',''))+1;
        }
        else if(nNewPage - nCurrPage == -1)
        {
          nNewPage = parseInt(aContentList.indexOf($('#contentSlides .contentPreview:first').attr('id').replace(/[^0-9]/g,''))) - 1;
          if(nNewPage < 0)
            return false;
          getTags(aContentList.slice(nNewPage, nNewPage + 1));
          nNextPage = nNewPage;
        }
        else
        {
          $('#contentSlides').fadeOut(200,function()
          {
            $('#contentSlides .contentPreview').remove();
            getTags(aContentList.slice(nNewPage, nNewPage + 4));
            nNextPage = nNewPage;
          });
        }
      }
    }
  }
}

//  Takes an array of items and submits a call to get info for the ids in that set
// see tag_display_page_v2.inc.php for outside function
function getTags(aSlice)
{
  if(aSlice == null || aSlice.length == 0)
  {
    aSlice = aContentList.slice(0,Math.max(4,aContentList.length));
  }
  if(ixnay == false)
  {
    aPath = encodeURI(window.location.pathname);
    $.get(aPath.replace(/[\?#].*$/i,'') + '&aid=' + aSlice.join(','),loadNewPage);
  }
}

// Takes output from getTags and loads it into the content window
function loadNewPage(sContent)
{
  if(sContent.length == 0)
  {
    sContent = '<center><br />No Items Found.<br /><br />Try Adding/Removing Some Topics or Content Types in the Filter.</center>';
  }
  if($('#contentList:visible').length > 0)	// reloading list
  {
    $('#loadingImg').show();
    if(nNextPage>0 || (nNextPage<nCurrPage))
      $(document).scrollTo($('#contentMenu'),800);
    $('#contentList').fadeOut(400,function()
    {
      // remove current items, replace with new ones
      $('#contentList .contentPreview').remove();
      if($('#contentList > div:first').length > 0)
        $('#contentList').scrollTo($('#contentList > div:first'));
      $('#contentList').html(sContent);
      $('#contentList .contentPreview:last').css('border-width','0px');
      $('#contentList').fadeIn(400,getPageNav);

      // reset the page and release lock on getting next set
      nCurrPage = nNextPage;
      ixnay = false;
      // set the first two items in the list to be featured more prominently
      $('#contentList .contentPreview .contentDetails:lt(2)').addClass('bigPreview');
    });
  }
  else	// reloading slideshow
  {
    // remove current items, replace with new ones
    if(nNextPage >= nCurrPage)
    {
      // add new slides to the end
      $('#contentSlides').append(sContent);
      // set slides to half visible
      $('#contentSlides .contentPreview').fadeTo(10,0.3);

      // except for first and last slide, we always slide over one
      if((nNextPage != 0 && nNextPage != aContentList.length) || aContentList.length == 2)
      {
        $('#contentSlides .contentPreview:eq(1)').fadeTo(10,1,function(){
            if (document.all) $('#contentSlides .contentPreview:eq(1)').css('filter',''); // IE opacity fix
        });
        $('#contentSlides .contentPreview:eq(0)').animate({marginLeft: '-530px'},500,function(){
          $('#contentSlides .contentPreview:eq(0)').remove();
          $('#contentSlides .contentPreview:eq(0)').addClass('currentPreview');
        });
      }
      if($('#contentSlides .contentPreview').length > Math.min(5, aContentList.length))
      {
        $('#contentSlides .contentPreview:eq(1)').fadeTo(10,1,function(){
            if (document.all) $('#contentSlides .contentPreview:eq(1)').css('filter',''); // IE opacity fix
        });
        while(parseInt(aContentList.indexOf($('#contentSlides .contentPreview:first').attr('id').replace(/[^0-9]/g,'')))!=nCurrPage)
        {
          $('#contentSlides .contentPreview:eq(0)').animate({marginLeft: '-530px'},500,function(){
            $('#contentSlides .contentPreview:eq(0)').remove();
            setTimeout('getPageNav();',200);
          });
        }
      }
      else
      {
        $('#contentSlides .contentPreview').fadeTo(10,0.3,function(){
          $('#contentSlides .contentPreview:eq(0)').fadeTo(10,1,function(){
              if (document.all) $('#contentSlides .contentPreview:eq(0)').css('filter',''); // IE opacity fix
          });
        });
      }
      // reset the page and release lock on getting next set
      nCurrPage = nNextPage;
      ixnay = false;
    }
    else if(nNextPage < nCurrPage)
    {
      // add new slides to the beginning
      // add negative margin so we don't disrupt too much
      $('#contentSlides').css('margin-left','-530px');
      $('#contentSlides').prepend(sContent);
      $('#contentSlides .contentPreview').fadeTo(10,0.5,function(){
          $('#contentSlides .contentPreview:eq(0)').fadeTo(10,1,function(){
              if (document.all) $('#contentSlides .contentPreview:eq(0)').css('filter',''); // IE opacity fix
          });
      });

      // slide new slide in
      $('#contentSlides').animate({marginLeft: '0px'},500);
      if($('#contentSlides .contentPreview').length > Math.min(4, aContentList.length))
      {
        for(i = $('#contentSlides .contentPreview').length; i > Math.min(3, aContentList.length); i--)
        {
          $('#contentSlides .contentPreview:eq(' + (i) + ')').remove();
        }
      }
      // pop off old slides to the right
      nCurrPage = nNextPage;
      ixnay = false;
    }
    if($('#contentSlides:visible').length == 0)
      $('#contentSlides').fadeIn(300,getPageNav);
    else
      setTimeout('getPageNav();',400);

  }
  $('#loadingImg').fadeOut();
}


function getPageNav()
{
    var thisPage = 0;
    var pageLinks = '';
    if($('#contentSlides:visible').length > 0)
      thisPage = parseInt(aContentList.indexOf($('#contentSlides .contentPreview:first').attr('id').replace(/[^0-9]/g,''))) + 1;
    else if($('#contentList .contentPreview:first').length > 0)
      thisPage = parseInt(aContentList.indexOf($('#contentList .contentPreview:first').attr('id').replace(/[^0-9]/g,''))) / 4 + 1;
		if(thisPage > 1)
    {
			$('#contentNav .first, #contentNav .prev').show();
      //pageLinks += '<a href="javascript:void(0);" onclick="changePage(0);"><img src="/images/shell_v2/newTagPages/pageFirst.png" alt="First Page" title="First Page" align="absmiddle"/></a> <a href="javascript:void(0);" onclick="changePage(0);">First</a>&nbsp;&nbsp;';
      //pageLinks += '<a href="javascript:void(0);" onclick="pageUp();"><img src="/images/shell_v2/newTagPages/pagePrev.png" alt="Previous Page" title="Previous Page" align="absmiddle"/></a> <a href="javascript:void(0);" onclick="pageUp();">Prev</a>&nbsp;&nbsp;&nbsp;&nbsp;';
    }
		else
		{
			$('#contentNav .first, #contentNav .prev').hide();
		}
    if($('#contentSlides:visible').length > 0)
    {
      $('#pageCount').html('');
      if(thisPage >= 5)
      {
        page = thisPage - 4;
        for(i = page; i < thisPage + 5; i++)
        {
          if(page > aContentList.length)
          {
            $('#contentNav').html(pageLinks);
            return false;
          }
          if((page-1) == thisPage)
            pageLinks += '<b>' + (page) + '</b>&nbsp;&nbsp;';
          else
            pageLinks += '<a href="javascript:void(0);" onclick="changePage(' + (page - 1) + ');">' + (page) + '</a> ';
          page++;
        }

      }
      else
      {
        for(i = 1; i <  Math.min(10, aContentList.length+1); i++)
        {
          if((nNextPage == 0 && i == 1) || (nNextPage != 0 && (i-1) == thisPage))
            pageLinks += '<b>' + (i) + '</b>&nbsp;&nbsp;';
          else
            pageLinks += '<a href="javascript:void(0);" onclick="changePage(' + (i - 1) + ');">' + i + '</a> ';
        }
      }
      pageLinks += '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(0);" onclick="pageDown();">Next</a> <a href="javascript:void(0);" onclick="pageDown();"><img src="/images/shell_v2/newTagPages/pageNext.png" align="absmiddle" alt="Next Page" title="Next Page" /></a> ';
//      pageLinks += '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="changePage(' + (aContentList.length - 1) + ');">Last</a> <a href="javascript:void(0);" onclick="changePage(' + (aContentList.length - 1) + ');"><img src="/images/shell_v2/newTagPages/pageLast.png" align="absmiddle"/></a> ';
    }
    else
    {
			var range = ((Math.max(0,thisPage - 1) * 4) + 1) 
				+ '-' 
				+ Math.min((Math.max(0,thisPage - 1) * 4) + 4,aContentList.length);
      $('#pageCount .range').html(range);
			$('#pageCount .total').html(aContentList.length);
      if(thisPage < aContentList.length)
      {
				$('#contentNav .last')
					.unbind('click')
					.click(function () {
						changePage((aContentList.length / 4) - 1);
					});
      }
    }
    //$('#contentNav').html(pageLinks);


}




/*****************************
*
* RELATED TAG FUNCTIONS
*
*****************************/
var currTagList;
var currScroll = 0;
var maxScrollWidth;
$(document).ready(function(){
  // the "next page" width
  maxScrollWidth = $('.tagListTd:visible').innerWidth();
  $('#tagType1,#tagType2').bind('mousedown',switchTagType);

  $('#tagType1,#tagType2').bind('mouseover',function(){

    // no hover effect when already active
    if(!$(this).hasClass('activeTagType')) {
      // replace left and right bookends
      $(this).children('img').each(function(){
        this.src = this.src.replace(/_inactive_/i,'_hover_');
      });
      $(this).toggleClass('hoverTagType');
    }

  });
  // hover effect finish
  $('#tagType1,#tagType2').bind('mouseout',function(){
    if($(this).hasClass('hoverTagType')) {
      // replace left and right bookends
      $(this).children('img').each(function(){
        this.src = this.src.replace(/_hover_/i,'_inactive_');
      });
      $(this).toggleClass('hoverTagType');
    }
  });

  // set scroll actions
  $('.tagListLeft').mousedown(function(){scrollLeft();});
  $('.tagListLeft').mouseup(function(){stopScrolling();});
  $('.tagListLeft').mouseout(function(){stopScrolling();});

  $('.tagListRight').mousedown(function(){scrollRight();});
  $('.tagListRight').mouseup(function(){stopScrolling();});
  $('.tagListRight').mouseout(function(){stopScrolling();});
  $('.tagListBottom').disableTextSelect();

});

function switchTagType()
{

  $('.activeTagType img').each(function(){
    // Replace left and right bookends
    this.src = this.src.replace(/tagtype_(left|right)/i,"tagtype_inactive_$1");
  });


  // set Active tag type
  $('#tagList1,#tagList2').toggleClass('activeTagList');
  $('.tagType').toggleClass('activeTagType');
  // Remove hover effect
  $('.tagType').removeClass('hoverTagType');
  $('.activeTagType img').each(function(){
    this.src = this.src.replace(/(_hover_|_inactive_)/i,'_');
  });
    // reset scroll
    currScroll=0;
    currTagList = $('.activeTagList .tagListTd span a');
}

var keepScrolling;
var delay = 500;

function stopScrolling() {
  clearTimeout(keepScrolling);
  delay = 500;
}

function scrollLeft()
{
  // when they hold down the button, keep going
  clearTimeout(keepScrolling);
  keepScrolling = setTimeout("scrollLeft()",500);

  var cellPadding = $('.activeTagList .tagListTd').outerWidth()-$('.activeTagList .tagListTd').innerWidth();
  var reachedVisibleWidth = 0;
  for(var i = currScroll;i >= 0;i--)
  {
    // use outer width to include both margin and padding
    if(reachedVisibleWidth - $('.activeTagList .tagListTd span a:eq('+i+')').outerWidth() < -1 * (maxScrollWidth + (cellPadding * 2)))
    {
      break;  // we've reached the end of the line
    }
    else
    {
      currScroll = i;
      reachedVisibleWidth -= $('.activeTagList .tagListTd span a:eq('+i+')').outerWidth();
    }
  }
  if(currScroll <= 0) {
    currScroll = 0;
    // set image to indicate we have more room
    $('.activeTagList .tagListLeft').css('background-position','0px -694px');
    $('.activeTagList .tagListRight').css('background-position','0px -658px');
  }
  else {
    // set image to indicate we DON'T have more room
    $('.activeTagList .tagListLeft').css('background-position','0px -622px');
    $('.activeTagList .tagListRight').css('background-position','0px -658px');
  }
  $('.activeTagList .tagListTd span').scrollTo('a:eq('+(currScroll)+')',300,'easeout');
}

function scrollRight()
{
  // when they hold down the button, keep going
  clearTimeout(keepScrolling);
  keepScrolling = setTimeout("scrollRight()",500);
  var reachedVisibleWidth = 0;

  // we have to include cell padding when calculating what is visible
  var cellPadding = $('.activeTagList .tagListTd').outerWidth()-$('.activeTagList .tagListTd').innerWidth();
  for(var i = currScroll;i < $('.activeTagList .tagListTd span a').length;i++)
  {
    // use outer width to include both margin and padding
    if(reachedVisibleWidth + $('.activeTagList .tagListTd span a:eq('+i+')').outerWidth()  > (maxScrollWidth + (cellPadding * 2)))
    {
      break;
    }
    else
    {
      reachedVisibleWidth += $('.activeTagList .tagListTd span a:eq('+i+')').outerWidth();
      currScroll = i;
    }
  }
  if(currScroll >= $('.activeTagList .tagListTd span a').length-5) {
    currScroll = $('.activeTagList .tagListTd span a').length - 1;
    // set image to indicate we have more room
    $('.activeTagList .tagListRight').css('background-position','0px -730px');
    $('.activeTagList .tagListLeft').css('background-position','0px -622px');
  }
  else {
    // set image to indicate we DON'T have more room
    $('.activeTagList .tagListRight').css('background-position','0px -658px');
    $('.activeTagList .tagListLeft').css('background-position','0px -622px');
  }

  $('.activeTagList .tagListTd span').scrollTo('a:eq('+(currScroll)+')',300,'easeout');
}

