/** Comparison Table Functionality **/

var tableLoaded = false;

var lastRequested = new Array;

var tableColumns = new Array;

var tableColumnStart = new Array;

var tableColumnMax = new Array;

var loadingTimeoutId;

function loadTable(elementId, tableId, userHash, page, order, direction, column, value, params, noHistory)
{
  
  if(noHistory == null)
    noHistory = false;

  if(elementId == 'comparisonTable_'+tableId)
  {

    if(noHistory == false)
    {
      $.history.callback = function ( reinstate, cursor ) {
        if(reinstate == undefined)
        {
          loadTable(elementId,
                    tableId,
                    userHash,
                    1, 
                    null,
                    null,
                    null,
                    null,
                    null,
                    true);
        }
        else
        {
          loadTable(reinstate.elementId,
                    reinstate.tableId,
                    reinstate.userHash,
                    reinstate.pageId,
                    reinstate.lastRequestedO,
                    reinstate.lastRequestedD,
                    reinstate.lastRequestedC,
                    reinstate.lastRequestedV,
                    null,
                    true
          );
        }
        window.scrollTo(0,0);
      } 

      $.history({
                 'elementId':elementId,
                 'tableId':tableId,
                 'userHash':userHash,
                 'pageId':page,
                 'lastRequestedO':order,
                 'lastRequestedD':direction,
                 'lastRequestedC':column,
                 'lastRequestedV':value
                });

      }
  }

  if(elementId === null || elementId === undefined)
  {
    unexpectedError();
    return false;
  }

  if(lastRequested[tableId] === undefined)
    lastRequested[tableId] = new Array();
  
  urlParts = location.href.split("?");
  urlParts = urlParts[0].split("#");

  var tableRequest = urlParts[0]+'?t='+tableId;

  tableLoaded = false;

  if(userHash != null)
  {
    tableRequest =  tableRequest + '&u=' + userHash;
    lastRequested[tableId]['u'] = userHash;
  }

  if(page != null)
    tableRequest = tableRequest + '&page=' + page;

  if(order != null)
  {
    tableRequest = tableRequest + '&o=' + order;
    lastRequested[tableId]['o'] = order;
  }

  if(direction != null)
  {
    tableRequest = tableRequest + '&d=' + direction;
    lastRequested[tableId]['d'] = direction
  }

  if(column != null)
  {
    tableRequest = tableRequest + '&c=' + column;
    lastRequested[tableId]['c'] = column;
  }
  else if(lastRequested[tableId]['c'] != null)
    tableRequest = tableRequest + '&c=' + lastRequested[tableId]['c'];

  if(value != null)
  {
    tableRequest =  tableRequest + '&v=' + value;
    lastRequested[tableId]['v'] = value;
  }
  else if(lastRequested[tableId]['v'] != null)
    tableRequest = tableRequest + '&v=' + lastRequested[tableId]['v'];

  if(params != null)
    tableRequest = tableRequest + '&' + params;

  $.ajax({ 
    type: "GET", 
    url: tableRequest,
    cache: false,
    error: function() { unexpectedError(); },
    success: function(response)
    {
      $('#'+elementId).html(response);

      tableLoaded = true;

      if(compareProducts[tableId])
      {
        updateCompareStatus(tableId);

        var elements = document.getElementById(elementId).getElementsByTagName('input');
        for( i=0; i < elements.length; i++ )
        {
          if(elements[i].type == 'checkbox')
          {
            var splitId = elements[i].id.split('_');
            
            if(splitId[4] && !isNaN(splitId[4]))
            {
              if(compareProducts[tableId].indexOf(parseFloat(splitId[4])) != -1)
              {
                addRemoveCompareProduct(tableId, parseFloat(splitId[4]), elements[i].id, true);
              }
            }
          }
        }
      }
      
      if(elementId == 'comparisonTable_'+tableId)
      {
        if(tableColumns[tableId] && tableColumnStart[tableId])
          scrollTableColumns(tableId, 'none');

        hideOverlay();
  
        window.scrollTo(0,0);
      }

      floatingTableHeaderCreate();
    }
  });
}

function pageTable(tableId, userHash, pageId, loadingText)
{
  if(lastRequested[tableId] === undefined)
    lastRequested[tableId] = new Array();
  
  if(loadingText == null)
    showLoadingOverlay('Loading table...');
  else
    showLoadingOverlay(loadingText);

  loadTable('comparisonTable_'+tableId,
            tableId,
            userHash,
            pageId,
            lastRequested[tableId]['o'],
            lastRequested[tableId]['d'],
            lastRequested[tableId]['c'],
            lastRequested[tableId]['v'],
            null
            );

  cycleBanner();
}

function reorderTable(tableId, userHash, order, direction)
{
  showLoadingOverlay('Reordering...');

  loadTable('comparisonTable_'+tableId, tableId, userHash, 1, order, direction);
}

function executeTableLoaded(code)
{
  if(tableLoaded == true)
  {
    eval(code);
    return true;
  }
  else
  {
    setTimeout("executeTableLoaded(\""+code+"\")",250);
    return false;
  }
}

function loadProviderResults(tableId, userHash, rowId, providerId, event)
{
  var productTbody = document.getElementById('table'+tableId+'_row_'+rowId+'_products');

  if(productTbody === null || productTbody === undefined)
  {
    unexpectedError();
    return false;
  }

  $('#table'+tableId+'_row_'+rowId+' .moreInfoText').toggle();
  $('#table'+tableId+'_row_'+rowId+' .iconCompareExpand').toggle();
  $('#table'+tableId+'_row_'+rowId).toggleClass('dataRowProviderSelected');
  
  if(productTbody.innerHTML != '')
  {
    $('#table'+tableId+'_row_'+rowId+'_products').toggle();
    scrollTableColumns(tableId, 'none');
  }
  else
  {
    var tempDiv = document.getElementById('tempdiv_'+tableId+'_row_'+rowId);

    if(!tempDiv)
    {
      var tempDiv = document.createElement('div');
      tempDiv.style.display = 'none';
      tempDiv.id = 'tempdiv_'+tableId+'_row_'+rowId;
    }

    tempDiv.innerHTML = '';

    document.body.appendChild(tempDiv);

    if(lastRequested[tableId] === undefined)
      lastRequested[tableId] = new Array();

    var loadingRow = document.createElement("tr")
    loadingRow.className="dataRow";
    loadingRow.id = "loadingRow_"+tableId+"_"+rowId;
    
    var td1 = document.createElement("td");
    td1.innerHTML = "&nbsp;";
    td1.className="compareTickBoxCell";
    
    var td2 = document.createElement("td");
    td2.innerHTML = '<img src="/images/common/icon-loading-small.gif" alt="Loading">';
    td2.className="dataCell productImageCell";
    td2.style.textAlign="center";
    td2.colSpan = 100;

    //loadingRow.appendChild(td1);
    loadingRow.appendChild(td2);
    productTbody.appendChild(loadingRow);

    loadTable('tempdiv_'+tableId+'_row_'+rowId,
              tableId,
              userHash,
              null, 
              lastRequested[tableId]['o'],
              lastRequested[tableId]['d'],
              lastRequested[tableId]['c'],
              lastRequested[tableId]['v'],
              'p='+providerId
              );
    
    setTimeout("executeTableLoaded(\"insertProviderResults("+tableId+", "+rowId+")\")",250);

  }

  if(event != undefined)
    disableParentClick(event);
}

function insertProviderResults(tableId, rowId)
{
  var productTbody = document.getElementById('table'+tableId+'_row_'+rowId+'_products');

  var tempDiv = document.getElementById('tempdiv_'+tableId+'_row_'+rowId);

  if((tempDiv.firstChild === null || tempDiv.firstChild === undefined))
  {
    unexpectedError();
    return false;
  }

  var productRows = tempDiv.firstChild.rows;

  while (productRows.length > 0)
    productTbody.appendChild(productRows[0]);

  $('#loadingRow_'+tableId+'_'+rowId).hide();

  scrollTableColumns(tableId, 'none');

  document.body.removeChild(tempDiv);
            
}

function expandProviderName(element)
{
  if(element.style.width == 'auto')
    element.style.width = '140px';
  else
    element.style.width = 'auto';
}

function scrollTableColumns(tableId, direction, event)
{

  if(tableColumnStart[tableId] == undefined || tableColumns[tableId] == undefined || tableColumnMax[tableId] == undefined)
    return false;

  var originalTableColumnStart = tableColumnStart[tableId];

  if(direction == 'left')
  {
    if((tableColumnStart[tableId] - 1) >= 0)
      tableColumnStart[tableId]--;
  }
  else if(direction == 'right')
  {
    if((tableColumnStart[tableId] + 1) <= (tableColumns[tableId].length - tableColumnMax[tableId]))
      tableColumnStart[tableId]++;
  }

  for( i=0; i < tableColumns[tableId].length; i++ )
  {
    if((i < tableColumnStart[tableId]) || (i > (tableColumnStart[tableId] + tableColumnMax[tableId] - 1)))
      $('#table'+tableId+'_table .tableColumn'+tableColumns[tableId][i]+':visible').hide();
    else
      $('#table'+tableId+'_table .tableColumn'+tableColumns[tableId][i]+'').show();
  }
    
  if(tableColumnStart[tableId] == 0)
    $('#table'+tableId+'_table .columnScrollCellLeft img:visible').hide();
  else
    $('#table'+tableId+'_table .columnScrollCellLeft img:hidden').show();

  if((tableColumnStart[tableId] + tableColumnMax[tableId]) == (tableColumns[tableId].length))
    $('#table'+tableId+'_table .columnScrollCellRight img:visible').hide();
  else
    $('#table'+tableId+'_table .columnScrollCellRight img:hidden').show();

   if(event != undefined)
     disableParentClick(event);

  floatingTableHeaderCreate();
}

/* Compare Functionality */

var compareProducts = new Array;

function addRemoveCompareProduct(tableId, productId, elementId, forceTick, event)
{
  if(compareProducts[tableId] == undefined)
    compareProducts[tableId] = new Array();

  if(!forceTick)
    forceTick = false;

  if(forceTick)
    document.getElementById(elementId).checked = true;

  if(document.getElementById(elementId).checked)
  {
    if(compareProducts[tableId].indexOf(productId) == -1)
      compareProducts[tableId].push(productId);
  }
  else
    compareProducts[tableId].splice(compareProducts[tableId].indexOf(productId), 1);

  updateCompareStatus(tableId);

  if(event != undefined)
     disableParentClick(event);
}

function removeAllSelectedProducts(tableId, fromOverlay)
{
  if(fromOverlay) 
  {
    $('#compareProductResults').hide();
    $('#compareProductEdit_noProducts').show();
  }

  compareProducts[tableId] = new Array;
  updateCompareStatus(tableId);

  $('#comparisonTable_'+tableId+' input[type=\'checkbox\']').attr('checked','');
}

function editSelectedProducts(tableId)
{
  if(compareProducts[tableId] && compareProducts[tableId].length > 0)
  {
    var url = '/overlay/compare-edit-products.htm?t='+tableId;

    for (var i=0, len=compareProducts[tableId].length; i<len; ++i)
      url = url+'&p['+i+']='+compareProducts[tableId][i];

    loadOverlay(url, null, 750, 400, true);
  }
}

function updateCompareStatus(tableId)
{
  if(compareProducts[tableId] && document.getElementById('table_'+tableId+'_compareStatus'))
  {
    if(compareProducts[tableId].length > 0)
    {
      document.getElementById('table_'+tableId+'_compareStatus').innerHTML = 'You have selected <b>'+compareProducts[tableId].length+'</b> products to compare.';
      $('#table_'+tableId+'_compareLinks').show();
    }
    else
    {
      document.getElementById('table_'+tableId+'_compareStatus').innerHTML = '';
      $('#table_'+tableId+'_compareLinks').hide();
    }
  }
}

function doCompare(subcatGroupId, tableId, userTableHash)
{
  if(compareProducts[tableId] && compareProducts[tableId].length > 1)
  {
    xmlDocContents = '';
    xmlDocContents += '<SubcatGroupId>'+subcatGroupId+'</SubcatGroupId>';
    xmlDocContents += '<BaseTableId>'+tableId+'</BaseTableId>';
    
    if(userTableHash != null)
      xmlDocContents += '<BaseTableHash>'+userTableHash+'</BaseTableHash>';

    xmlDocContents += '<RestrictByProductId>';

    for (var i=0, len=compareProducts[tableId].length; i<len; ++i)
    {
      if(i != 0)
        xmlDocContents += '||';

      xmlDocContents += compareProducts[tableId][i];
    }

    xmlDocContents += '</RestrictByProductId>';
    advancedSearchSendData(xmlDocContents);
  }
  else
    errorBox('Compare Products', '<p>You must select at least two products to compare.</p><p>Please go <a href="javascript:hideOverlay();">back</a> and select more products.</p>');
}

function removeSelectedProduct(tableId, productId)
{
  var lastElementId = null;

  $('#comparisonTable_'+tableId+' input[id*=\'prd_'+productId+'\']').attr('checked','');
  $('#comparisonTable_'+tableId+' input[id*=\'prd_'+productId+'\']:first').each(function (i) { lastElementId = this.id });

  addRemoveCompareProduct(tableId, productId, lastElementId);
  
  $('#compareProductEdit_'+productId).hide();

  if(compareProducts[tableId].length == 0)
  {
    $('#compareProductEdit_noProducts').show();
    $('#compareProductResults').hide();
  }
}

function loadSimpleSearch()
{
  $('#simpleSearchBox .searchToggle').toggle();
  $('#advancedSearchContent').hide();
  $('#simpleSearchBox .searchBox').css('position','absolute').css('width','450px');
  $('#searchAdditionalOptionsPromo').show();
}

/* Advanced Search */
var advancedSearchContents = '';

function loadAdvancedSearch(tableIdOverride, tableHashOverride, xmlErrors)
{
  if(typeof(thisSubcatGroupId) == "undefined")
    unexpectedError();
  else if(typeof(thisTableId) == "undefined")
    unexpectedError();
  else if(typeof(thisTableHash) == "undefined")
    unexpectedError();
  else if(typeof(thisSectionSearchPage) == "undefined")
    unexpectedError();
  else
  {
    if($('#advancedSearchContent').html() != '')
    {
      if($('#advancedSearchContent:hidden').length == 1 && $('#simpleSearchBox .textBox:hidden').length != 1)
      {
        $('#simpleSearchBox .searchToggle').toggle();
        $('#advancedSearchSummary').addClass('advancedSearchSummaryFaded');
        $('#simpleSearchBox .searchBox').css('width','950px').css('position','static');
        $('#advancedSearchSummary .tableResultsSearchCriteria').hide();
      }
      else
      {
        $('#advancedSearchContent').slideToggle();
        $('#advancedSearchSummary .tableResultsSearchCriteria').slideUp();
        $('#advancedSearchSummary').toggleClass('advancedSearchSummaryFaded');
      }

      $('#searchAdditionalOptions').hide();
      $('#searchAdditionalOptionsPromo').hide();
    }
    else
    {      
      if($('#simpleSearchBox .textBox:hidden').length != 1)
      {
        $('#advancedSearchContent').css('height',$('#simpleSearchBox .searchOptions').height()+$('#searchAdditionalOptionsPromo').height());
        $('#simpleSearchBox .searchToggle').toggle();
        $('#simpleSearchBox .searchBox').css('width','950px').css('position','static');
        $('#advancedSearchContent').animate({height:'230px'}, 500, function(){ if(advancedSearchContents!='') { $('#advancedSearchContent').html(advancedSearchContents).css('height','auto'); if(xmlErrors != null) advancedSearchHandleErrors(xmlErrors); } });
        $('#advancedSearchSummary').addClass('advancedSearchSummaryFaded');
        $('#advancedSearchSummary .tableResultsSearchCriteria').hide();
      }
      else
      {
        $('#advancedSearchContent').animate({height:'230px'}, 500, function(){ if(advancedSearchContents!='') { $('#advancedSearchContent').html(advancedSearchContents).css('height','auto'); if(xmlErrors != null) advancedSearchHandleErrors(xmlErrors); } });
        $('#advancedSearchSummary').addClass('advancedSearchSummaryFaded');
        $('#advancedSearchSummary .tableResultsSearchCriteria').slideUp();
      }

      $('#searchAdditionalOptions').slideUp();
      $('#searchAdditionalOptionsPromo').hide();
      
      loadAdvancedSearchContent(tableIdOverride, tableHashOverride, xmlErrors);
    }
  }
}

function loadAdvancedSearchContent(tableIdOverride, tableHashOverride, xmlErrors)
{
  $('#advancedSearchContent').html('<p align="center" style="margin-top:20px; font-weight:bold;"><img src="/images/common/icon-loading.gif"><br />Loading...</p>');

  if(tableIdOverride != null)
    var requestUrl = '/overlay/power-search.htm?s='+thisSubcatGroupId+'&t='+tableIdOverride;
  else
    var requestUrl = '/overlay/power-search.htm?s='+thisSubcatGroupId+'&t='+thisTableId;

  if(tableHashOverride != null)
    requestUrl = requestUrl + '&u='+tableHashOverride;
  else if(thisTableHash != null)
    requestUrl = requestUrl + '&u='+thisTableHash;

  $.ajax({ 
     type: "GET", 
     url: requestUrl,
     cache: false,
     error: function() { unexpectedError(); },
     success: function(response)
     {
       if($('#advancedSearchContent').queue().length == 0)
       {
         $('#advancedSearchContent').html(response).css('height','auto');

         if(xmlErrors != null)
           advancedSearchHandleErrors(xmlErrors);
       }
       else
         advancedSearchContents = response;
     } 
   });
}

function advancedSearchCompaniesToggle()
{
  $('#searchGroup_company .searchCompanyContentsHidden').toggle();
  $('#searchGroup_company .searchCompanyMore').toggle();
}

function advancedSearchCompaniesCount()
{
  if($('#advancedSearchAllCompanies').attr('checked') == true)
  {
    $('#searchGroup_company .advancedSearchCompanyOptions input').removeAttr('checked');
    $('#searchGroup_company #advancedSearchAllCompanies').attr('checked','checked');
    $('#searchGroup_company .searchGroupHeaderSummary .companyWord span').hide();
    $('#searchGroup_company .searchGroupHeaderSummary .productCountContainer').hide();
    $('#searchGroup_company .searchGroupHeaderSummary .companyCountContainer').show();
    $('#searchGroup_company .searchGroupHeaderSummary .companyCount').html('all');
    $('#searchGroup_company .searchGroupHeaderSummary .companyWord .plural').show();
  }
  else if($('#advancedSearchSelectedProducts').attr('checked') == true)
  {
    $('#searchGroup_company .searchGroupHeaderSummary .productCountContainer').show();
    $('#searchGroup_company .searchGroupHeaderSummary .companyCountContainer').hide();
    $('#searchGroup_company .searchGroupHeaderSummary .productWord span').hide();
    $('#searchGroup_company .advancedSearchCompanyOptions input').removeAttr('checked');
    $('#searchGroup_company #advancedSearchSelectedProducts').attr('checked','checked');
    $('#searchGroup_company .searchCompanyContents .companySelect').removeAttr('checked');

    var productCount = $('#searchGroup_company .searchProductContents .productSelect:checked').length;

    if(productCount == 0)
      advancedSearchCompanyAllCompanies();
    else
    {
      $('#searchGroup_company .advancedSearchCompanyOptions input').removeAttr('checked');
      $('#searchGroup_company #advancedSearchSelectedProducts').attr('checked','checked');

      if(productCount == 1)
        $('#searchGroup_company .searchGroupHeaderSummary .productWord .singular').show();
      else 
        $('#searchGroup_company .searchGroupHeaderSummary .productWord .plural').show();

      $('#searchGroup_company .searchGroupHeaderSummary .productNumberCount').html(productCount);
    }
  }
  else
  {
    $('#searchGroup_company .searchGroupHeaderSummary .productCountContainer').hide();
    $('#searchGroup_company .searchGroupHeaderSummary .companyCountContainer').show();
    $('#searchGroup_company .searchGroupHeaderSummary .companyWord span').hide();

    var companyCount = $('#searchGroup_company .searchCompanyContents .companySelect:checked').length;

    if(companyCount == 0)
      advancedSearchCompanyAllCompanies();
    else
    {
      $('#searchGroup_company .advancedSearchCompanyOptions input').removeAttr('checked');
      $('#searchGroup_company #advancedSearchSelectedCompanies').attr('checked','checked');

      if(companyCount == 1)
        $('#searchGroup_company .searchGroupHeaderSummary .companyWord .singular').show();
      else 
        $('#searchGroup_company .searchGroupHeaderSummary .companyWord .plural').show();

      $('#searchGroup_company .searchGroupHeaderSummary .companyCount').html(companyCount);
    }
  }

  if($('#advancedSearchGroupByProvider').attr('checked') == true)
    $('#searchGroup_company .searchGroupHeaderSummary .companySummary').show();
  else
    $('#searchGroup_company .searchGroupHeaderSummary .companySummary').hide();
}

function advancedSearchCompanyAllCompanies()
{
  $('#searchGroup_company .searchCompanyContents .companySelect').removeAttr('checked');
  $('#searchGroup_company .searchCompanyContents .productSelect').removeAttr('checked');
  $('#searchGroup_company .advancedSearchCompanyOptions input').removeAttr('checked');
  $('#searchGroup_company #advancedSearchAllCompanies').attr('checked','checked');
  advancedSearchCompaniesCount();
}

function advancedSearchCompanySelectedCompanies()
{
  $('#searchGroup_company .advancedSearchCompanyOptions input').removeAttr('checked');
  $('#searchGroup_company #advancedSearchSelectedCompanies').attr('checked','checked');
  $('#searchGroup_company .searchCompanyContents .productSelect').removeAttr('checked');
  $('#searchGroup_company .searchGroupHeaderSummary .productCountContainer').hide();
  $('#searchGroup_company .searchGroupHeaderSummary .companyCountContainer').show();

  if($('#searchGroup_company .searchProductContents .companySelect:checked').length == 0)
  {
    $('#searchGroup_company .searchGroupHeaderSummary .companyWord span').hide();
    $('#searchGroup_company .searchGroupHeaderSummary .companyCount').html('all');
    $('#searchGroup_company .searchGroupHeaderSummary .companyWord .plural').show();
  }
}

function advancedSearchCompanySelectedProducts()
{
  $('#searchGroup_company .advancedSearchCompanyOptions input').removeAttr('checked');
  $('#searchGroup_company #advancedSearchSelectedProducts').attr('checked','checked');
  $('#searchGroup_company .searchCompanyContents .companySelect').removeAttr('checked');
  $('#searchGroup_company .searchGroupHeaderSummary .productCountContainer').show();
  $('#searchGroup_company .searchGroupHeaderSummary .companyCountContainer').hide();

  if($('#searchGroup_company .searchProductContents .productSelect:checked').length == 0)
  {
    $('#searchGroup_company .searchGroupHeaderSummary .productWord span').hide();
    $('#searchGroup_company .searchGroupHeaderSummary .productNumberCount').html('all');
    $('#searchGroup_company .searchGroupHeaderSummary .productWord .plural').show();
  }
}

function advancedSearchToggleGroup(groupid, forceDirection)
{
  /*if(ie)
    jQuery.fx.off = true;*/

  if(typeof(groupid) != 'number')
    groupid = groupid.replace('searchGroup_','');

  if(typeof(forceDirection) != 'undefined')
  {
    if(forceDirection == 'up')
    {
      $('#searchGroup_'+groupid+' .searchGroupContents').slideUp('normal');
      $('#searchGroup_'+groupid+' .searchGroupHeader').removeClass('searchGroupHeaderSelected');
    }
    else if(forceDirection == 'down')
    {
      $('#searchGroup_'+groupid+' .searchGroupContents').slideDown('normal');
      $('#searchGroup_'+groupid+' .searchGroupHeader').addClass('searchGroupHeaderSelected');
    }
  }
  else
  {
    $('#searchGroup_'+groupid+' .searchGroupContents').slideToggle('normal');
    $('#searchGroup_'+groupid+' .searchGroupHeader').toggleClass('searchGroupHeaderSelected');
  }

  /*if(ie)
    jQuery.fx.off = false;*/
}

function advancedSearchEnableAttribute(attribute, group, force)
{
  if(typeof(force) != 'undefined' && force === true)
  {
    if($('#searchAttribute_'+attribute+' input[class=attributeSelect]').is(':checked'))
      $('#searchAttribute_'+attribute+' input[class=attributeSelect]').removeAttr('checked');
    else
      $('#searchAttribute_'+attribute+' input[class=attributeSelect]').attr('checked','checked');
  }
   
  if($('#searchAttribute_'+attribute+' input[class=attributeSelect]').is(':checked'))
    $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions').show();
  else
    $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions').hide();

  advancedSearchSelectNoFilter(attribute, group);
  advancedSearchCheckCounts(group);
}

function advancedSearchSelectFilter(attribute, group)
{
  $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions .noFilterRadio').removeAttr('checked');
  $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions .filterRadio').attr('checked','checked');
  advancedSearchCheckCounts(group);
}

function advancedSearchSelectNoFilter(attribute, group)
{
  $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions input[type=text]').removeAttr('value');
  $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions select option').removeAttr('selected');
  $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions input').removeAttr('checked');
  $('#searchAttribute_'+attribute+' .searchAttributeFilterOptions .noFilterRadio').attr('checked','checked');
  $('#searchAttribute_'+attribute).removeClass('searchAttributeContentsError');

  advancedSearchCheckCounts(group);
}

function advancedSearchCheckFilter(attribute, group)
{
  if(advancedSearchGetSearchValues(attribute) == '')
    advancedSearchSelectNoFilter(attribute, group);
}

function advancedSearchCheckCounts(group)
{
  var columnCount = $('#searchGroup_'+group+' .attributeSelect:checked').length;
  var filterCount = $('#searchGroup_'+group+' .filterRadio:checked').length;
  var oldFilterCount = $('#searchGroup_'+group+' .searchGroupHeaderSummary .filterCount').html();

  if(columnCount == 0)
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .columnCount').html('no');
  else
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .columnCount').html(columnCount);

  $('#searchGroup_'+group+' .searchGroupHeaderSummary .columnWord span').hide();
  
  if(columnCount == 0 || columnCount > 1)
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .columnWord .plural').show();
  else
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .columnWord .singular').show();

  if(filterCount == 0)
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .filterCount').html('no');
  else
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .filterCount').html(filterCount);

    $('#searchGroup_'+group+' .searchGroupHeaderSummary .filterWord span').hide();
  
  if(filterCount == 0 || filterCount > 1)
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .filterWord .plural').show();
  else
    $('#searchGroup_'+group+' .searchGroupHeaderSummary .filterWord .singular').show();
}

function advancedSearchGetSearchValues(attribute)
{
  attributeSearchValue = '';

  $('#searchAttribute_'+attribute+' .searchValue').each(function(i)
  {
    if($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox')
    {
      if($(this).attr('checked') == true)
      {
        if(attributeSearchValue != '')
          attributeSearchValue += '||';

        attributeSearchValue += $(this).val();    
      }
    }
    else
    {
      if(attributeSearchValue != '')
        attributeSearchValue += '||';

      attributeSearchValue += $(this).val();    
    }            
  });

  return attributeSearchValue;
}

function advancedSearchSubmit()
{
  var xmlDocContents = '';
  
  $('#advancedSearchContent .searchAttributeContents').removeClass('searchAttributeContentsError');
  $('#advancedSearchContent .searchAttributeContents .standardInputError').removeClass('standardInputError');
  $('#advancedSearchContent #advancedSearchMessage .advancedSearchError').hide();
  $('#advancedSearchContent #advancedSearchMessage .advancedSearchTitle').show();

  $('#advancedSearchContent .searchGroupContents').slideUp();
  $('#advancedSearchContent .searchGroupHeader').removeClass('searchGroupHeaderSelected');

  if($('#advancedSearchForm #advancedSearchSubcatGroup').length > 0)
    xmlDocContents += '<SubcatGroupId>'+$('#advancedSearchForm #advancedSearchSubcatGroup').val()+'</SubcatGroupId>';

  if($('#advancedSearchForm #advancedSearchTableId').length > 0 && $('#advancedSearchForm #advancedSearchTableId').val() != '')
    xmlDocContents += '<UserTableId>'+$('#advancedSearchForm #advancedSearchTableId').val()+'</UserTableId>';

  if($('#advancedSearchForm #advancedSearchTableHash').length > 0 && $('#advancedSearchForm #advancedSearchTableHash').val() != '')
    xmlDocContents += '<UserTableHash>'+$('#advancedSearchForm #advancedSearchTableHash').val()+'</UserTableHash>';

  if($('#advancedSearchForm #advancedSearchOrderBy').length > 0 && $('#advancedSearchForm #advancedSearchOrderBy').val() != '')
    xmlDocContents += '<OrderByAttribute>'+$('#advancedSearchForm #advancedSearchOrderBy').val()+'</OrderByAttribute>';

  if($('#advancedSearchForm #advancedSearchResultsPerPage').length > 0)
    xmlDocContents += '<ResultsPerPage>'+$('#advancedSearchForm #advancedSearchResultsPerPage').val()+'</ResultsPerPage>';

  if($('#advancedSearchForm #advancedSearchGroupByProvider').length > 0)
    if($('#advancedSearchForm #advancedSearchGroupByProvider').attr('checked') == true)
      xmlDocContents += '<GroupByProvider>true</GroupByProvider>';
    else
      xmlDocContents += '<GroupByProvider>false</GroupByProvider>';

  if($('#advancedSearchForm #advancedSearchSelectedProducts').attr('checked') == true && $('#advancedSearchForm #searchGroup_company .productSelect:checked').length != 0)
  {
    var product = '';

    $('#advancedSearchForm #searchGroup_company .productSelect:checked').each(function(i) {
      if(product != '')
        product += '||';
      
      product += $(this).val();
    });
    
    if(product != '')
      xmlDocContents += '<RestrictByProductId>'+product +'</RestrictByProductId>';
  }
  else if($('#advancedSearchForm #advancedSearchSelectedCompanies').attr('checked') == true && $('#advancedSearchForm #searchGroup_company .companySelect:checked').length != 0)
  {
    var provider = '';

    $('#advancedSearchForm #searchGroup_company .companySelect:checked').each(function(i) {
      if(provider != '')
        provider += '||';
      
      provider += $(this).val();
    });
    
    if(provider != '')
      xmlDocContents += '<RestrictByProviderId>'+provider +'</RestrictByProviderId>';
  }

  $('#advancedSearchForm .searchAttributeContents').each(function(i) { 
    if($(this).children('.attributeSelect').attr('checked') == true)
    {
      attribute = $(this).attr('id').replace('searchAttribute_','');
      xmlDocContents += '<SearchColumn><AttributeId>'+attribute+'</AttributeId>';

      if($(this).find('.filterRadio').attr('checked') == true)
      { 
        attributeSearchValue = advancedSearchGetSearchValues(attribute);
        
        if(attributeSearchValue != '')
          xmlDocContents += '<SearchValue>'+attributeSearchValue+'</SearchValue>';
      }
      
      xmlDocContents += '</SearchColumn>';
    }
  });

  advancedSearchSendData(xmlDocContents);
}

function advancedSearchSendData(xmlDocContents)
{
  if(typeof(thisSectionSearchPage) == "undefined")
  {
    unexpectedError();
    return false;
  }

  xmlDocContents = xmlDocContents.replace('&','&amp;');

  var xmlDoc = jQuery.createXMLDocument('<SearchRequest>'+xmlDocContents+'</SearchRequest>');

  showLoadingOverlay('Sending search criteria...');
  var loadingText = setTimeout("showLoadingOverlay('Searching products...');", 300);

  $.ajax({
		url: '/php/services/power_search_xml.php',
    type: "POST",
    async: true,
		processData: false,
		contentType: "text/xml",
		data: xmlDoc,
    cache: false,
		dataType: "xml",
    error: function() { clearTimeout(loadingText); unexpectedError(); },
		success: function(xml)
    {
      clearTimeout(loadingText);

      var noAttributeError = true;
      var errorText = '';

      if($(xml).find('ErrorFound').text() == 'true')
      {
        if($('#advancedSearchContent').html() == '')
          loadAdvancedSearch($(xml).find('UserTableId').text(),$(xml).find('UserTableHash').text(), xml);
        else
          advancedSearchHandleErrors(xml)
      }
      else if($(xml).find('ErrorFound').text() == 'false')
      { 
        if($(xml).find('UserTableId').length == 0)
          unexpectedError();
        if($(xml).find('UserTableHash').length == 0)
          unexpectedError();
        else
        {
          showLoadingOverlay('Loading table...');

          var tableUrl = thisSectionSearchPage+'?t='+$(xml).find('UserTableId').text()+'&u='+$(xml).find('UserTableHash').text();

          if(window.location.href.indexOf(tableUrl) == -1)
            window.location.href = tableUrl;
          else  
          {
            loadTable('comparisonTable_'+$(xml).find('UserTableId').text(), $(xml).find('UserTableId').text(),$(xml).find('UserTableHash').text(), null, null, null, null, null, null);
            
            $('#advancedSearchContent').slideUp();
            $('#advancedSearchSummary .tableResultsCount .resultsCount').html($(xml).find('TotalResults').text());

            var companyWordDisplay = false;
            var subjectWordPlural = false;
            var companyWordPlural = false;
            var moreWordPlural = false;

            if($('#advancedSearchForm #advancedSearchGroupByProvider').length > 0 && $('#advancedSearchForm #advancedSearchGroupByProvider').attr('checked') == true)
            {
              companyWordDisplay = true;
              subjectWordPlural = false;
  
              if($(xml).find('TotalResults').text() == 1)
              {
                companyWordPlural = false;
                moreWordPlural = true;
              }
              else
              {
                companyWordPlural = true;
                moreWordPlural = false;
              }
            }
            else
            {
              companyWordDisplay = false;
              companyWordPlural = false;

              if($(xml).find('TotalResults').text() == 1)
              {
                subjectWordPlural = false;
                moreWordPlural = true;
              }
              else
              {
                subjectWordPlural = true;
                moreWordPlural = false;
              }
            }

            if(companyWordDisplay) 
              $('#advancedSearchSummary .tableResultsCount .companyWord').show();
            else
              $('#advancedSearchSummary .tableResultsCount .companyWord').hide();
            
            $('#advancedSearchSummary .tableResultsCount .companyWord span').hide();

            if(companyWordPlural)
              $('#advancedSearchSummary .tableResultsCount .companyWord .plural').show();
            else
              $('#advancedSearchSummary .tableResultsCount .companyWord .singular').show();

            $('#advancedSearchSummary .tableResultsCount .subjectWord span').hide();

            if(subjectWordPlural)
              $('#advancedSearchSummary .tableResultsCount .subjectWord .plural').show();
            else
              $('#advancedSearchSummary .tableResultsCount .subjectWord .singular').show();
            
            $('#advancedSearchSummary .tableResultsCount .moreWord span').hide();

            if(moreWordPlural)
              $('#advancedSearchSummary .tableResultsCount .moreWord .plural').show();
            else
              $('#advancedSearchSummary .tableResultsCount .moreWord .singular').show();

            $('#advancedSearchSummary .tableResultsSearchCriteria').html($(xml).find('SummaryHTML').text());

            $('#advancedSearchSummary').removeClass('advancedSearchSummaryFaded');

            if($(xml).find('EnableNearMatch').text() == 'true')
              $('#advancedSearchNearMatch').show();
            else
              $('#advancedSearchNearMatch').hide();

            hideOverlay();
          }
   
          $('#advancedSearchForm #advancedSearchTableId').attr('value',$(xml).find('UserTableId').text());
          $('#advancedSearchForm #advancedSearchTableHash').attr('value',$(xml).find('UserTableHash').text());
        }
      }
      else
      {
        clearTimeout(loadingText);
        unexpectedError();
      }
    }
  });
}

function advancedSearchHandleErrors(xml)
{
  var errorText = '';

  $(xml).find('Error').each(function()
  { 
    if($(this).attr('attribute_id') != null)
    {
      errorText = 'There was a problem with some of your search filters.'
      $('#searchAttribute_'+$(this).attr('attribute_id')).addClass('searchAttributeContentsError');
      $('#searchAttribute_'+$(this).attr('attribute_id')+' .searchAttributeFilterError').html($(this).text());
      $('#searchAttribute_'+$(this).attr('attribute_id')+' input[type=text]').addClass('standardInputError');
      $('#searchAttribute_'+$(this).attr('attribute_id')+' select').addClass('standardInputError');

      advancedSearchToggleGroup($('#searchAttribute_'+$(this).attr('attribute_id')).parent().parent().parent().attr('id'), 'down');
      noAttributeError = false;
    }
    else
    {
      errorText = $(this).text();
      noAttributeError = true;
    }
  });

  if(noAttributeError)
  {
    if($('#advancedSearchForm .productSelect:checked').length > 0)
      advancedSearchToggleGroup($('#advancedSearchForm .productSelect:checked').parent().parent().parent().parent().attr('id'), 'down');
    
    if($('#advancedSearchForm .companySelect:checked').length > 0)
      advancedSearchToggleGroup($('#advancedSearchForm .companySelect:checked').parent().parent().parent().parent().attr('id'), 'down');
    
    if($('#advancedSearchForm .attributeSelect:checked').length > 0)
    {
      $('#advancedSearchForm .attributeSelect:checked').each( function() {
        advancedSearchToggleGroup($(this).parent().parent().parent().parent().attr('id'), 'down');
      });
    }
  }

  $('#advancedSearchMessage .advancedSearchTitle').hide();
  $('#advancedSearchMessage .advancedSearchError').show().html(errorText+'<br />Please change your selections.');

  hideOverlay();
}

function advancedSearchUpdate(tableId, tableHash, subcatGroupId)
{
  xmlDocContents = '';
  xmlDocContents += '<SubcatGroupId>'+subcatGroupId+'</SubcatGroupId>';
  xmlDocContents += '<UserTableId>'+tableId+'</UserTableId>';
  xmlDocContents += '<UserTableHash>'+tableHash+'</UserTableHash>';
  xmlDocContents += '<BaseTableId>'+tableId+'</BaseTableId>';
  xmlDocContents += '<BaseTableHash>'+tableHash+'</BaseTableHash>';
  advancedSearchSendData(xmlDocContents);
}

function advancedSearchClearAllFilters()
{
  $('#advancedSearchForm .productSelect:checked').click();
  $('#advancedSearchForm .companySelect:checked').click();
  $('#advancedSearchForm .attributeSelect:checked').click();
  $('#advancedSearchForm .searchAttributeFilterOptions').hide();
  advancedSearchCompaniesCount();
  $('#advancedSearchForm .searchGroup').each(function(i) { advancedSearchCheckCounts( $(this).attr('id').replace('searchGroup_','')); });
}

/*
**	history for ajax/javascript history
**		0.3 history events now setup in queue to ensure all entries reside in the history stack
**		0.2 no more FORM GET submission, straight location.href instead + hold time for iframe load
**		0.1 hidden frame + not bookmarkable + stores data for state change + allows reinstating data on forw/back hit
**	authored by Jim Palmer - released under MIT license
**  collage of ideas from Taku Sano, Mikage Sawatari, david bloom and Klaus Hartl
*/
(function($) {

	$.history = function ( store ) {

		// (initialize) create the hidden iframe if not on the root window.document.body
		if ( $("#__historyFrame").length == 0 ) {

			// set the history cursor to (-1) - this will be populated with current unix timestamp or 0 for the first screen
			$.history.cursor = $.history.intervalId = 0;
			// initialize the stack of history stored entries
			$.history.stack = {};
			// initialize the stack of loading hold flags
			$.history._loading = {};
			// initialize the queue for loading history fragments in sequence
			$.history._queue = [];

			// append to the root window.document.body without the src - uses class for toggleClass debugging - display:none doesn't work
			$("body").append('<iframe id="__historyFrame" src="/ajax/ajax-request.htm" style="border:0px; width:0px; height:0px; visibility:hidden;" />');
      //$("body").append('<div id="__historyDebug"></div>');

			// set the src (safari doesnt load the src if set in the append above)  + set the onLoad event for the iframe
			$('#__historyFrame').load(function () {

					// parse out the current cursor from the location/URL
					var cursor = $(this).contents().attr( $.browser.msie ? 'URL' : 'location' ).toString().split('#')[1];
					if ( cursor ) {
						// remove the cursor from the load queue
						var qPos = $.inArray( cursor, $.history._queue );
						if ( qPos > -1 )
							$.history._queue.splice( qPos, 1 );
						// flag that the iframe is done loading the new fragment id
						$.history._loading[ cursor ] = false;
					}

					// setup interval function to check for changes in "history" via iframe hash and call appropriate callback function to handle it
					$.history.intervalId = $.history.intervalId || window.setInterval(function () {
							// if any cursors in queue - load first cursor (FIFO)
							if ( $.history._queue.length > 0 && !$.history._loading[ $.history._queue[0] ] ) {
								// flag this queued cursor as loading so this interval will not load more than once
								$.history._loading[ $.history._queue[0] ] = true;
								// move the history cursor in the hidden iframe to the newest fragment identifier
								$('#__historyFrame').contents()[0].location.href = 
									$('#__historyFrame').contents().attr( $.browser.msie ? 'URL' : 'location' ).toString().replace(/[\?|#]{1}(.*)$/gi, '') + 
									'?' + $.history._queue[0] + '#' + $.history._queue[0];
							} else if ( $.history._queue.length == 0 ) {
								// fetch current cursor from the iframe document.URL or document.location depending on browser support
								var cursor = $("#__historyFrame").contents().attr( $.browser.msie ? 'URL' : 'location' ).toString().split('#')[1];
								// display debugging information if block id exists
								$('#__historyDebug').html('"' + $.history.cursor + '" vs "' + cursor + '" - ' + (new Date()).toString());
								// if cursors are different (forw/back hit) then reinstate data only when iframe is done loading
								if ( parseFloat($.history.cursor) >= 0 && parseFloat($.history.cursor) != ( parseFloat(cursor) || 0 ) ) {
									// set the history cursor to the current cursor
									$.history.cursor = parseFloat(cursor) || 0;
									// reinstate the current cursor data through the callback
									if ( typeof($.history.callback) == 'function' )
										$.history.callback( $.history.stack[ cursor ], cursor );
								}
							}
						}, 300);

				});

		} else {			// handle new history entries apre-initialization

			// set the current unix timestamp for our history
			$.history.cursor = (new Date()).getTime().toString();
			// add this cursor fragment id into the queue to be loaded by the checking function interval
			$.history._queue.push( $.history.cursor );
			// insert into the stack with current cursor
			$.history.stack[ $.history.cursor ] = store;

		}
			
	}

	// pre-initialize the history functionality - if you include this plugin this will be loaded as a singleton at time of the root window.onLoad
	$(document).ready( function () { $.history(); } );


})(jQuery);

function tableSplitTestChanges()
{
  $(document).ready( function ()
  {
    if(typeof(googleGoalId) != 'undefined' && googleGoalId != null)
    {
      $(".comparisonTable .actionCell a, .comparisonTable .productImageCell a, .comparisonTable .providerProductCell a").each(function (i)
      {
        if($(this).attr('href').indexOf('&subchannel') != -1)
        {
          if(typeof(googleGoalId) != 'undefined' && googleGoalId != null && $(this).attr('href').indexOf('&goalid') == -1)
            $(this).attr('href',$(this).attr('href')+'&goalid='+googleGoalId);
        }
      });
    }
  });

 var percentMatchHTML = '<div class="comparisonTableAfterText">"% match" displayed in green below the buttons in this table indicates how well the product matches your search criteria.</div>';
  
  $(document).ready( function ()
  {
    if(typeof(matchPercentHTML) != 'undefined' && matchPercentHTML != null)
    {
      $(".comparisonTable .actionCell").each(function (i)
      {
        if($(this).html().indexOf(matchPercentHTML) == -1)
          $(this).html($(this).html()+matchPercentHTML);
      });
     
      if($(".comparisonTableContainer").html().indexOf(percentMatchHTML) == -1)
        $(".comparisonTableContainer").html($(".comparisonTableContainer").html()+percentMatchHTML);
    }
  });

}

var floatingTableHeaderEnabled = true;
var floatingTableHeaderShowing = false;

function floatingTableHeaderCreate()
{
  if(!ie6)
  {
    if(floatingTableHeaderEnabled)
    {
      $(document).ready( function ()
      {
        $(window).unbind("scroll", floatingTableHeaderScroll);
        $(window).unbind("resize", floatingTableHeaderScroll);

        var table = $('.comparisonTable[id!=floatingTableHeader]:first');
        
        if($('#floatingTableHeader').length > 0)
          $('#floatingTableHeader').remove();
        
        var newTableWrapper = $(document.createElement('div')).attr('id','floatingTableHeader').addClass('comparisonTable').insertBefore(table);
        var newTable = $(document.createElement('table')).attr('cellspacing','0').appendTo(newTableWrapper);
        
        if(floatingTableHeaderShowing == false)
          newTableWrapper.hide();

        $('.comparisonTable[id!=floatingTableHeader]:first .headerRow').clone().attr('id','floatingTableHeader_header').appendTo(newTable);
        $('.comparisonTable[id!=floatingTableHeader]:first .subHeaderRow').clone().attr('id','floatingTableHeader_subheader').appendTo(newTable);
         
        floatingTableHeaderWidths();
        
        newTableWrapper.width(table.width()); 
        newTableWrapper.css({position:'fixed',top:'0px',zIndex:'99'});

        $(window).bind("scroll", floatingTableHeaderScroll);
        $(window).bind("resize", floatingTableHeaderScroll);
      });
    }
  }
}

function floatingTableHeaderWidths()
{
  if(!ie6)
  {
    if(floatingTableHeaderEnabled)
    {
      var cells = $('#floatingTableHeader_header td'); 
      var i = 0; 
      jQuery.each( $('.comparisonTable[id!=floatingTableHeader]:first .headerRow td') , function() { 
        
        if($(this).is(":visible"))
          $(cells[i]).width($(this).width()); 

        i++; 
      });
        
      var cells = $('#floatingTableHeader_subheader td'); 
      var i = 0; 
      jQuery.each( $('.comparisonTable[id!=floatingTableHeader]:first .subHeaderRow td') , function() { 
        
        if($(this).is(":visible"))
          $(cells[i]).width($(this).width()); 

        i++; 
      }); 
    }
  }
}

function floatingTableHeaderScroll()
{
  var floatingTablePosition = $('.comparisonTable[id!=floatingTableHeader]:first').position();
  var floatingContainerPosition = $('#pageContainer').position();

  if($(window).width() < 960)
    floatingTableHeaderShowing = false;
  else if($(window).scrollTop() > (floatingTablePosition.top + floatingContainerPosition.top))
    floatingTableHeaderShowing = true;
  else
    floatingTableHeaderShowing = false;
  
  if(($(window).scrollTop() + $('#floatingTableHeader').height() + 100) > ((floatingTablePosition.top + floatingContainerPosition.top) + $('.comparisonTable[id!=floatingTableHeader]:first').height()))
    floatingTableHeaderShowing = false;

  if(floatingTableHeaderShowing && $('#floatingTableHeader:visible').length == 0)
  {
    $('#floatingTableHeader').show();
    $('#floatingTableHeader .headerRowEmailTable .standardInput').val($('.comparisonTable[id!=floatingTableHeader]:first .headerRowEmailTable .standardInput').val());
    $('#floatingTableHeader .headerRowEmailTable .standardInput').attr('class',$('.comparisonTable[id!=floatingTableHeader]:first .headerRowEmailTable .standardInput').attr('class'));
    $('.comparisonTable[id!=floatingTableHeader]:first .headerRowEmailTable .standardInput').attr('disabled','disabled');
  }
  else if(!floatingTableHeaderShowing && $('#floatingTableHeader:visible').length == 1)
  {
    $('#floatingTableHeader').hide();
    $('.comparisonTable[id!=floatingTableHeader]:first .headerRowEmailTable .standardInput ').val($('#floatingTableHeader .headerRowEmailTable .standardInput').val());
    $('.comparisonTable[id!=floatingTableHeader]:first .headerRowEmailTable .standardInput ').attr('class',$('#floatingTableHeader .headerRowEmailTable .standardInput').attr('class'));
    $('.comparisonTable[id!=floatingTableHeader]:first .headerRowEmailTable .standardInput').removeAttr('disabled');
  }
}

function submitSimpleSearchForm(url)
{
  if(url == null)
  {
    if($('[name=tableAdvancedSearchTable]:checked').val() != 'Other' && $('[name=tableAdvancedSearchTable]:checked').val() != undefined)
      url = $('[name=tableAdvancedSearchTable]:checked').val();
    else if($('[name=tableAdvancedSearchTable]:checked').val() == 'Other')
    {
      if($('#tableAdvancedSearchTable').attr('value') != '')
        url = $('#tableAdvancedSearchTable').attr('value');
    }
  }

  if(url != null)
    window.location.href = url;
}

function submitBroadbandPostcodeChecker() 
{
  $('#advancedSearchContent').html('');

  var postcodeRegEx = /[A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9]?[ABEHMNPRVWXY0-9]? {0,2}[0-9][ABD-HJLN-UW-Z]{2}/i;

  if($('#simpleSearchPostcode').length == 1 && $('#simpleSearchPostcode').val() != '')
  {
    if(postcodeRegEx.test($('#simpleSearchPostcode').val()))
    {
      xmlDocContents = '<SubcatGroupId>17</SubcatGroupId>';
      xmlDocContents += '<BaseTableId>210</BaseTableId>';
      xmlDocContents += '<SearchColumn><AttributeId>50001</AttributeId>';
      xmlDocContents += '<SearchValue>'+$('#simpleSearchPostcode').val()+'</SearchValue>';
      xmlDocContents += '</SearchColumn>';
      advancedSearchSendData(xmlDocContents);
    }
    else
      $('#simpleSearchPostcodeError').css('color','red').html('Invalid postcode. Please check and correct.');
  }
}

function loadSearchAdditionalOptions(url, noToggle)
{

  if(noToggle == null)
    noToggle = false;

  if($('#searchAdditionalOptions:hidden').length == 1 || noToggle)
  {
    if($('#searchAdditionalOptions .searchOptions').html() == '')
    {      
      $.ajax({ 
       type: "GET", 
       url: url,
       cache: false,
       error: function() { unexpectedError(); },
       success: function(response)
       {
         $('#searchAdditionalOptions .searchOptions').html(response);
         $('#searchAdditionalOptions').slideDown();
       }
      });
    }
    else
      $('#searchAdditionalOptions').slideDown();
  }
  else
    $('#searchAdditionalOptions').slideUp();

}



/** Product Related Stuff **/
function expandProductDetails(productId, attributeId, direction)
{
  if(direction=='expand')
  {
    $('.prdDetailsAttribute_'+productId+'_'+attributeId+'_shorttext').hide();
    $('.prdDetailsAttribute_'+productId+'_'+attributeId+'_fulltext').show();
  }
  else
  {
    $('.prdDetailsAttribute_'+productId+'_'+attributeId+'_shorttext').show();
    $('.prdDetailsAttribute_'+productId+'_'+attributeId+'_fulltext').hide();
  }
}

function getFullProductDetails(url)
{  
  if($('#productDetail').html() == '')
  {
    var loadingDiv = $(document.createElement("div")).attr("id","productDetailsLoading")
                            .html('<img src="/images/common/icon-loading.gif" style="margin-bottom:10px;"/><br/><b>Loading...</b>')
                            .css({'text-align':'center','padding':'20px'});
    $("#productDetail").load(url+'?details=true&r='+Math.random());
    loadingDiv.appendTo("#productDetail");
  }
}

function simpleSearchPromoSelect(id, stopScrolling)
{
 
  if(stopScrolling == undefined || stopScrolling == null)
    stopScrolling = true;

  $('#simpleSearchBox .promoBoxNumbers .promoBoxNumberSelected').removeClass('promoBoxNumberSelected');
  $('#simpleSearchBox .promoBoxNumbers #promoBoxNumber_'+id).addClass('promoBoxNumberSelected');
  $('#simpleSearchBox .promoBox').hide();
  $('#simpleSearchBox #promoBox_'+id).show();

  if(stopScrolling)
  {
    $.doTimeout('sPromoEven');
    $.doTimeout('sPromoOdd');
  }
  else
  {
    if((id+1)%2)
      var timerId = 'sPromoEven';
    else
      var timerId = 'sPromoOdd';

    if($('#simpleSearchBox .promoBoxNumbers #promoBoxNumber_'+(id+1)).length == 1)
      $.doTimeout(timerId, 8000, simpleSearchPromoSelect, (id+1), false);
    else
      $.doTimeout(timerId, 8000, simpleSearchPromoSelect, 0, false);
  }
}

function tableRowHoverIn(element)
{
  $(element).addClass('dataRowHover');
}

function tableRowHoverOut(element)
{
  $(element).removeClass('dataRowHover');
}

function tableRowClick(url)
{
   if(loadTrackingLink(url))
     window.location = url;       
}

function tableEmailSubmit(form)
{
  var submitSuccess = false;
  var submitParams = $(form).serialize();

  addFormLoading('tableEmailSubmit','loadingFadeSmall',form);

  $.ajax({ 
    type: "GET", 
    url: '?sendTableEmail=true&'+submitParams,
    cache: false,
    async: false,
    error: function() { unexpectedError(); },
    success: function(response) { if(response == 'success') { submitSuccess = true; } }
  });

  if(submitSuccess)
  {
    showSuccessMessage('tableEmailSubmit','tableEmailSubmit','<img src="images/common/icon-tick.gif"> Comparison Table Sent!','messageFadeSmall',form);
    $(form).children('.standardInput').addClass('standardInputFaded');
    $(form)[0].reset();
  }
  else
    showSuccessMessage('tableEmailSubmit','tableEmailSubmit','<img src="images/common/icon-cross.gif"> <span style="color:#FF0000;">Email is invalid format</span>','messageFadeSmall',form);
}
