// whitepages.survey namespace
if (typeof(whitepages.publicSearch) == 'undefined') { whitepages.publicSearch = function() {} }
if (typeof(whitepages.publicSearch.parser) == 'undefined') { 
  whitepages.publicSearch.parser = function() {
    // Constuctor
    
    // Log object to hold all data needed for logging to back-end
    this.Log = function() {
      this.provider  = '';
      this.pagename  = '';
      this.results   = '';
      this.response  = '';
      this.error     = '';
      this.query     = '';
      this.startTime = 0;
      this.endTime   = 0; 
      this.loadTime  = 0;
    }

    this.fallbackTemplate = null;
    this.successTemplate = null;

  }
}

/**
 * Public properties
 */
whitepages.publicSearch.parser.prototype.maxResults = 0; // int of the max results allowed.
whitepages.publicSearch.parser.prototype.toggle = []; // array of strings cointaining class names to toggle between.
whitepages.publicSearch.parser.prototype.provider = ''; // String describing provider name.
whitepages.publicSearch.parser.prototype.repeatContainer = {}; // DOM element.
whitepages.publicSearch.parser.prototype.repeatPlaceholder = {}; // DOM element.
whitepages.publicSearch.parser.prototype.data = {}; // Data to query the API with.

whitepages.publicSearch.parser.prototype.xhr = {}; // XHR object 


/**
 * Static Methods
 */


/**
 * Instance Methods
 */




/**
 * populateTemplate fills the ad template with the data from the structure and displays it.
 *
 * @param data {object} is a formatted Data structure of the data returned from the public search
 */
whitepages.publicSearch.parser.prototype.populateTemplate = function(data, status) {

  // DEBUG: alert('populateTemplate running -- status: ' + status);
  
  // Process success template
  var $success = $(this.successTemplate);
  var $fallback = $(this.fallbackTemplate);
  var template = $success.html();
  // The repeat template comes from the DOM, so it has some extra tbody tags in it, and some of our tokens have been escaped.  Undo this.
  var repeatTmp = $(this.repeatContainer).html().replace(/\<tbody\>/i,'').replace(/\<\/tbody\>/i,'').replace(/\%5B/g, '[').replace(/\%5D/g, ']');
  var toggleLen = this.toggle.length;
  var replace = '';

  if (data.length == 0) {
    // If no results came back, show the fallback form.
    $fallback.show();
  } else {
    // We have results so lets display them
    for (var i = 0, l = data.length; i < l && i < this.maxResults ; i++) {
      var tmp = repeatTmp;
      tmp = tmp.replace(/\[\[TOGGLE\]\]/g, this.toggle[i % toggleLen]);
      tmp = tmp.replace(/\[\[fname\]\]/g, data[i]['fname']);
      tmp = tmp.replace(/\[\[lname\]\]/g, data[i]['lname']);
      tmp = tmp.replace(/\[\[mname\]\]/g, data[i]['mname']);
      tmp = tmp.replace(/\[\[displayname\]\]/g, data[i]['displayname']);
      tmp = tmp.replace(/\[\[city\]\]/g, data[i]['city']);
      tmp = tmp.replace(/\[\[state\]\]/g, data[i]['state']);
      tmp = tmp.replace(/\[\[zip\]\]/g, data[i]['zip']);
      tmp = tmp.replace(/\[\[age\]\]/g, data[i]['age']);
      tmp = tmp.replace(/\[\[email\]\]/g, data[i]['email']);
      tmp = tmp.replace(/\[\[results\]\]/g, data.length);
      tmp = tmp.replace(/\[\[aux\]\]/g, data[i]['aux']);
      replace += tmp;
    }
  
    template = template.replace(/\[\[fname\]\]/g, data[0]['fname']);
    template = template.replace(/\[\[lname\]\]/g, data[0]['lname']);
    template = template.replace(/\[\[mname\]\]/g, data[0]['mname']);
    template = template.replace(/\[\[displayname\]\]/g, data[0]['displayname']);
    template = template.replace(/\[\[city\]\]/g, data[0]['city']);
    template = template.replace(/\[\[state\]\]/g, data[0]['state']);
    template = template.replace(/\[\[zip\]\]/g, data[0]['zip']);
    template = template.replace(/\[\[age\]\]/g, data[0]['age']);
    template = template.replace(/\[\[email\]\]/g, data[0]['email']);
    template = template.replace(/\[\[results\]\]/g, data.length);
    template = template.replace(/\[\[aux\]\]/g, data[0]['aux']);

    $success.html(template);
    $('#' + this.repeatPlaceholder.id).replaceWith(replace);
    $success.show();
  
  }

  // TODO: Log the query params
  this.Log.response = '200';
  this.Log.results = data.length;
  this.Log.endTime = new Date();
  this.Log.loadTime = this.Log.endTime - this.Log.startTime;
  this.Log.pagename = whitepages.page.data.admin_page_name;

}

/**
 * complete is a callback function used by the ajax call, and fires when the request
 * completes whether it was a success or fail.  We use this method to make the call
 * to the backend to log to the server if necessary.  This callback gets the full
 * XHR object back, so we can base this decision on the HTTP status.
 *
 */
whitepages.publicSearch.parser.prototype.complete = function(xhr, status, query) 
{
  // DEBUG: alert('running complete function.');

  // Turn the data object into a query string formatted string of key value pairs (&key=value)
  var dataMap = [];
  $.each(
    query,
    function(i, v) {
      dataMap.push(i + "=" + v);
    });
  this.Log.query = escape(dataMap.join("&"));

  // Only log errors to the server to save space.
  if (status != 'success') {
    this.logToServer();
  }
}

/**
 * error is a callback function for an error coming back from the ajax call.  Use
 * this function to set the fallback ad display, and then populate the rest of the 
 * log data.  Hold off on calling the logging method until complete event.
 *
 */
whitepages.publicSearch.parser.prototype.error = function(xhr, status) 
{
  // DEBUG: alert('ERROR: ' + whitepages.common.dump(this.Log));

  // Turn on the fallback ad
  $(this.fallbackTemplate).show();
  
  if (status == 'timeout') {
    this.Log.error = status;
  }

  try {
    this.Log.response = xhr.status;
  }
  catch(e) {
    // will usually occur if there is a network error in FF.  XHR.status is not available in those cases.
  }

  this.Log.results = 0; // Errors should have no data
  this.Log.endTime = new Date();
  this.Log.loadTime = this.Log.endTime - this.Log.startTime;
  this.Log.pagename = whitepages.page.data.admin_page_name;
}


/**
 * loadAdData loads the appropriate publicSearch data and populates the ad template from the Atlas creative.
 * It will also build a list of logging information and call a page that will log this in the backend.
 *
 * @param pProvider {string} is the name of the provider you wish to get data for
 * @param pQuery {object} is basically a hash of the query params to be passed in
 */
whitepages.publicSearch.parser.prototype.loadAdData = function() 
{
  this.Log.provider = this.provider;
  this.Log.startTime = new Date();

  whitepages.publicSearch.mapper.queryProvider(this.provider, this.data, this);
}

/**
 * logToServer takes the Log object and serializes it into a query string and makes a request to the server
 * so that the tlog can record it and stuff it in the data base
 */
whitepages.publicSearch.parser.prototype.logToServer = function() 
{
  // DEBUG: alert('logging to server');
  $.ajax({
      url: '/utility/log_public_search',
      type: 'GET',
      data: this.Log, 
      success: function () {
        // Ignore the response, we just wanted to send data to the server
      },
      error: function(xhr, status) {
        // Logging probably failed, but not much we can do about it here.
      }
    });
}

/**
 * setFallback is a simple setter for the fallbackTemplate
 *
 * @param fallback {object} reference to the fallback DOM object
 */
whitepages.publicSearch.parser.prototype.setFallback = function(fallback) {
  this.fallbackTemplate = fallback;
}

/**
 * setSuccess is a simple setter for the successTemplate
 *
 * @param success {object} reference to the success DOM object
 */
whitepages.publicSearch.parser.prototype.setSuccess = function(success) {
  this.successTemplate = success;
}


