<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xoomle="http://www.dentedreality.com.au/xoomle/docs/">

  <!-- include reference to document containing the developer's keys -->
  <xsl:import href="keys.xsl"/>

  <!-- setup the baseline queries -->
  <xsl:variable name="google">http://xoomle.dentedreality.com.au</xsl:variable>
  <xsl:variable name="google-search-base">
    <xsl:value-of select="concat($google, '/search')"/>
  </xsl:variable>
  <xsl:variable name="google-spelling-base">
    <xsl:value-of select="concat($google, '/spell')"/>
  </xsl:variable>
  <xsl:variable name="google-cache-base">
    <xsl:value-of select="concat($google, '/cache')"/>
  </xsl:variable>

  <!-- Obtain the first url from the search criteria -->
  <xsl:template name="feeling-lucky">
    <xsl:param name="search-term"/>

    <!-- Build the query string -->
    <xsl:variable name="google-query-string">
      <xsl:variable name="base-query">
        <xsl:call-template name="google-request">
          <xsl:with-param name="search-term" select="$search-term"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:value-of select="concat($base-query, '&amp;maxResults=1')"/>
    </xsl:variable>

    <xsl:variable name="google-results" select="document($google-query-string)"/>

    <xsl:value-of select="$google-results//xoomle:URL"/>
    
  </xsl:template>




  <!-- Perform the basic google search -->
  <xsl:template name="basic-search">
    <xsl:param name="search-term"/>

    <xsl:variable name="google-query-string">
      <xsl:call-template name="google-request">
        <xsl:with-param name="search-term" select="$search-term"/>
      </xsl:call-template>
    </xsl:variable>

    <xsl:variable name="google-results" select="document($google-query-string)"/>

    <xsl:copy-of select="$google-results"/>

  </xsl:template>



  <!-- Creates the core search query containing base URL, search terms and the developer key -->
  <xsl:template name="google-request">
    <xsl:param name="search-term"/>

    <!-- Remove extraneous whitespace, then substitue '+' for space characters -->
    <xsl:variable name="google-search">
      <xsl:value-of select="translate(normalize-space($search-term), ' ', '+')"/>
    </xsl:variable>

    <!-- Extract the google key from the $key document -->
    <xsl:variable name="google-key" select="document($key)//google"/>
    <xsl:value-of select="concat($google-search-base, '?q=', $google-search, '&amp;key=', $google-key)"/>

  </xsl:template>

</xsl:stylesheet>