//
// Directory listings core javascript
//
// Author:  Andrew Waer
// Date:    March 2009
//
// Requires: Prototype.js, EI.Geolocation
// 
// This namespace is for geocoding functionality. 
// 
// EI.Listings.setSpecialty() must be passed a value for successful instantiation
// 

if (typeof EI != 'undefined') {

  EI.namespace('Listings');

  EI.Listings = function() {

    var self = this;

    var _specialty_id;
    var _listings;
    var _listings_api_url = 'http://www.docshop.com/cgi-opt/geolist.cgi';
    var _location = new EI.Geolocation();
    var _default_search_radius = 100;

    function getParams(callback) {
      return {
        latitude:     _location.latitude,
        longitude:    _location.longitude,
        radius:       _default_search_radius,
        specialty_id: _specialty_id,
        callback: callback || 'EI.Listings.setListings'
      }
    }

    // Removes script tag from document <head>
    // Called automatically by anonymous timeout set by appendScriptElement
    // 
    function removeScriptElement(id) {
      if (headElem = document.getElementsByTagName('head')[0]) headElem.removeChild($(id));
    }

    // Generates a random valid ID for usage with DOM elements
    // 
    function generateRandomElementId() {
      return '_EI-' + (new Date).getTime().toString(36);
    }

    // Creates script tag and appends to document <head>
    // 
    function appendScriptElement(src) {
      var scriptElem = document.createElement('script');
      var scriptId = generateRandomElementId();

      scriptElem.setAttribute('type', 'text/javascript');
      scriptElem.setAttribute('charset', 'UTF-8');
      scriptElem.setAttribute('id', scriptId)
      scriptElem.setAttribute('src', src);

      // Adds script tag and set timeout to remove after 5 seconds
      if (headElem = document.getElementsByTagName('head')[0]) {
        headElem.appendChild(scriptElem);
        window.setTimeout(function(){ removeScriptElement($(scriptId)) }, 5000);
      }
    }

    return {

      getLocation: function() {
        return _location;
      },

      setSpecialty: function(specialty_id) {
        if (specialty_id) {
          _specialty_id = specialty_id;
          this.findListings();
        }
      },

      findListings: function(callback) {
        // Append script tag to call remote service
        if (_specialty_id) {
          var script_src = _listings_api_url  + '?' + $H( getParams(callback) ).toQueryString();
          appendScriptElement(script_src);
        }
      },

      setListings: function(data) {
        if (typeof data == 'object')
          _listings = data;
      },

      getListings: function() {
        return _listings;
      }

    }
  }();

}