(function($) {
  $(document).ready(function() {

    // All pages
    $('.help').hide();      // help
    $('.tab-help').show();  // show tabs
    $('.tab-help a').click(function(){
      $('.help').slideToggle("fast");
    });

    // Add default value to search box
    $("#queries_searchbox_query.site-search").DefaultValue("Search site");

    // Add autocomplete to search box.
    $.get("/js-content/list-of-families/", function(data){
      var typeAheadData = data.split(",");
      $("input.products-autocomplete").autocomplete(typeAheadData, {matchContains: true, selectFirst: false});
    });

    // Home page
    if ($("#id51").length > 0) {
      addTableFilter();
      addDateSortingForResourcesTable();
      createHomepageTabs();
    }
    
    // Tablesorter
    if ($('.sortable').length > 0) {
      $('.sortable').tablesorter({widgets: ['zebra']}); 
    }

    // Home page again. This must come after the Tablesorter function
    if ($("#id51").length > 0) {
      changeDateSortingLinkForResourcesTable();
    }

    // Change displayed Matrix select field metadata keys into Matrix metadata values.
    loadMetadataKeysAndValuesList();
    formatSearchTerms();
    formatResourceMetadata();
  
    // Pages with links to Products on them
    if ($("a.product-link").length) {
      makeProductsFiltersSticky();
    }

    // Systems and Products main page
    if ($("#systems-and-products").length > 0) {
      createSecondLevelTabs();
    }
    
    // Family pages only
    if ($("div.family-page").length > 0) {
      setCookieWhenProductLinksClicked();
    }

    // Product pages
    if ($("#products-content").length > 0) {
      addProductResourceClassLinks();
      addProductPageResourceTypeAhead();
      addManualsSubClassLinks();
      addSoftwareFirmwareSubClassLinks();
      addProductUserTaskLinks();
      setUpRequestFirmwareLinks();
      preLoadResourceClassAndUserTaskContainers();
      highlightCurrentProductTab();
      setupResourcesFilterBox();
      removeEmptyMetadataFields();
      setupListOfProducts();
    }

    // Resource pages only
    if ($("div.resource-page").length > 0) {
      removeEmptyMetadataFields();

      // Firmware resources only
      if ($("div.Firmware").length) {
        setUpRequestFirmwareLinks();
      }

    }

    // Search page
    if ($("#id504, #id2827").length > 0) {
      tidySearchResults();
      removeDuplicateResults();
      addSearchResultsFilter();
      showOnlyProductsInChosenFamilyForSearch();
      clearAllSearchFiltersButton();
      addPagination();
    }

    // Technical Notes page
    if ($("#id5753").length > 0) {
      tidySearchResults();
      showOnlyProductsInChosenFamilyForSearch();
      clearAllSearchFiltersButton();
      addPagination();
    }

  });  
})(jQuery);


function normaliseUrls(sel){

  $(sel).each(function(){

    var href = $(this).attr('href');

    if (href.indexOf("#")!=-1){
    
    } else {
      
      if(href.indexOf("?") > 0 ) {

        href = href.substr(i.indexOf("?"));
        $(this).attr({href: "" + href + "&SQ_DESIGN_NAME=blank"});
        $(this).attr({href: "/js-content/systems-and-products" + href + "&SQ_DESIGN_NAME=blank"});

      } else {
        
        if ($(this).parent('#filter-all').length > 0) {
      
          $(this).attr({href: "/js-content/systems-and-products?class=&SQ_DESIGN_NAME=blank"});
          
        } else {
  
          $(this).attr({href: href + "?SQ_DESIGN_NAME=blank"});
        }
      }
    }
  });
} // end of normaliseUrls(sel)



function loadMetadataKeysAndValuesList() {

  // Load the asset listing of metadata keys/values in the background
  var divText = '<div id="metadata-keys-values"></div>';
  $("body").append(divText);
  $("#metadata-keys-values").hide();
  $("#metadata-keys-values").load("/js-content/list-metadata-keys-and-values", {}, function() {

    changeMetadataKeysIntoValues();

  });
  
} // end loadMetadataKeysAndValuesList



function changeMetadataKeysIntoValues() {

  // Currently Matrix is unable to print a select metadata's field's key or value on demand. It can only print one or the other everywhere. This function changes keys into values. If Matrix functionality allows for this in the future then this function can be removed.

  // Check if the keys and values have been loaded
  if ($("#metadata-keys-values").html().length) {
  
    // Create array of key/value pairs
    var keyValuePairs = [];
    $("#metadata-keys-values div").each(function() {
      var textString = $(this).text();
      var arrayData = unserialize(textString);
      for (key in arrayData) {
        keyValuePairs[key] = arrayData[key];
      }

    });

    // Go through each key to be replaced (each one is in a span with class="replace-with-xxxxx") and replace it with the appropriate value
    $("span.replace-with-value, span.replace-with-list-items, span.replace-with-links-to-systems, span.replace-with-links-to-user-tasks").each(function() {

      // There may be multiple metadata keys separated by semicolons. Split these keys up and then recombine the values with ampersands.
      var keyString = $(this).html();
      var key;
      var valueString = "";
      var pos;

      // loop through keys and build up valueString
      while (keyString.indexOf(";",0) >= 0) {
        pos = keyString.indexOf(";",0);
        key = keyString.substring(0, pos);
        keyString = keyString.substring(pos + 2);

        if ($(this).hasClass("replace-with-value")) {
          valueString += keyValuePairs[key] + ", ";
        }

        if ($(this).hasClass("replace-with-list-items")) {
          valueString += "<li>" + keyValuePairs[key] + "</li>\n";
        }

        if ($(this).hasClass("replace-with-links-to-systems")) {
          valueString += createLinkToSystem(key, keyValuePairs[key]);
        }

        if ($(this).hasClass("replace-with-links-to-user-tasks")) {
          valueString += createLinkToUserTask(keyValuePairs[key]);
        }
      }

      if ($(this).hasClass("replace-with-value")) {
        valueString += keyValuePairs[keyString];
      }

      if ($(this).hasClass("replace-with-list-items")) {
        valueString += "<li>" + keyValuePairs[keyString] + "</li>\n";
      }

      if ($(this).hasClass("replace-with-links-to-systems")) {
        valueString += createLinkToSystem(keyString, keyValuePairs[keyString]);
      }

      if ($(this).hasClass("replace-with-links-to-user-tasks")) {
        valueString += createLinkToUserTask(keyValuePairs[keyString]);
      }

      $(this).replaceWith(valueString);

    });

  }

} // end of changeMetadataKeysIntoValues()



function createLinkToSystem(systemMetadata, systemReadable) {

  var productSystem;
  var productClass;

  if (systemMetadata.indexOf("sysp25") != -1) {
    productClass = "sysp25";
  } else {
    productClass = "sysanalog";
  }

  productSystem = systemMetadata.substr(productClass.length);
  productClass = productClass.replace(/sys/,"cl");

  return '<li><a href="/systems-and-products-subs?class=' + productClass + '&system=' + productSystem + '&system1=' + systemMetadata + '">' + systemReadable + '</a></li>\n';


} // end createLinkToSystem



function createLinkToUserTask(userTaskReadable) {

  return '<li>' + userTaskReadable + '</li>\n';
  
} // end createLinkToSystem



function addProductResourceClassLinks() {

  // If query string parameter class is set and it is a resource class, use this as the default resource class to display. Otherwise use manuals
  var parameter = $(document).getUrlParam("SQ_PAINT_LAYOUT_NAME");
  var urlResourceClass = "";
  var urlUserTask = "";

  if (parameter !== null) {

    switch(parameter.substring(0,2)) {
      case "rc":
        urlResourceClass = parameter;
        break;
      case "us":
        urlUserTask = parameter;
        break;
    }
  }

  if (urlResourceClass == "" && urlUserTask == "") {
    urlResourceClass = "rcmanual";

  }

  // Set default filter to be the resource class
  $("#products-content").addClass(urlResourceClass);
  
  // Add type-ahead filterable class to the visible div.resource divs
  $("div.resource:visible").addClass("filterable");
  
  // Insert links to the Products' Manuals, Software/Firmware and Technical Notes resources
  var currentProduct = $("#current-product").text();
  var resourceClassFilter = '<ul id="resource-class-filter" class="hide"><li><a class="rcmanual " href="?SQ_PAINT_LAYOUT_NAME=rcmanual"><span class="product-name">' + currentProduct + ' </span>Manuals</a></li><li><a class="rcsoftwarefirmware" href="?SQ_PAINT_LAYOUT_NAME=rcsoftwarefirmware"><span class="product-name">' + currentProduct + ' </span>Software / Firmware</a></li><li><a class="rctechnicalnotes" href="?SQ_PAINT_LAYOUT_NAME=rctechnicalnotes"><span class="product-name">' + currentProduct + ' </span>Technical Notes</a></li></ul>';

  // Insert these links into the page
  $("#resource-class-filter-container-top").html(resourceClassFilter);
  
  if (urlResourceClass != "") {

    // Set selected filter
    $("#resource-class-filter li a." + urlResourceClass).parent("li").addClass("selectedFilter");

  }

  // If one of the filters is clicked, add a class to the products-content div. The CSS will then only show the resources for this resource class.
  $("#resource-class-filter li a, #manuals-subclasses a").click(function() {
  
    // Move the resource-class-filter ul to the top of the page. Move the user-task-filter to the right column.
    $("#resource-class-filter-container-top").append($("#resource-class-filter"));
    $("#user-task-filter-container-right").append($("#user-task-filter")).show();
    $("#resource-class-filter-container-right").hide();

    var newFilter = $(this).attr("class");
    filterResources(newFilter, "resourceClass");

    // Set cookie to remember which of the filters was clicked last. If user goes to another product, we want to show this filter first. Cookie will expire after 10 minutes.
    setCookie("product-filter", newFilter, "/", 10);
    
    // Add filter to product links so that when clicked they will automatically display the most recently viewed filter first
    addFilterToProductLinks(newFilter);

    return false;
    
  });  

  // get assetid of current page to pass in to Matrix searches
  var matrixAssetid = $("body").attr("id");
  matrixAssetid = matrixAssetid.substring(2);
  
  var noOfResourceClassLinks = $("#resource-class-filter li a").length;
  var resourceClassCounter = 0;

  // Check to see if there are any resources for this resource class filter/product combination
  $("#resource-class-filter li a").each(function() {
  
    var currentLink = $(this);
    var resourceClass = $(this).attr("class");

    $.get("/js-content/find-if-resource-has-resource-class-metadata", { assetid: matrixAssetid, resourceclass: resourceClass }, function(data){
      if (data == "false") {
        $(currentLink).parent("li").remove();
      } else {
        $(currentLink).parent("li").show();
      }

      resourceClassCounter++;

      // After all links have been checked, perform the following actions.
      if (resourceClassCounter == noOfResourceClassLinks) {

        // If resource class has been selected (and not user task) and the selected link has been removed, then set the selected link to be first list item and click the link in it.
        if (urlUserTask == "") {

          if ($("#resource-class-filter li.selectedFilter").length == 0) {
            $("#resource-class-filter li:first").addClass("selectedFilter").find("a").click();
          }

          // Show the Resource Class filters
          $("#resource-class-filter").show();

          // Place a hidden copy of the resource class filters in the right column
          $("#resource-class-links ul").html($("#resource-class-filter").html());

        } else {
        
          // Place a copy of the resource class filters in the right column and show them
          $("#resource-class-links ul").html($("#resource-class-filter").html());
          $("#resource-class-filter").show();
        
        }

      }

    });
    
  });

} // end of addProductResourceClassLinks



function filterResources(newFilter, filterType) {

  $("#resource-class-filter li.selectedFilter").removeClass("selectedFilter");

  if (filterType == "resourceClass") {

    // Remove the highlight from the currently highlighted tab and highlight the clicked tab
    $("#resource-class-filter li a." + newFilter).parent("li").addClass("selectedFilter");

  }

  // Remove any existing filter from the products-content div and add the clicked filter as a class. 
  // The product-content div has a class of 'tabs-content' applied to it as well as the classes that begin with 'rc' or 'msc'.
  // We will simply constuct the new class (including 'tabs-content' and the new filter) and apply it to this div.
  $("#products-content").attr("class", "tabs-content " + newFilter);
  
  // Remove any potential show/hide type-ahead filtering by showing all the div.resources divs. The CSS will still override this making only the desired resources visible.
  $("div.filterable, .filterable div.resource-content").removeAttr("style");

  // Remove the class 'filterable' from all div.resource divs. Then add 'filterable' class to the visible div.resource divs
  $("div.filterable").removeClass("filterable");
  $("div.resource:visible").addClass("filterable");

  // Clear the type-ahead input box
  $("#FilterTextBox").attr("value","");

} // end of filterResources




function addProductUserTaskLinks() {

  var urlUserTask = $(document).getUrlParam("usertask");

  if (urlUserTask !== null) {

    // Set default filter to be the resource class
    $("#products-content").addClass(urlUserTask);

    // Add type-ahead filterable class to the visible div.resource divs
    $("div.resource:visible").addClass("filterable");
    
  }

  var currentProduct = $("#current-product").text();
  var userTaskLinks = '<ul id="user-task-filter"><li><a class="utinstallation" href="?SQ_PAINT_LAYOUT_NAME=usertasks&usertask=utinstallation"><span class="product-name">' + currentProduct + ' </span>Installation &amp; Configuration</a></li><li><a class="utoperation" href="?SQ_PAINT_LAYOUT_NAME=usertasks&usertask=utoperation"><span class="product-name">' + currentProduct + ' </span>Operation</a></li><li><a class="utservicing" href="?SQ_PAINT_LAYOUT_NAME=usertasks&usertask=utservicing"><span class="product-name">' + currentProduct + ' </span>Servicing</a></li><li><a class="utsoftware" href="?SQ_PAINT_LAYOUT_NAME=usertasks&usertask=utsoftware"><span class="product-name">' + currentProduct + ' </span>Software & Firmware</a></li><li><a class="utaccessoriesinstallation" href="?SQ_PAINT_LAYOUT_NAME=usertasks&usertask=utaccessoriesinstallation"><span class="product-name">' + currentProduct + ' </span>Accessories Installation</a></li></ul>';
  $("#user-task-filter-container-right").append(userTaskLinks);

  // get assetid of current page to pass in to Matrix searches
  var matrixAssetid = $("body").attr("id");
  matrixAssetid = matrixAssetid.substring(2);

  // Check to see if there are any resources for this user task filter/product combination
  var noOfLinks = $("#user-task-filter li a").length;
  var linkNo = 1;

  $("#user-task-filter li a").each(function() {
  
    var currentLink = $(this);
    var userTask = $(this).attr("class");
    
    $.get("/js-content/find-if-resource-has-user-task-metadata", { assetid: matrixAssetid, usertask: userTask }, function(data){
      if (data == "false") {
        $(currentLink).parent("li").remove();
      }

      if (linkNo == noOfLinks) {

        $("#user-task-filter-container-right").show();
        // If one of the filters is clicked, add a class to the products-content div. The CSS will then only show the resources for this resource class.
        $("#user-task-filter li a").click(function() {

          // Move the user-task-filter ul to the top of the page. Move the resource-class-filter to the right column.
          $("#user-task-filter-container-top").append($("#user-task-filter"));
          $("#resource-class-filter-container-right").append($("#resource-class-filter")).show();
          $("#user-task-filter-container-right").hide();
          
          // Add selectedFilter class to the li
          $("#user-task-filter li.selectedFilter").removeClass("selectedFilter");
          $(this).parent("li").addClass("selectedFilter");

          var newFilter = $(this).attr("class");
          filterResources(newFilter, "userTask");

          // Set cookie to remember which of the filters was clicked last. If user goes to another product, we want to show this filter first. Cookie will expire after 10 minutes.
          setCookie("product-filter", newFilter, "/", 10);

          // Add filter to product links so that when clicked they will automatically display the most recently viewed filter first
          addFilterToProductLinks(newFilter);

          return false;

        });  

      }
      linkNo++;

    });
  
  });

  if (urlUserTask !== null) {

    // Move the user-task-filter ul to the top of the page. Move the resource-class-filter to the right column.
    $("#user-task-filter-container-top").append($("#user-task-filter"));
    $("#resource-class-filter-container-right").append($("#resource-class-filter")).show();
    $("#user-task-filter-container-right").hide();

    // Add selectedFilter class to the li
    $("#user-task-filter li.selectedFilter").removeClass("selectedFilter");
    $("#user-task-filter li a." + urlUserTask).parent("li").addClass("selectedFilter");

  }

} // end of addProductUserTaskLinks()



function preLoadResourceClassAndUserTaskContainers() {

  // Load additional resources into container divs behind the scenes using Ajax.
  // Loop through the container divs. If they contain an Ajax loading image, then they have not yet been populated.
  var currentURL = window.location.pathname;

  $("div.container").each(function() {
  
    if ($(this).find("#ajax-loading-image").length) {
    
      var paintLayout = $(this).find("span").text();
      $(this).load(currentURL + "?SQ_DESIGN_NAME=blank&SQ_PAINT_LAYOUT_NAME=" + paintLayout + " #" + paintLayout + "-inner-container", function() {
      
        // Load the subclass links for Manuals and Software/Firmware
        if (paintLayout == "rcmanual") {
          addManualsSubClassLinks();
        }
        if (paintLayout == "rcsoftwarefirmware") {
          addSoftwareFirmwareSubClassLinks();
          setUpRequestFirmwareLinks();
        }
        
        addProductPageResourceTypeAhead();
        changeMetadataKeysIntoValues();

      });
    
    }
  
  });



} // end preLoadResourceClassAndUserTaskContainers



function setUpRequestFirmwareLinks() {

  // Loop through all the versions. Find out all the zip files that exist under this version. If the zip files are not already displayed on page, show a 'Request Firmware' link (as the user does not have permissions to download the zip files directly).
  $("span.firmware-version-id, span.version-id").each(function() {
  
    // Find version id
    var versionId = $(this).text();
    var versionDetails = $(this).parents("div.version-details");
    var versionWrapper = versionDetails.parent();

    // Ajax call to get all zip files under one version
    versionDetails.find("div.unprocessed-zip-files").load("/js-content/list-zip-files-and-metadata?versionid=" + versionId, function(data){

      // Find asset ids of zip files already displayed in this version
      var zipFiles = [];
      versionWrapper.find("span.zip-file-asset-id, span.file-asset-id").each(function() {

        zipFiles[zipFiles.length] = $(this).text();

      });

      // Loop through all spans containing metadata values. If the zip file is already being displayed then we remove the span.
      versionDetails.find("div.unprocessed-zip-files span").each(function() {

        isZipFileAlreadyOnPage($(this), zipFiles);

      });

      // For each zip file that hasn't yet been displayed, show a 'Request Firmware' link.
      versionDetails.find("span[id^='zip-file-metadata-UniqueID']").each(function() {
      
        // Create a new 'resource-details' div immediately after the current version-details div.
        var id;
        var uniqueId, language, releaseDate;
        var zipFileId = $(this).attr("class");
        zipFileId = zipFileId.substring(1);
        
        versionDetails.find("span.z" + zipFileId).each(function() {
        
          id = $(this).attr("id");
          switch(id) {

            case "zip-file-metadata-ReleaseDate-" + zipFileId:
              releaseDate = $(this).text();

              // Remove the release date span
              $(this).remove();
              break;

            case "zip-file-metadata-Language-" + zipFileId:
              language = $(this).text();

              // Remove the language span
              $(this).remove();
              break;

            case "zip-file-metadata-UniqueID-" + zipFileId:
              uniqueId = $(this).text();
              break;

          }

        });
        
        var resourceName;
        // If on product page
        if ($("div.product-page").length > 0) {
          resourceName = $(this).parents("div.resource-content").find("h4").text();
        }

        // If on resource page
        if ($("div.resource-page").length > 0) {
          resourceName = $(this).parents("div.resource-page").find("h1.resource-h1").text();
        }

        var versionNumber = versionDetails.find("span.version-number").text();

        // Add 'Request Firmware' link
        var newResourceDetailsDiv = '<div class="resource-details request-firmware"><span class="resource-metadata-unique-id">' + uniqueId + '</span>, ' + releaseDate + ', <span class="replace-with-value">' + language + '</span><div class="download-link"><a class="request-firmware-link" href="/request-firmware?prodcode=' + uniqueId + '&version=' + versionNumber + '&name=' + resourceName + '"><img src="./?a=2767" height="16" width="16" alt="ZIP file icon" /><span>Request Firmware</span><span class="access">' + resourceName + '</span></a></div></div>';
        versionDetails.after(newResourceDetailsDiv);

        // Remove the unique id span
        $(this).remove();
        
        // Convert metadata keys into values
        changeMetadataKeysIntoValues();

      });
      
    });
  
  });


} // end setUpRequestFirmwareLinks



function isZipFileAlreadyOnPage(span, zipFiles) {

  // If the zip file is already being displayed then we remove the span.
  var zipFileClass = span.attr("class");
  zipFileClass = zipFileClass.substring(1);

  // Loop through array of zip file asset ids
  var i = 0;
  while (i < zipFiles.length) {

    if (zipFileClass == zipFiles[i]) {
      span.remove();
    }
    i++;

  }

} // end isZipFileAlreadyOnPage



function highlightCurrentProductTab() {

  // The current product name is in an span in an h2 with a id of current-product-name. We'll then highlight the tab with the same name.
  var currentProduct = $("div#current-product").text();
  $("ul.tabs-level1-list li a").each(function() {
  
    if ($(this).text() == currentProduct) {
      $(this).parent("li").addClass("selectedTab");
    }
  
  });

} // end highlightCurrentProductTab


function tidySearchResults(){

  var noOfResults = $("#results-count").text();

  // On the search page, we're only showing 150 results.
  // If the total results listed found (but not displayed) is more than this, show that 150 have been found.
  if ($("#id504, #id2827").length > 0) {
    if (noOfResults > "150") {
      noOfResults = "150";
    }
  }

  // If no keyword search term then remove the text " for ''" from the Results h2 heading
  if ($("span#results-search-term").text().length == 0) {
    $("h2#results-heading").text(noOfResults + " results");
  }

  // If no spelling suggestion, then remove the 'Did you mean?' paragraph
  if ($("#spelling-suggestion").text() == "") {
    $("#spelling-suggestion-para").hide();
  }

} // end of tidySearchResults()


function removeDuplicateResults(){

  // Remove duplicate results

  // As we are returning resource files' parents (i.e. Resource or Resource Software assets), it is possible we can get duplicate search results. This function removes duplicate results, keeping the results highest up the results list.
  if ($(".search-results-list").length > 0) {
  
    $(".search-results-list .search-result").each(function() {
    
      // add class to result to mark it as processed
      $(this).addClass("processed");
      
      var asset = $(this).find("h3").attr("className");
      var h3String = "h3[class='" + asset + "']";
      $(".search-results-list .search-result").not(".processed").find(h3String).parent(".search-result").remove();
    
    });
    
    // Remove the processed class from all results
    $(".search-results-list .search-result").removeClass("processed");
    
    var newNoOfResults = $(".search-results-list .search-result").length;
    
    var newResultsString;
    if (newNoOfResults == 1) {
      newResultsString = "1 result";
    } else {
      newResultsString = newNoOfResults + " results";
    }

    $("#results-count").html(newResultsString);
    
  }

} // end of removeDuplicateResults()



function addTableFilter() {

  //add index column with all content.  
  $(".filterable tr:has(td)").each(function(){  
    var t = $(this).text().toLowerCase(); //all row text  
    $("<td class='indexColumn'></td>")  
     .hide().text(t).appendTo(this);  
  });//each tr  

  $("#FilterTextBox").keyup(function(){  
    var s = $(this).val().toLowerCase().split(" ");  
    //show all rows.  
    $(".filterable tr:hidden").show();  
    $.each(s, function(){  
        $(".filterable tr:visible .indexColumn:not(:contains('" + this + "'))").parent().hide();
    });//each  

  });//key up.

}; // end of addTableFilter()



function addProductPageResourceTypeAhead() {

  //add index column with all content.
  $("div.resource-content h4").each(function(){  
    var t = $(this).text().toLowerCase();
    $("<div class='indexColumn'></div>").hide().text(t).insertBefore($(this));
  }); //each resource  

  $("#FilterTextBox").keyup(function(){  
    var s = $(this).val().toLowerCase().split(" ");  
    // show all resources
    $(".filterable div.resource-content:hidden, div.filterable:hidden").show();
    $.each(s, function(){
      $(".filterable div.indexColumn:not(:contains('" + this + "'))").parent("div.resource-content").each(function() {
        $(this).hide();

        // if resource category is left with no resources visible in it, hide the whole resource category
        if (!($(this).parents("div.resource").find("div.resource-content:visible").length)) {
          $(this).parents("div.resource").hide();
        }

      });
    });//each

  });//key up.

}; // end of addProductPageResourceTypeAhead()



function addManualsSubClassLinks() {

  // Add list of links to Manuals' sub classes. Clicking on one of these links will only show resources which for that sub class.
  if ($("#manuals-subclasses").length && ($("div.rcmanual > h3").length > 1)) {

    // Add border and padding to links
    $("#manuals-subclasses").addClass("has-border");
    
    var linksText = '<ul>\n';
    var subClassesList = "rcmanual ";

    $("div.rcmanual > h3").each(function() {

      // Determine which sub class we are processing
      var classes = $(this).parent("div").attr("class");
      var startOfSubClass = classes.indexOf("msc");
      classes = classes.substring(startOfSubClass);

      var subClass;
      if (classes.indexOf(" ") != -1) {
        subClass = classes.substring(0, classes.indexOf(" "));
      } else {
        subClass = classes;
      }
      subClassesList += subClass + " ";

      linksText += '<li><a class="' + subClass + '" href="#' + subClass + '">' + $(this).text() + '</a></li>\n';

    });

    linksText += "</ul>";

    $("#manuals-subclasses").html(linksText);
    
    // Format links into 3 columns
    $("#manuals-subclasses ul").makeacolumnlists({cols:3,colWidth:220,equalHeight:false,startN:1});

    
  }

} // end addManualsSubClassLinks



function addSoftwareFirmwareSubClassLinks() {

  // Add list of links to Software Firmware sub classes. Clicking on one of these links will only show resources which for that sub class. The subclasses are Software and Firmware.
  if ($("#software-firmware-subclasses").length && ($("div.rcsoftware > h3").length == 1) && ($("div.rcfirmware > h3").length == 1)) {

    // Add border and padding to links
    $("#software-firmware-subclasses").addClass("has-border");
    
    var linksText = '<ul><li><a href="#rcsoftwarefirmware" class="rcsoftwarefirmware">Software &amp; Firmware</a></li><li><a href="#rcsoftware" class="rcsoftware">Software</a></li><li><a href="#rcfirmware" class="rcfirmware">Firmware</a></li></ul>\n';
    $("#software-firmware-subclasses").html(linksText);

    // Format links into 3 columns
    $("#software-firmware-subclasses ul").makeacolumnlists({cols:3,colWidth:220,equalHeight:false,startN:1});
    
  }

} // end addSoftwareFirmwareSubClassLinks




function addSearchResultsFilter() {

  //add index column with all content.
  $(".filterable li.search-result h3").each(function(){  
    var t = $(this).text().toLowerCase();
    $("<div class='indexColumn'></div>").hide().text(t).insertBefore($(this));
  }); //each search result

  $("#FilterTextBox").keyup(function(){  
    var s = $(this).val().toLowerCase().split(" ");  
    // show all resources  
    $(".filterable li.search-result:hidden").show();
    $.each(s, function(){  
      $(".filterable div.indexColumn:not(:contains('" + this + "'))").parent("li.search-result").each(function() {
        $(this).hide();
      });
    });//each

  });//key up.

} // end of addSearchResultsFilter()


function createSecondLevelTabs() {

  // make second level tabs filter based on system

  var filterClass = $(document).getUrlParam("class");
  if (filterClass == null) {
    filterClass = "clp25";
  }
  var system = $(document).getUrlParam("system");
  if (system == null) {
    system = "all";
  }

  var status = $(document).getUrlParam("status");
  if (status == null) {
    status = "";
  }

  if (status.length) {
  
    // set the selected tab
    $("#filter-discontinued").addClass("selectedTab");

  } else {
  
    // create tabs
    var ulHtml;
    if (filterClass == "clp25") {
      ulHtml = '<ul class="tabs-level2-list ' + system + '"><li id="second-level-all"><a>All</a></li><li id="second-level-conventional"><a>Conventional</a></li><li id="second-level-conventionalsimulcast"><a>Conventional Simulcast</a></li><li id="second-level-trunked"><a>Trunked</a></li><li id="second-level-trunkedsimulcast"><a>Trunked Simulcast</a></li></ul>';
    } else if (filterClass == "clanalog") {
      ulHtml = '<ul class="tabs-level2-list ' + system + '"><li id="second-level-all"><a>All</a></li><li id="second-level-conventional"><a>Conventional</a></li><li id="second-level-conventionalqs"><a>Conventional QS</a></li><li id="second-level-trunkedmpt"><a>Trunked MPT</a></li></ul>';
    }

    // set the selected tab
    $("#filter-" + filterClass).addClass("selectedTab");

    // add tabs after first level tabs
    $("#tabs-level2-content").before(ulHtml);

    // set the selected second level tab
    $("#second-level-" + system).addClass("selectedTab");

    // add hover to li elements to fix IE6 bug
    $("ul.tabs-level2-list li").hover(function() {
      $(this).addClass("hover");
    }, function() {
      $(this).removeClass("hover");
    });

    // add links to new tabs
    var allHref = $("#filter-" + filterClass + " a").attr("href");
    $("#second-level-all").attr("href", allHref);

    if (filterClass == "clp25") {

      var conventionalHref, conventionalSimHref, trunkedHref, trunkedSimHref;
      allHref = '?class=clp25';
      conventionalHref = '?class=clp25&system=conventional&system1=sysp25conventional';
      conventionalSimHref = '?class=clp25&system=conventionalsimulcast&system1=sysp25conventionalsimulcast';
      trunkedHref = '?class=clp25&system=trunked&system1=sysp25trunked';
      trunkedSimHref = '?class=clp25&system=trunkedsimulcast&system1=sysp25trunkedsimulcast';

      $("#second-level-all a").attr("href", allHref);
      $("#second-level-conventional a").attr("href", conventionalHref);
      $("#second-level-conventionalsimulcast a").attr("href", conventionalSimHref);
      $("#second-level-trunked a").attr("href", trunkedHref);
      $("#second-level-trunkedsimulcast a").attr("href", trunkedSimHref);

    } else {

      var conventionalQSHref, trunkedMPTHref;

      allHref = '?class=clanalog';
      conventionalHref = '?class=clanalog&system=conventional&system1=sysanalogconventional';
      conventionalQSHref = '?class=clanalog&system=conventionalqs&system1=sysanalogconventionalqs';
      trunkedMPTHref = '?class=clanalog&system=trunkedmpt&system1=sysanalogtrunkedmpt';

      $("#second-level-all a").attr("href", allHref);
      $("#second-level-conventional a").attr("href", conventionalHref);
      $("#second-level-conventionalqs a").attr("href", conventionalQSHref);
      $("#second-level-trunkedmpt a").attr("href", trunkedMPTHref);

    }
    
  }
  

} // end of createSecondLevelTabs()



function addAutoCompleteToProductField() {

  // hide select box of products and show text input field
  $("#product-autocomplete-text").show().DefaultValue("Enter product name");
  $("#queries_product_query").hide();
  
  // if a select box has a value already selected (from previous search) then populate this value into the text box
  $("#queries_product_query option:selected").each(function() {
    $("#product-autocomplete-text").val($(this).text());
  });

  // create products array from select list
  var products = [];
  var i = 0;
  $("#queries_product_query option").each(function() {
    products[i++] = $(this).text();
  });

  // make the input text field auto complete based on values in the products array
  $("#product-autocomplete-text").autocomplete(products);

  // when the user submits the form, relfect the change in the text field back to the hidden select box
  $("#search_page_504").submit(function() {

    var selectedValue = $("#product-autocomplete-text").val();
  
    // remove current selection from select box
    $("#queries_product_query option").removeAttr("selected");
    
    $("#queries_product_query option").each(function() {

      if ($(this).text() == selectedValue) {
        $(this).attr("selected","selected");
      }
    
    });
  
  });

  // Enter default value for autocomplete box if no current value
  $("#product-autocomplete-text").DefaultValue("Enter product name");

} // end of addAutoCompleteToProductField()


function removeEmptyMetadataFields() {

  $("span.resource-metadata-detail").each(function() {
    if ($(this).text() == "") {
      $(this).parent("span").hide();
    };
  });

} // end of removeEmptyMetadataFields()



function formatSearchTerms() {

  $("span.format-search-term").each(function() {
    var term = $(this).find("ul li").html();
    $(this).remove("ul").html(term).show();
  });

};  // end of formatSearchTerms()


function formatResourceMetadata() {

  // If there is no unique id for a resource then hide the whole span (this hides the comma too!)
  $("span.resource-metadata-unique-id").each(function() {

    if ($(this).text() == ",") {
      $(this).remove();
    }
  
  });

  // Convert file size units (kb, mb, etc.) into captials (KB, MB, etc.)
  $("span.file-size").each(function() {
  
    var fileSize = $(this).text();
    fileSize = fileSize.toUpperCase();
    $(this).text(fileSize);
  
  });

}; // end of formatResourceMetadata



function showOnlyProductsInChosenFamilyForSearch() {

  // Move product checkboxes from their initial location so that they live as hidden sub lists under each of the family checkboxes. When the family checkbox is ticked, the list of products in that family drops down.
  $("div#products-in-families ul").each(function() {
  
    // Create empty unordered list underneath the corresponding family checkbox
    var familyMetadataKey = $(this).attr("id");
    var checkboxLabel = $("div#search-family ul li label[for='queries_family_query_" + familyMetadataKey + "']");
    checkboxLabel.after('<ul class="' + familyMetadataKey + ' hide"></ul>');
    var unorderedList = checkboxLabel.siblings("ul");


    // Loop through products in family and move the (real) product checkbox to live underneath the family checkbox
    $(this).find("li").each(function() {
    
      var productMetadataKey = $(this).text();
      while (productMetadataKey.indexOf(' ') != -1) {
        productMetadataKey = productMetadataKey.replace(/ /, "");
      }

      var inputObject = $("div#search-products ul li input[value='" + productMetadataKey + "']");
      var liToAppend = inputObject.parent("li");
      unorderedList.append(liToAppend);
    });
  
  });

  // When the user chooses a Family, show the Products for this Family.
  $("div#search-family ul li input").click(function() {
  
    if ($(this).attr("checked")) {
      $(this).siblings("ul").slideDown();
    
    } else {

      // Hide and untick all input boxes in this ul
      $(this).siblings("ul").slideUp().find("li input:checked").click();
    }
  
  });
  
  // On page load, show the products for the families that are ticked
  $("div#search-results ul li input:checked, #manage-resources-search-fields ul li input:checked").each(function() {

    if ($(this).attr("checked")) {
  
      $(this).siblings("ul").show();
  
    } else {
  
      // Hide and untick all input boxes in this ul
      $(this).siblings("ul").slideUp().find("li input:checked").click();
    }

  });

}; // end of showOnlyProductsInChosenFamilyForSearch()



function clearAllSearchFiltersButton() {

  // When 'Clear all filters' button is clicked, untick all the metadata search fields.
  $("#clear-all-search-filters").click(function(){
    $("#search-fields input:checkbox").attr("checked", "");
  });

}; // end of clearAllSearchFiltersButton()



function addDateSortingForResourcesTable() {

  // As dates printed are in the format 'Mon year' (e.g. Apr 2009), we need to populate the hidden column with class="date-sorting' with data in the format 'yyyymm' (e.g. 200904') so that we can sort dates.
  $("div.tabs-level2 td.date").each(function() {
  
    var dateString = $(this).text();
    if (dateString != "") {

      var month = dateString.substring(0,3);
      var year = dateString.substring(4);
      var dateInMinutesSince1970 = Date.parse(month + " 1, " + year);
      var dateObject = new Date();

      dateObject.setTime(dateInMinutesSince1970);
      month = dateObject.getMonth() + 1;
      month += "";
      if (month.length == 1) {
        month = "0" + month;
      }
      $(this).siblings("td.date-sorting").text(year + month);

    }
  
  });

}; // end of addDateSortingForResourcesTable()



function changeDateSortingLinkForResourcesTable() {

  // When the date column is sorted, use the hidden date-sorting column instead
  $("div.tabs-level2 th.date").click(function() {
  
    $("div.tabs-level2 th.date-sorting").click();
    return false;

  });

  // Click the Release Date column twice on page load so that the default sorting on the table is in reverse chronological order by Release Date.
  $("div.tabs-level2 th.date").click().click();

}; // end of changeDateSortingLinkForResourcesTable()



function log(logStr) {

  if (typeof window.loadFirebugConsole != "undefined") {
    console.log(logStr);
  }

} // end of log

  

function addPagination() {

  var totalResults = $(".search-result").length;
  var noInBatch = 20;
  var resultNo = 0;
  
  if (totalResults <= noInBatch) {

    $("#show-more-results").hide();

  } else {

    var noOfResultsLeftToShow = Math.min(noInBatch, totalResults - noInBatch);
//    var moreResultsHTML = '<p>Currently showing <span id="current-results">' + noInBatch + '</span> of ' + totalResults + ' results.</p><p><a id="show-more-results-link">Show <span id="no-in-next-batch">' + noOfResultsLeftToShow + '</span> more results</a></p>';
    var moreResultsHTML = '<p><a id="show-more-results-link">Show <span id="no-in-next-batch">' + noOfResultsLeftToShow + '</span> more results</a></p>';
    $("#show-more-results").html(moreResultsHTML);
    
    $(".search-result").each(function() {

      if (resultNo >= noInBatch) {
        $(this).hide();
      }
      resultNo++;

    });

    $("#show-more-results").click(function() {
    
      var totalResults = $(".search-result").length;
      var visibleResults = $(".search-result:visible").length;
      var noInBatch = 20;
      var noInNextBatch = Math.min(noInBatch, totalResults - (visibleResults));
      var resultNo = 0;

      // Show next set of results
      $(".search-result:hidden").each(function() {
      
        if (resultNo < noInNextBatch) {
          $(this).show();
        }
        resultNo++;

      });
      
      visibleResults += noInNextBatch;
      noInNextBatch = Math.min(noInBatch, totalResults - (visibleResults));
      
      // If there are more results to show, amend the Show More Results text. Otherwise remove it.
      if (visibleResults != totalResults) {
        $("#current-results").text(visibleResults);
        $("#no-in-next-batch").text(noInNextBatch);
      } else {
        $("#show-more-results").remove();
      }
      
    
    });
  
  }
    
} // end of addPagination



function setupResourcesFilterBox() {

  $("#show-product-filter-box a").click(function() {
  
    $("#product-filter-resources").slideDown();
//    $("#show-product-filter-box").html('<img src="/__data/assets/image/0003/6168/subtract-icon.gif" /> Filter resources on this page');
    $("#show-product-filter-box").slideUp();
  
  });  
  
} // end of setupResourcesFilterBox



function createHomepageTabs() {

  // When the user clicks on a Recently Updated Files tab, show the relevant table and hide the others. Also, make current tab highlighted by adding the class selectedTab to the list item.
  $("#all-files-tab a").click(function() {
  
    $("div.tabs-level2 table[id!='homepage-all-files']").hide();
    $("#homepage-all-files").show();

    $("ul.tabs-level1-list li.selectedTab").removeClass("selectedTab");
    $(this).parent("li").addClass("selectedTab");

  });

  $("#software-tab a").click(function() {
  
    $("div.tabs-level2 table[id!='homepage-software']").hide();
    $("#homepage-software").show();
  
    $("ul.tabs-level1-list li.selectedTab").removeClass("selectedTab");
    $(this).parent("li").addClass("selectedTab");

  });

  $("#firmware-tab a").click(function() {
  
    $("div.tabs-level2 table[id!='homepage-firmware']").hide();
    $("#homepage-firmware").show();
  
    $("ul.tabs-level1-list li.selectedTab").removeClass("selectedTab");
    $(this).parent("li").addClass("selectedTab");

  });

} // end of createHomepageTabs



function setupListOfProducts() {

  $("#show-all-products, #show-all-products-image").click(function() {
  
    // Slide the list of families down
    $("#show-all-products, #show-all-products-image").hide();
    $("#show-all-products").after("<h3>All products</h3>");
    $("#list-of-families ul").slideDown();
    // $("#show-all-products-image img").attr("src", "/__data/assets/image/0003/6168/subtract-icon.gif");
    
  
  });
  
} // end setupListOfProducts


function makeProductsFiltersSticky() {

  // If a cookie is set storing the last product filter used by a user, then add this filter to all product links
  var filter = $.cookie("product-filter");
  
  if (filter != null) {

    addFilterToProductLinks(filter);
  
  }

} // end makeProductsFiltersSticky



function addFilterToProductLinks(filter) {

  var href, startOfQueryString;
  
  $("a.product-link").each(function() {

    href = $(this).attr("href");
    startOfQueryString = href.indexOf("?");

    // We want the href without any existing query string
    if (startOfQueryString > 0) {
      href = href.substring(0, startOfQueryString);
    }

    // If filter is a user task, we need to add an additional parameter to the query string
    if (filter.substring(0,2) == "ut") {

      href += "?SQ_PAINT_LAYOUT_NAME=usertasks&usertask=" + filter;

    } else {

      href += "?SQ_PAINT_LAYOUT_NAME=" + filter;
    }

    $(this).attr("href", href);

  });
  
  // Refresh cookie
  setCookie("product-filter", filter, "/", 10);

} // end addFilterToProductLinks



function setCookie (name, value, path, minutes) {

  var date = new Date();
  date.setTime(date.getTime() + (minutes * 60 * 1000));
  $.cookie(name, value, { path: path, expires: date });


} // setCookie



function setCookieWhenProductLinksClicked() {

  var filter;
  var startPos;

  $("div.product ul li a").click(function() {
  
    // The filter is the value component of the SQ_PAINT_LAYOUT_NAME parameter in the url
    filter = $(this).attr("href");
    startPos = filter.indexOf("SQ_PAINT_LAYOUT_NAME=");
    filter = filter.substring(startPos + 21);
    
    // Set cookie
    setCookie("product-filter", filter, "/", 10);
  
  });

} // end setCookieWhenProductLinksClicked