var strFilterType = 'filter';
var strFiltersType = 'filters';

function addFilterToCookie(strValue)
{
  var strPickedFilters = $.cookie('VSFilters');
  if(strPickedFilters != null && !strPickedFilters.match(strValue))
  {
    if(strPickedFilters != null && strPickedFilters != '')
    {
      var strDivider = ';';
    }
    else
    {
      var strDivider = '';
    }

    if(strPickedFilters == 'filters')
    {
      $.cookie('VSFilters', strValue);
    }
    else
    {
      $.cookie('VSFilters', $.cookie('VSFilters') + strDivider + strValue);
    }
  }
  else if(strPickedFilters == null)
  {
    $.cookie('VSFilters', strValue);
  }
}

function repopulateFilters()
{
  return false;
  var strPickedFilters = $.cookie('VSFilters');
  if(strPickedFilters != null && strPickedFilters != '')
  {
    arrPickedFilters = strPickedFilters.split(';');
    for(i=0; i<arrPickedFilters.length; i++)
    {
      strFilter = arrPickedFilters[i];
      arrBits = strFilter.split("_");
      var strFilterName = '';
      for(var j=0; j<arrBits.length-1; j++)
      {
        if(strFilterName != '')
        {
          strFilterName+= '_' + arrBits[j];
        }
        else
        {
          strFilterName+= arrBits[j];
        }
      }

      if(strFilterName == 'categories_id')
      {
        $('.applied_' + strFilterName + '_url_picked').remove();
      }

      if($('#applied_' + strFilterName).length == 0)
      {
        $('#ajax_filters_wrapper').append('<input type="hidden" name="' + strFilterName + '[]" value="' + arrBits[j] + '" class="applied_' + strFilterName + ' js_add" id="applied_ajax_filters_' + strFilter + '" />');
      }
      $('#filter_catalog_navigation_link_' +arrPickedFilters[i] + ' a').addClass('active_filter');
    }
    //refreshProductListings();
  }
  $.cookie('VSFilters', strPickedFilters);
}
function showAjaxLoaderPopover (){

  if($('#ajax_filters_loading').length == 0)
  {
    var strHTML = '<div id="ajax_filters_loading"></div>';
    $('#middle_column').append(strHTML);
    //$('body').append(strHTML);
  }
  else
  {
    $('#ajax_filters_loading').show();
    //$('#ajax_filters_loading').fadeIn(250);
  }
  //$('#middle_column').fadeOut(500);
}

function isIE()
{
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}
var lastHash = '';
var blnCheckHash = false;
function pollHash() {
  if(blnCheckHash == true && lastHash !== self.document.location.hash) {
    lastHash = self.document.location.hash;
    //alert('hash changed, looking to update');
    // hash has changed, so do stuff:
    //initialTickFilters();
    showAjaxLoaderPopover();
    $('.manual_applied').remove();
    updateFromHash();
    refreshProductFilters('', getProductListingsQuery());
    refreshProductListings();
  }
}

function updateFromHash()
{
  var strURLCriteria = unescape(self.document.location.hash.substring(1));

  arrBits = strURLCriteria.split(':');
  blnRemoveDefaultCategories = false;
  //$('a.active_filter').removeClass('active_filter');

  for(var i=0; i<arrBits.length; i++)
  {
    var strType = '';
    if(arrBits[i].substring(0,4) != 'page') var strType = arrBits[i].substring(0,1);
    var strID = arrBits[i].substring(1,arrBits[i].length);
    var strApplyAs = null;
    var strFullApplyAs = null;
    switch(strType)
    {
      case 't':
        strApplyAs = 'tags_id';
        break;
      case 'b':
        strApplyAs = 'price_band_id';
        break;
      case 'c':
        strApplyAs = 'categories_id';
        break;
      case 'p':
        strApplyAs = 'category_parent_id';
        break;
      case 'm':
        strApplyAs = 'manufacturer_id';
        break;
      case 'a':
        strApplyAs = 'attribute_value_ids';
        break;
    }
    if(strApplyAs != null)
    {
      strFullApplyAs = strApplyAs + '_' + strID;
      if($('#ajax_filters_' + strFullApplyAs).length == 0 && $('#applied_ajax_finder_' + strFullApplyAs).length == 0)
      {
        if(!blnRemoveDefaultCategories && strApplyAs == 'categories_id')
        {
          blnRemoveDefaultCategories = true;
          //$('.applied_categories_id_url_picked').attr('disabled', true);
          pullOutCurrentCategory();
        }

        if(strID != null)
        {
          if($('#applied_ajax_filters_' + strFullApplyAs).length == 0)
          {
            $('#ajax_filters_wrapper').append('<input type="hidden" name="' + strApplyAs + '[]" id="applied_ajax_filters_' + strFullApplyAs + '" class="applied_' + strApplyAs + ' url_applied applied_' + strApplyAs + '_picked" value="' + strID + '" />');
          }
          else
          {
            $('#applied_ajax_filters_' + strFullApplyAs).attr('disabled', false);
          }
        }
      }
      if($('#filter_catalog_navigation_link_' + strFullApplyAs).length > 0)
      {
        strExistingClass = $('#filter_catalog_navigation_link_' + strFullApplyAs + ' a').attr('className');
        $('#filter_catalog_navigation_link_' + strFullApplyAs + ' a').addClass('active_filter');
        strClearLinkHTML = '<a href="#" onclick="removeProductFiltersGroup(\'' + strApplyAs + '\'); return false;" class="remove_filter" title="Clear"><span class="remove_filter_span">Clear</span></a>';
        $('#filter_catalog_navigation_' + strApplyAs + '_clear_all').text('');
        $('#filter_catalog_navigation_' + strApplyAs + '_clear_all').append(strClearLinkHTML);
      }
    }
    else
    {
      if(arrBits[i].match(/page/))
      {
        $('#ajax_filters_pages').val(arrBits[i].replace(/page/, ''));
      }
      if(arrBits[i].match(/sort/))
      {
        $('#ajax_finder_sortby').val(arrBits[i].replace(/sort/, ''));
      }
    }
  }
}

function pullOutCurrentCategory()
{
  strURL = new String(document.location);
  if(!strURL.match('search/'))
  {
    arrTempURLBits = strURL.split('-c');
    if(arrTempURLBits.length > 0)
    {
      blnApplyEndCategoryID = false;
      for(var j=1; j< arrTempURLBits.length; j++)
      {
        if(arrTempURLBits[j].match('#'))
        {
          strSplit = '#';
        }
        else
        {
          strSplit = '/';
        }

        arrCatID = arrTempURLBits[j].split(strSplit);
        strApplyCategoryAs = 'categories_id';

        if(j == (arrTempURLBits.length-1))
        {
          strApplyCategoryAs = 'parent_category_id';
          blnApplyEndCategoryID = true;
        }
        else
        {
          strID = null; // set to null, to avoid putting in level 1 categories when we're at level 3 etc.
        }

        if(blnApplyEndCategoryID)
        {
          strFullApplyCategoryAs = strApplyCategoryAs + '_' + arrCatID[0];

          if(!isNaN(arrCatID[0]))
          {

            if($('#applied_ajax_filters_' + strFullApplyCategoryAs).length == 0)
            {
              $('#ajax_filters_wrapper').append('<input type="hidden" name="' + strApplyCategoryAs + '[]" id="appied_ajax_filters_' + strFullApplyCategoryAs + '" class="applied_' + strApplyCategoryAs + ' url_applied applied_' + strApplyCategoryAs + '_picked" value="' + arrCatID[0] + '" />');
            }
            else
            {
              $('#applied_ajax_filters_' + strFullApplyCategoryAs).attr('disabled', false);
            }
          }
        }
      }
    }
  }
}

function initialTickFilters()
{
  //repopulateFilters();
  arrFilters = $('#ajax_filters_wrapper').children();
  strQueryString = '?';
  for(i=0; i<arrFilters.length; i++)
  {
    if(arrFilters[i].name != undefined && !arrFilters[i].disabled)
    {
      strFilterName = arrFilters[i].id;
      strFilterName = strFilterName.replace(/applied_ajax_filters_/, '');

      //addFilterToCookie(strFilterName);
      arrFilterNameBits = strFilterName.split("_",3);
      iBlah = arrFilterNameBits.pop();
      strPlainFilterName = '';
      for(j=0; j<arrFilterNameBits.length; j++)
      {
        strPlainFilterName  += arrFilterNameBits[j] + '_';
      }
      strPlainFilterName = strPlainFilterName.substring(0,strPlainFilterName.length-1);

      if(strPlainFilterName == 'price_band')
      {
        strPlainFilterName = 'price_band_id';
      }

      //alert(strPlainFilterName + ': '  + $('.applied_' + strPlainFilterName).length + '/' + $('.filter_catalog_navigation_' + strPlainFilterName + '_link').length);
      //filter_catalog_navigation_categories_id_link
      if(strFilterName != '' && $('.applied_' + strPlainFilterName).length < $('.filter_catalog_navigation_' + strPlainFilterName + '_link').length)
      {
        if($('#filter_catalog_navigation_link_' + strFilterName).length > 0)
        {
          strExistingClass = $('#filter_catalog_navigation_link_' + strFilterName + ' a').attr('className');
          $('#filter_catalog_navigation_link_' + strFilterName + ' a').addClass('active_filter');

          strClearLinkHTML = '<a href="#" onclick="removeProductFiltersGroup(\'' + strExistingClass + '\'); return false;" class="remove_filter" title="Clear"><span>Clear</span></a>';
          //alert(strFilterName);
          $('#filter_catalog_navigation_' + strExistingClass + '_clear_all').text('');
          $('#filter_catalog_navigation_' + strExistingClass + '_clear_all').append(strClearLinkHTML);

        }
      }
    }
  }

  var strURLCriteria = unescape(self.document.location.hash.substring(1));

  if(strURLCriteria == '')
  {
    //refreshProductFilters('', getProductListingsQuery());
  }
  else
  {
    //showAjaxLoaderPopover();
    //updateFromHash();
    //refreshProductListings('');
  }
}
function refreshProductFiltersNew(strRefreshBasedOn, strQueryString)
{
  $.getJSON('/ajax/refreshFilters' + strQueryString ,
    function (strJSON)
    {
      $('#filters_navigation').html('');
      $('#filters_navigation').append(strJSON);
      //alert('Updated!');
    }
  );
}
var strRefreshBasedOn = ' ';
function refreshProductFilters(strRefreshBasedOn, strQueryString)
{
  //alert('/ajax/refreshFilters' + strQueryString);
  if(!blnRunningFiltersRefresh)
  {
    blnRunningFiltersRefresh = true;
    $.getJSON('/ajax/refreshFilters' + strQueryString ,
      function (strJSON)
      {
        if(strJSON._narrow_tags == 'Y' || $('.filter_title_tags_id:visible').length >= 1)
        {
          $('.filter_catalog_navigation_tags_id_link').addClass('filter_catalog_navigation_link_disabled');
          $.each(strJSON.tags_id, function(i, iTagID) { $('#filter_catalog_navigation_link_tags_id_' + iTagID).removeClass('filter_catalog_navigation_link_disabled'); });
        }
        if(strJSON._narrow_attributes == 'Y' || $('.filter_catalog_navigation_attribute_value_ids_title:visible').length >= 1)
        {
          $('.filter_catalog_navigation_attribute_value_ids_link').addClass('filter_catalog_navigation_link_disabled');
          $.each(strJSON.attribute_value_ids, function(i, iAttributeValueID) { $('#filter_catalog_navigation_link_attribute_value_ids_' + iAttributeValueID).removeClass('filter_catalog_navigation_link_disabled'); });
        }
        if((blnClickedLink && strJSON._criteria.categories_id == undefined) || (!blnClickedLink && strRefreshBasedOn != '' && strRefreshBasedOn != 'categories_id')/* || $('.filter_title_categories_id:visible').length >= 1*/)
        {
          $('.filter_catalog_navigation_categories_id_link').addClass('filter_catalog_navigation_link_disabled');
          $.each(strJSON.categories_id, function(i, iCategoryID) { $('#filter_catalog_navigation_link_categories_id_' + iCategoryID).removeClass('filter_catalog_navigation_link_disabled'); });
        }
        if((blnClickedLink && strJSON._criteria.manufacturer_id == undefined) || (!blnClickedLink && strRefreshBasedOn != '' && strRefreshBasedOn != 'manufacturer_id')/* || $('.filter_title_manufacturer_id:visible').length >= 1*/)
        {
          //alert('UPdating the manufacturer_ids...' + strJSON._criteria.manufacturer_id + ', ' + strRefreshBasedOn + ', ' + blnClickedLink);
          $('.filter_catalog_navigation_manufacturer_id_link').addClass('filter_catalog_navigation_link_disabled');
          $.each(strJSON.manufacturer_id, function(i, iBrandID) { $('#filter_catalog_navigation_link_manufacturer_id_' + iBrandID).removeClass('filter_catalog_navigation_link_disabled');  });
        }
        if((blnClickedLink && strJSON._criteria.rating == undefined) || (!blnClickedLink && strRefreshBasedOn != '' && strRefreshBasedOn != 'tags_id'))
        {
          $('.filter_catalog_navigation_rating_link').addClass('filter_catalog_navigation_link_disabled');
          $.each(strJSON.rating, function(i, iRating) { $('#filter_catalog_navigation_link_rating_' + iRating).removeClass('filter_catalog_navigation_link_disabled'); });
        }
        if((blnClickedLink && strJSON._criteria.price_band_id == undefined) || (!blnClickedLink && strRefreshBasedOn != '' && strRefreshBasedOn != 'price_band_id')/* || $('.filter_title_price_band_id:visible').length >= 1*/)
        {
          $('.filter_catalog_navigation_price_band_id_link').addClass('filter_catalog_navigation_link_disabled');
          $.each(strJSON.price_band_id, function(i, iPriceBandID) { $('#filter_catalog_navigation_link_price_band_id_' + iPriceBandID).removeClass('filter_catalog_navigation_link_disabled'); });
        }
        toggleBlankFilterGroups();
      }
    );
    blnRunningFiltersRefresh = false;
  }
  //addFilterToCookie(strRefreshBasedOn);
}
function getProductListingsQuery()
{
  arrFilters = $('#ajax_' + strFiltersType + '_wrapper').children();

  strQueryString = '?';
  for(i=0; i<arrFilters.length; i++)
  {
    //console.log(arrFilters[i].name+'='+arrFilters[i].value+' '+arrFilters[i].disabled);
    if(arrFilters[i].name != undefined && !arrFilters[i].disabled)
    {
      strQueryString+= arrFilters[i].name + '=' + arrFilters[i].value + '&';
    }
  }
  return strQueryString;
}

var blnRunningFiltersRefresh = false;
var blnRunningRefresh = false;

function refreshProductListings(strRefreshBasedOn)
{
  if(!blnRunningRefresh)
  {
    blnRunningRefresh = true;
    updateFromHash();
    strQueryString = getProductListingsQuery();
    //refreshProductFilters(strRefreshBasedOn, strQueryString);
    //alert('Basedon: '+strRefreshBasedOn+'\n/ajax/refreshProductListings' + strQueryString);
    $.getJSON('/ajax/getProductListings' + strQueryString, function(strJSON)
    {
      toggleBlankFilterGroups();
      $('#middle_column').attr('innerHTML', strJSON);
      attachAjaxToNumPerPage();
      rebuildProductListings();
      changePageTitle();
      $('#ajax_filters_loading').hide();
      $('.quick_buy_trigger').unbind('click');
      initQuickBuy();
      if(typeof fnPostFilterCallback == 'function')fnPostFilterCallback(strJSON);
      if(typeof tb_call == 'function')tb_call();

      if($("a.product_zoom_small").length>0 && typeof showtrail == 'function' && typeof gettrailobjnostyle =='function')
      {
        if(gettrailobjnostyle()===false)
        {
          $("<div id='preview_div'></div>").appendTo($(document));
        }
        $("a.product_zoom_small").mouseover(function(){showtrail($(this).attr("href"),$(this).attr('alt'),450,450);})
                                 .mouseout(function(){hidetrail();});
      }

      $('.hide_after_ajax').hide();
      updateFromHash();
    });
    if(strRefreshBasedOn != '')
    {
      var iNumStillActive = 0;
      $('.' + strRefreshBasedOn).each(function()
      {
        if($(this).hasClass('active_filter')) iNumStillActive++;
      });
      strClearLinkHTML = '';
      if(iNumStillActive > 0)
      {
        strClearLinkHTML = '<a href="#" onclick="removeProductFiltersGroup(\'' + strRefreshBasedOn + '\'); return false;" class="remove_filter" title="Clear"><span>Clear</span></a>';
      }
      $('#filter_catalog_navigation_' + strRefreshBasedOn + '_clear_all').text('');
      $('#filter_catalog_navigation_' + strRefreshBasedOn + '_clear_all').append(strClearLinkHTML);
    }
    blnRunningRefresh = false;
  }
}
function changePageTitle()
{
  try
  {
    if (typeof($('#metatitle').val()) != 'undefined' && $('#metatitle').val() != '')
    {
      document.title = $('#metatitle').val();
    }
    else
    {
      document.title = $('h1').text();
    }
  }
  catch (err)
  {
  }
}

function closeAjax()
{
  $('#ajax_filters_loading').hide();
}

function attachAjaxToNumPerPage()
{
  $('.pagination').show();
  $('#page_view_options > a, .view_all, .view_all > a').unbind('click');
  $('#page_view_options > a, .view_all, .view_all > a').bind('click', function()
  {
    strlinkText = $(this).text();
    strlinkText = strlinkText.replace(/.*\s([0-9]+|all).*/i,'$1');
    if (isNaN(strlinkText))
    {
      $('#ajax_filters_num_per_page').val('all');
      $('#ajax_filters_pages').val('1');
      showAjaxLoaderPopover();
      refreshProductListings('');
      return false;
    }
    else
    {
      $('#ajax_filters_num_per_page').val(strlinkText);
      showAjaxLoaderPopover();
      refreshProductListings('');
      return false;
    }
  });
}

function toggleBlankFilterGroups()
{
  $('.filter_catalog_navigation').show();
  $('.force_hide').hide();
  $('.filter_catalog_navigation').each(function(i, objEl)
  {
    strElementID = objEl.id;
    if(!strElementID.match('_keyword'))
    {
      if($('#' + strElementID + ' > ul > li > div > ul > li.filter_catalog_navigation_link').length == $('#' + strElementID + ' > ul > li > div > ul > .filter_catalog_navigation_link_disabled').length)
      {
        $('#' + strElementID).hide();
      }
    }
  });
}

function rebuildProductListings()
{
  //initQuickBuy();
  $('.pagination a').unbind('click');
  $('.pagination a').bind('click', function()
  {
    var strText = $(this).text();
    strText = strText.toLowerCase();
    strText = strText.replace(/^\s+|\s+$/g,"");
    if(strText.match("next"))
    {
      $('.pagination strong').each(function()
      {
        iCurrentPage = $(this).text();
      });
      strText = parseInt(iCurrentPage)+parseInt(1);
    }
    else if(strText.match("prev"))
    {
      $('.pagination strong').each(function()
      {
        iCurrentPage = $(this).text();
      });
      strText = parseInt(iCurrentPage)-parseInt(1);
    }

    var strHash = self.document.location.hash;
    if(!strHash.match('page'))
    {
      strHash = strHash + ':page' + strText;
    }
    else
    {
      arrBits = strHash.split(':');
      strCurrentPage = null;

      for(i=0; i < arrBits.length; i++)
      {
        if(arrBits[i].match(/page/))
        {
          strCurrentPage = arrBits[i];
        }
      }
      strHash = strHash.replace(strCurrentPage, 'page' + strText);
    }

    self.document.location.hash = strHash;

    $.scrollTo('0px', 750);
    //alert('scroll?!');

    $('#ajax_filters_pages').val(strText);
    //showAjaxLoaderPopover();
    //refreshProductListings('page');
    $.history.load(self.document.location.hash.replace(/#/, ''));
    $('#page_number').remove();
    return false;
  });
}

function removeProductFiltersGroup(strRemoveGroupKey)
{
  strHash = self.document.location.hash;
  arrHashBits = strHash.split(':');
  strApplyAsBase = null;

  switch(strRemoveGroupKey)
  {
    case 'tags_id':
      strApplyAsBase = 't';
      break;
    case 'price_band_id':
      strApplyAsBase = 'b';
      break;
    case 'categories_id':
      strApplyAsBase = 'c';
      break;
    case 'category_parent_id':
      strApplyAsBase = 'p';
      break;
    case 'manufacturer_id':
      strApplyAsBase = 'm';
      break;
    case 'attribute_value_ids':
      strApplyAsBase = 'a';
      break;
  }

  $('#filter_catalog_navigation_title_' + strRemoveGroupKey + ' .active_filter').each(function()
  {
    $(this).removeClass('active_filter');
    removeProductFiltersCriteria($(this).attr('name'), false);
    if(strApplyAsBase != null)
    {
      var iElementId = $(this).attr('id');
      iElementId = iElementId.replace(strRemoveGroupKey + '_', '');
      strApplyAs = strApplyAsBase + iElementId;

      for(var i=0; i<arrHashBits.length; i++)
      {
        if(arrHashBits[i] == strApplyAs || arrHashBits[i] == '#' + strApplyAs)
        {
          strHash = strHash.replace(strApplyAs, '');
        }
      }
    }
  });

  strHash = strHash.replace('::::::::::', ':');
  strHash = strHash.replace(':::::::::', ':');
  strHash = strHash.replace('::::::::', ':');
  strHash = strHash.replace(':::::::', ':');
  strHash = strHash.replace('::::::', ':');
  strHash = strHash.replace(':::::', ':');
  strHash = strHash.replace('::::', ':');
  strHash = strHash.replace(':::', ':');
  strHash = strHash.replace('::', ':');

  if(strHash == ':')
  {
    strHash = '';
  }

  //alert($('.filter_catalog_navigation_link .filter_catalog_navigation_' + strRemoveGroupKey + '_link').length);

  //$('.filter_catalog_navigation_link .filter_catalog_navigation_' + strRemoveGroupKey + '_link').removeClass('active_filter');


  //if(strHash != self.document.location.hash)
  //{
  // Added redirect to blank search when removing tags. Otherwise the url causes reselection - AS
  strTemp = new String(self.document.location);
  if(strTemp.match(/-t[0-9]+$/))
  {
    document.location = '/search/all-products';
  }
  else
  {
    self.document.location.hash = strHash;
  }
 // }

  //showAjaxLoaderPopover();
  //refreshProductListings(strRemoveGroupKey);
}

function removeProductFiltersCriteria(strRemoveKey, blnRunRefresh)
{
  $('#'+strRemoveKey).removeClass('active_filter');

  $('#ajax_filters_wrapper_' + strRemoveKey).remove();
  $('#applied_ajax_filters_' + strRemoveKey).attr('disabled', false);

  if($('#applied_ajax_filters_' + strRemoveKey).hasClass('base_category_id'))
  {
    if($('#applied_ajax_filters_parent_category_id_' + $('#applied_ajax_filters_' + strRemoveKey).val() ).length > 0)
    {
      $('#applied_ajax_filters_' + strRemoveKey).remove();
    }
    else
    {
      $('#applied_ajax_filters_' + strRemoveKey).attr('disabled', true);
    }
  }
  else
  {
    $('#applied_ajax_filters_' + strRemoveKey).remove();
  }

  $('#your_selection_' + strRemoveKey).remove();

  var strID = strRemoveKey;

  arrBits = strRemoveKey.split("_");
  strRemoveKey = '';

  for(var i=0; i<arrBits.length-1; i++)
  {
    if(strRemoveKey != '')
    {
      strRemoveKey+= '_' + arrBits[i];
    }
    else
    {
      strRemoveKey+= arrBits[i];
    }
  }

  if(strRemoveKey == 'categories_id')
  {
    if($('.applied_' + strRemoveKey).length == 0)
    {
      $('.base_category_id').attr('disabled', false);
    }
  }

  var strApplyAs = null;
  var strActualID = strID.replace(strRemoveKey + '_', '');

  switch(strRemoveKey)
  {
    case 'tags_id':
      strApplyAs = 't';
      break;

    case 'price_band_id':
      strApplyAs = 'b';
      break;

    case 'categories_id':
      strApplyAs = 'c';

      if($('.manual_applied_categories_id').length == 0)
      {
        if($('.base_category_id:enabled').length == 0)
        {
          $('.base_category_id').attr('disabled', false);
        }
      }
      break;

    case 'category_parent_id':
      strApplyAs = 'p';

      if($('.manual_applied_categories_id').length == 0)
      {
        if($('.base_category_id:enabled').length == 0)
        {
          $('.base_category_id').attr('disabled', false);
        }
      }
      break;

    case 'manufacturer_id':
      strApplyAs = 'm';
      break;

    case 'attribute_value_ids':
      strApplyAs = 'a';
      break;
  }


  if(strApplyAs != null)
  {

    if(self.document.location.hash != '')
    {
      strID = strID.replace(strRemoveKey + '_', '');
      strHash = self.document.location.hash;
      strHash = strHash.replace(':' + strApplyAs + strID, '');
      strHash = strHash.replace('#' + strApplyAs + strID, '');

      if(strHash == '#')
      {
        strHash = '';
      }

      self.document.location.hash = strHash;
    }


  }

  if($('.active_filter').length == 0 && $('.active_filter_criteria').length == 0)
  {
    $('#catalog_navigation_criteria').hide();
  }

  return false;
}

function applyAjaxSortOrder(strSortValue)
{
  if($('#ajax_filters_wrapper').length > 0)
  {
    strSortValue = strSortValue.replace('?sort=', '');
    if(!isNaN(strSortValue))
    {
      $('#ajax_filters_sortby').val(strSortValue);

      var strHash = self.document.location.hash;

      if(strHash != '')
      {
        var strDivider = ':';
      }
      else
      {
        var strDivider = '';
      }
      if(!strHash.match('sort'))
      {
        strHash = strHash + strDivider + 'sort' + strSortValue;
      }
      else
      {
        arrBits = strHash.split(':');
        strCurrentPage = null;
        for(i=0; i < arrBits.length; i++)
        {
          if(arrBits[i].match(/sort/))
          {
            strCurrentPage = arrBits[i];
          }
        }
        strHash = strHash.replace(strCurrentPage, 'sort' + strSortValue);
        //alert(strHash);
      }

      self.document.location.hash = strHash;

    }
    else
    {
      $('#ajax_filters_sortby').val('');
      showAjaxLoaderPopover();
      refreshProductListings();
    }
  }
  else
  {
    document.location.href = document.location.pathname + strSortValue;
  }
}

function applyAjaxViewType(strViewType)
{
  if(strViewType != "")
  {
    $.cookie('VSViewType', strViewType, {expires: +365, path: '/', domain: window.location.hostname});
  }

  showAjaxLoaderPopover();
  refreshProductListings();
}


var blnClickedLink = false;
var strClickedLink = ' ';
function filtersHistoryCallback(strHash)
{
  //alert(strHash);
  //alert($('.manual_applied').length);
  //alert($('.url_applied').length);

  if(strHash || $('.manual_applied').length > 0 || $('.url_applied').length > 0)
  {
    showAjaxLoaderPopover();
    rebuildCategoriesForHash(strHash);
    refreshProductFilters(strClickedLink, getProductListingsQuery());
    refreshProductListings();
  }
  else if($('.manual_applied').length == 0 && $('.url_applied').length == 0)
  {
    if(blnClickedLink)
    {
      $('.base_category_id').attr('disabled', false);
      rebuildCategoriesForHash(strHash);
      showAjaxLoaderPopover();
      $('a.active_filter').removeClass('active_filter');
      $('.manual_applied').remove();
      $('.url_applied').remove();
      refreshProductFilters(strClickedLink, getProductListingsQuery());
      refreshProductListings();
      blnClickedLink = false;
    }
    else
    {
      // default action on page load
      //rebuildCategoriesForHash(strHash);
      //alert('filtersHistoryCallback 3');
    }
  }
  else
  {
    //alert('fallback, ' + $('.manual_applied').length + ', ' + $('.url_applied').length);
    //alert('filtersHistoryCallback 4');
  }
}
function rebuildCategoriesForHash(strHash){
  blnRebuildCategoriesFromHash = false;

    if(!blnClickedLink)
    {
      blnRebuildCategoriesFromHash = true;
      $('.url_applied').each(function()
      {
        if($(this).hasClass('applied_parent_category_id'))
        {
          //if($('.base_category_id:enabled').length == 1)
          //{
            if(strHash == '')
            {
              $(this).removeClass('url_applied');
              $(this).addClass('base_category_id');
            }
          //}
        }
      });
    }


    $('.manual_applied').remove();
    $('.url_applied').remove();
    updateFromHash();

    //if(strHash == '')
    //{
      pullOutCurrentCategory();
    //}

    if(blnRebuildCategoriesFromHash && strHash)
    {
      //alert('blnRebuildCategoriesFromHash');
      // remove all categories from the Hash we've been passed
      arrHashBits = strHash.split(':');
      $('.base_category_id').attr('disabled', true);
      for(var i=0; i<arrBits.length; i++)
      {
        if(arrBits[i].substr(0,1) == 'c')
        {
          iCategoryID = arrBits[i].substr(1,arrBits[i].length);
          $('#applied_ajax_filters_categories_id_' + iCategoryID).attr('disabled', true);
        }
      }

      // get the new Hash that we've generated in updateFromHash() call
      arrHashBits = location.hash.split(':');
      for(var i=0; i<arrBits.length; i++)
      {
        if(arrBits[i].substr(0,1) == 'c')
        {
          iCategoryID = arrBits[i].substr(1,arrBits[i].length);
          $('#applied_ajax_filters_categories_id_' + iCategoryID).attr('disabled', false);
        }
      }
    }
}/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 * API rewrite by Lauris Buk?is-Haberkorns
 */

(function($) {

function History()
{
	this._curHash = '';
	this._callback = function(hash){};
};

$.extend(History.prototype, {

	init: function(callback) {
		this._callback = callback;
		this._curHash = location.hash;

		if($.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (this._curHash == '') {
				this._curHash = '#';
			}

			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var iframe = $("#jQuery_history")[0].contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = this._curHash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			this._historyBackStack = [];
			this._historyBackStack.length = history.length;
			this._historyForwardStack = [];
			this._isFirst = true;
			this._dontCheck = false;
		}
		this._callback(this._curHash.replace(/^#/, ''));
		setInterval(this._check, 100);
	},

	add: function(hash) {
		// This makes the looping function do something
		this._historyBackStack.push(hash);

		this._historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this._isFirst = true;
	},

	_check: function() {
		if($.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != $.history._curHash) {

				location.hash = current_hash;
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));

			}
		} else if ($.browser.safari) {
			if (!$.history._dontCheck) {
				var historyDelta = history.length - $.history._historyBackStack.length;

				if (historyDelta) { // back or forward button has been pushed
					$.history._isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) $.history._historyForwardStack.unshift($.history._historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) $.history._historyBackStack.push($.history._historyForwardStack.shift());
					}
					var cachedHash = $.history._historyBackStack[$.history._historyBackStack.length - 1];
					if (cachedHash != undefined) {
						$.history._curHash = location.hash;
						$.history._callback(cachedHash);
					}
				} else if ($.history._historyBackStack[$.history._historyBackStack.length - 1] == undefined && !$.history._isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						$.history._callback(document.URL.split('#')[1]);
					} else {
						$.history._callback('');
					}
					$.history._isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != $.history._curHash) {
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));
			}
		}
	},

	load: function(hash) {
		var newhash;

		if ($.browser.safari) {
			newhash = hash;
		} else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		this._curHash = newhash;

		if ($.browser.msie) {
			var ihistory = $("#jQuery_history")[0]; // TODO: need contentDocument?
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			this._callback(hash);
		}
		else if ($.browser.safari) {
			this._dontCheck = true;
			// Manually keep track of the history values for Safari
			this.add(hash);

			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {$.history._dontCheck = false;};
			window.setTimeout(fn, 200);
			this._callback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  this._callback(hash);
		}
	}
});

$(document).ready(function() {
	$.history = new History(); // singleton instance
});

})(jQuery);