// whitepages.survey namespace
if (typeof(whitepages.publicSearch) == 'undefined') { whitepages.publicSearch = function() {}; }
if (typeof(whitepages.publicSearch.mapper) == 'undefined') { whitepages.publicSearch.mapper = function() {}; }

whitepages.publicSearch.mapper.defaultTimeout = 8000; // Default timeout value

/**
 * queryProvider sends a request to the API of the specified provider with the specified query
 * string paramters.  It then recieves the response and creates a consistent data structure
 * with the respone data.
 *
 * @param pProvider {string}
 * @param pQuery {object} 
 */
whitepages.publicSearch.mapper.queryProvider = function (pProvider, pQuery, pParser) {
  
  /**
   * formatted data looks like:
   *   [
   *     {
   *       'fname'       : 'First',
   *       'mname'       : 'Middle',
   *       'lname'       : 'Last', 
   *       'displayname' : 'First [Middle ]Last', 
   *       'age'         : 32,
   *       'city'        : 'Seattle',
   *       'state'       : 'WA',
   *       'zip'         : '98101',
   *       'aux'         : 'foo and bar'
   *     },
   *     {etc...}
   *   ]
   * 
   */
  var formattedData = [];
  var APIURL = '';

  switch (pProvider) {
    case 'PeopleFinders': case 'PeopleFindersEmail':
	  APIURL = ( pProvider == 'PeopleFindersEmail' ) ? '/gateway/gpeople.xml' : '/gateway/people.xml';
      // Map data from our format to the format of the provider
	  var inputType = ( pProvider == 'PeopleFindersEmail' ) ? 'email' : 'name';
      inputData = {
            input : inputType, 
            fn : pQuery['fname'], 
            ln : pQuery['lname'], 
            state : pQuery['state'], 
            city : pQuery['city'] 
      };      
	  $.ajax({
        url: APIURL, 
        data: inputData, 
        dataType: 'xml',
        timeout: this.defaultTimeout,
        success: function (data, status) {
          var xmlData = data.documentElement
          $('record', xmlData).each(function (i) {
            // build formattedData
            var record = $(this);
            var newRecord = {};
            var tmpName = whitepages.publicSearch.mapper.correctNameCase($('name', record).text());
            tmpName = tmpName.split(',');
            newRecord['lname'] = tmpName[0];
            tmpName = tmpName[1].replace(' ', '').split(' ');
            newRecord['fname'] = tmpName[0];
            newRecord['mname'] = tmpName[1] || '';
            newRecord['displayname'] = newRecord['fname'] + ' ' + (newRecord['mname'] ? newRecord['mname'] + ' ' : '') + newRecord['lname'];
            newRecord['city'] = whitepages.publicSearch.mapper.correctNameCase($('city', record).text());
            newRecord['state'] = $('state', record).text();
            newRecord['zip'] = $('zip', record).text();
            newRecord['age'] = $('age', record).text();
			newRecord['email'] = $('email', record).text();
            formattedData.push(newRecord);
          });
          pParser.populateTemplate(formattedData, status); 
        },
        error: function (xhr, status, exception) {
          // handle error here.
          pParser.error(xhr, status);
        },
        complete: function (xhr, status) {
          // Call complete function to handle logging status'
          pParser.complete(xhr, status, inputData);
        }
      });
      break;

    case 'PeopleSearchMedia':     
      // Build XML request 
      var searchXML = '' +
        "<search>" +
          "<searchType>WPCPeopleSearch</searchType>" +
          "<searchCriteria>" +
            "<firstName>" + pQuery['fname'] + "</firstName>" +
            "<lastName>" + pQuery['lname'] + "</lastName>" +
            "<city>" + pQuery['city'] + "</city>" +
            "<state>" + pQuery['state'] + "</state>" +
          "</searchCriteria>" +
          "<identification>" +
            "<websiteKey>7</websiteKey>" +
            "<partnerID>WP-WPC</partnerID>" +
            "<partnerPassword>HjT3de9</partnerPassword>" +
            "<ipAddress>192.168.0.1</ipAddress>" +
          "</identification>" +
        "</search>";
      var inputData = { sSearchRequest: searchXML }
     
      /*  URL switching for different environments
         example:
         var urlsByEnv = {
           'development' : '/SearchServicePublicDev.asmx/SearchXML',
           'prod'  	 : '/SearchServicePublicProd.asmx/SearchXML',
           'qa'  	 : '/SearchServicePublicQA.asmx/SearchXML',
           'default'     : '/SearchServicePublic.asmx/SearchXML'
         };	*/
      var urlsByEnv = { 'default' : '/SearchServicePublic.asmx/SearchXML' };
      var APIURL = urlsByEnv[whitepages.page.data.environment] || urlsByEnv['default'];
      
      // make ajax call 
      $.ajax({
          url: APIURL,
	  	  data: inputData,
	  	  dataType: 'xml',
          contentType: 'text/xml',
	  	  timeout: this.defaultTimeout,
	  	  success: function ( data, status ) {
            var xmlData = data.documentElement;
            $( 'person', xmlData ).each( function(i) {
	      	  // build formattedData
	      	  var newRecord = {};
              newRecord['fname'] = $( this ).attr( 'firstName' );
              newRecord['mname'] = $( this ).attr( 'middleName' ) || '';
              newRecord['lname'] = $( this ).attr( 'lastName' );
              newRecord['displayname'] = $( this ).attr( 'fullName' );
              newRecord['age'] = $( this ).attr( 'displayAge' ) || '';
              newRecord['city'] = $( this ).attr( "city" );
              newRecord['state'] = $( this ).attr( "state" );
              newRecord['aux'] = $( this ).attr( 'urladdition' ).replace( /&amp;/g, '&' );
              formattedData.push( newRecord );
	    });
            pParser.populateTemplate( formattedData, status ); 
	  },
	  error: function ( xhr, status, exception ) {
	    // handle error here.
	    pParser.error( xhr, status );
	  },
	  complete: function ( xhr, status ) {
	    // Call complete function to handle logging status'
	    pParser.complete( xhr, status, inputData );
	  }   
	});
    break;

    case 'USSearch':
      APIURL = '/preview/xml/getdata';
      // Map data from our format to the format of the provider
      inputData = {
		searchType : 'name', 
		Password: 'W3', 
		UserName : 'W3', 
		searchFName : pQuery['fname'], 
		searchLName : pQuery['lname'], 
		searchCity : pQuery['city'], 
		searchState : pQuery['state'] 
	  };
      $.ajax({
        url: APIURL, 
        data: inputData, 
        dataType: 'xml',
        timeout: this.defaultTimeout,
        success: function( data, status ) {
          var xmlData = data.documentElement
          $( 'Profile', xmlData ).each( function(i) {
            // build formattedData
			var Identity = $( 'Identity', $( this ) );
			var Address= $( 'Address', $( this ) );
            var newRecord = {};
			newRecord['fname'] = $( 'FirstName', Identity ).text();
            newRecord['mname'] = $( 'MiddleName', Identity ).text() || '';
            newRecord['lname'] =  $( 'LastName', Identity ).text();
            newRecord['displayname'] = newRecord['fname'] + ' ' + ( newRecord['mname'] ? newRecord['mname'] + ' ' : '' ) + newRecord['lname'];
            newRecord['displayname'] = whitepages.publicSearch.mapper.correctNameCase( newRecord['displayname'] );
			newRecord['city'] = whitepages.publicSearch.mapper.correctNameCase( $( 'City', Address ).text() );
            newRecord['state'] = $( 'State', Address ).text();
            newRecord['zip'] = $( 'Zip', Address ).text();
            newRecord['age'] = $( 'Age', Identity ).text();
            formattedData.push( newRecord );
          });
          pParser.populateTemplate( formattedData, status ); 
        },
        error: function ( xhr, status, exception ) {
          // handle error here.
          pParser.error( xhr, status );
        },
        complete: function( xhr, status ) {
          // Call complete function to handle logging status'
          pParser.complete( xhr, status, inputData );
        }
      });
      break;
  }
}

/**
 * correctNameCase takes a name and returs it with the 'correct' capitalization.
 * 
 * @param pName {string} the string containing the name
 * @return {string} correctly capitalized name.
 */
whitepages.publicSearch.mapper.correctNameCase = function(pName) {
  var letters = pName.split('');
  for (var i=0, l=letters.length; i<l; i++) {
    if (i == 0 || letters[i-1] == ' ') {
      letters[i] = letters[i].toUpperCase();
    } else {
      letters[i] = letters[i].toLowerCase();
    }
  }

  return letters.join('');
}