whitepages.results = function() {};
whitepages.results.page_done = false;
whitepages.results.events_attached = 0;

// this provides the hover state of multiple results
whitepages.results.attach_hover = function() {
  var result_set = $('div.result');
  // Using polling, rather than $(document).ready(), because it's faster.
  if (result_set.length <= whitepages.results.events_attached || whitepages.events_attached < 10) {
    setTimeout(whitepages.results.attach_hover, 50);
    return;
  }
  result_set.hover(
    function () {
      $(this).addClass('highlighted');
    }, 
    function () {
      $(this).removeClass('highlighted');
    }
  );
  whitepages.results.events_attached = result_set.length;
  // Edge case: When rendering slowly, it is possible to do a partial load of the listing set, and then poll.
  // This ensures that everything is covered.
  if (whitepages.events_attached < 10 && !whitepages.results.page_done) setTimeout(whitepages.results.attach_hover, 50);
};

whitepages.results.attach_hover(); // Begin polling.

$(document).ready(function() {
  // Inform redundancy that everything is done.
  whitepages.results.page_done = true;
  
  var categories_div_max_height = 180;
  var categories = $('#business_more_categories');
  if (categories) {
    if (categories.height() > categories_div_max_height) {
      categories.height(categories_div_max_height + 'px');
    }
  }

  var filters_div_max_height = 180;
  var filters = $('#biz_location_filters');
  if (filters) {
    if (filters.height() > filters_div_max_height) {
      filters.height(filters_div_max_height + 'px');
    }
  }

});

whitepages.results.sort_chosen = function(token)
{
  var selected = $('#s_b option:selected').val();
  if (selected != '')
  {
    var url = $.query.set('s_b', selected).set('page', '1').set('t', token);
    window.location.href = url.toString();
  }
}

// Sends omniture tracking data for sort change on results page
whitepages.results.sort_chosen_business_track = function(sender)
{
 	var tracking_desc = sender[sender.selectedIndex].innerHTML;
  whitepages.analytics.track_click(this, {events:['general_interaction'], evars:{'listing_interaction_evar':'BS: Sort: ' + tracking_desc}});
}

// THIS SERVES THE SECOND AD ON THE SINGLE AND MULTIPLE RESULTS PAGES
// In order for this to work, the page must have an empty div with the id 'second_ad'
// binding the load event to the window is basically attaching an event listener to window.load
$(window).bind("load", function() {
    // first we get the height of the div the contains the ad.
    // If there is no right rail div, then make this divh size big enough that it doesn't show a right_rail_2
    var divh = $('#wpn_ad_content_right_rail').length > 0 ? document.getElementById('wpn_ad_content_right_rail').offsetHeight : '500';
    // we're using 305px as our dividing line. Most med_rect ads are 300x250, but FF adds 
    // a couple of pixels to the images for some reason, and just incase someone decides 
    // to put a square 300x300 ad in that spot, we're covered.
    if (divh < 305) {
      // Atlas hserver specific variables go here.
      var rand = (Math.random().toString()).substring(2,11);
      var pageid = (Math.random().toString()).substring(2,11);
      // the jquery syntax here is the same as using a getElementById and innerHTML call.
      // SANDBOX: var ad_call = 'http://whitesb1.adbureau.net/hserver/random=' + rand + '/pageid=' + pageid + '/AAMSZ=right_rail2' + rsi_data + '/site=WHITEPAGES/area=RESULTS';
      var ad_call = whitepages.page.data.ad_server  +'/hserver/random=' + rand + '/pageid=' + pageid + '/AAMSZ=right_rail2' + rsi_data + '/site=' + whitepages.page.data.admin_site_name  + '/area=' + whitepages.page.data.atlas_page_name;
      $('#second_ad').html('<iframe src="' + ad_call + '" scrolling="no" hspace="0" vspace="0" frameborder="0" marginheight="0" marginwidth="0" width="300" height=250" allowtransparency="true" test="test"></iframe>');
    }
  });

// this takes the listing that is provided via DAS on the site and turns the html breaks into an EOL character for the text box.
// this probably won't be necessary when we remove the text box later on.
whitepages.results.listingToSend = function(listing) {
  // pass listing content into message box
  var content = listing.split('<br />');
  var display = '';
  // try to jquery-ize the array
  for ( i=0; i < content.length; i++ ) {
    if (content[i] != '') {
      display += content[i] + "\n";
    }
  }
  $("#message_text").val( display );
}

whitepages.results.validateListingToSend = function(myForm) {
  var errors = '';

  if (myForm.to_phone) {
	  errors += whitepages.ui.validatePhone(myForm.to_phone, '#to_error_message');
	  errors += whitepages.ui.validatePhone(myForm.from_phone, '#from_error_message');
  } else {
	  errors += whitepages.ui.validateEmail(myForm.to_cell, '#to_error_message');
	  errors += whitepages.ui.validateEmail(myForm.from_cell, '#from_error_message');
  }
  errors += whitepages.ui.validateText(myForm.message_text, '#text_error_message');

  if (errors != '') {
    return false;
  }
  return true;
}

// this takes the form data from the send to phone feature and sends it to a users phone.
whitepages.results.sendListing = function(type, send_listing_url, thank_you_url) {
  var send = document.getElementById('send');
  var to_cell   = send.to_phone.value;
  var from_cell = send.from_phone.value;
  var message   = escape( send.message_text.value.replace(/\n/g,"\r\n") );

  // following variables are to set height and width of loading icon div
  var h = $("#sendListingDiv").height();
  var w = $("#sendListingDiv").width();

  // run the loader while the ajax runs through it's routine and before the thank you page pops.
  $("#sendListingDiv").empty();
  whitepages.ui.runLoader();
  $("#wp_popup_loading").height(h).width(w);

  $("#wp_popup_inner").load(thank_you_url, '', function() {
    $("#listing_type").html( type );
    var url_and_data = send_listing_url.split('?');
    $.ajax({
      type: "GET",
      url: url_and_data[0],
      data: "to=" + to_cell + "&from=" + from_cell + "&message=" + message + url_and_data[1]
      });
  });
}

whitepages.results.sendBusinessListing = function()
{
  var send_form = $('form#send');
  var action = send_form.attr('action');
  
  var data = {};
  data.to = $('#to_val').val();
  data.from = $('#from_val').val();
  data.uid = $('#uid').val();
  
  // following variables are to set height and width of loading icon div
  var h = $("#sendListingDiv").height();
  var w = $("#sendListingDiv").width();

  // run the loader while the ajax runs through it's routine and before the thank you page pops.
  $("#sendListingDiv").empty();
  whitepages.ui.runLoader();
  $("#wp_popup_loading").height(h).width(w);

  $("#wp_popup_inner").load(action, data);
};

// this loads a half_rect ad for pop-ups that appear on the page after the original ad call.
whitepages.results.loadHalfRect = function(adserver) {
  var rand = (Math.random().toString()).substring(2,11);
  var pageid = (Math.random().toString()).substring(2,11);
  var ad_call = adserver + '/hserver/random=' + rand + '/pageid=' + pageid + '/AAMSZ=half_rect' + rsi_data + '/site=WEBLAB';
  $('#send_listing_thanks_ad').html('<iframe src="' + ad_call + '" scrolling="no" hspace="0" vspace="0" frameborder="0" marginheight="0" marginwidth="0" width="300" height="100" allowtransparency="true" test="test"></iframe>');
}

whitepages.results.toggle_more_business_categories = function(caller)
{
  whitepages.ui.show_div('business_more_categories');
}

whitepages.results.toggle_show_business_location_filters = function(caller)
{
  whitepages.ui.show_div('biz_location_filters');
}

whitepages.results.social_link_click = function(e,linktype) {
  evar_value = 'Facebook';
  if(linktype == 'twitter'){
    evar_value = 'Twitter';
  }else if(linktype == 'linkedin'){
    evar_value = 'LinkedIn';  
  }
  
  whitepages.analytics.track_click(e, {events:['social_link'], evars: {'social_link_evar': evar_value}, link_type: 'e'});
}


whitepages.results.track_print = function(tracking_url)
{
  // We simply create a new image and set the src to the tracking URL. This
  // basically does a "fire and forget" request for us.
  (new Image).src = tracking_url;
};


/*
 * delete_photo
 *
 * REQUIRES:    jquery
 * DESCRIPTION: This method calls the action that will delete a photo
 *
 * PARAMETERS:
 *   url - URL to delete a photo
 *   redirect - URL to redirect to after the response returns a success
 *   message_id - Element id where message is displayed
 *
 */
whitepages.results.delete_photo = function(url, redirect, message_id) {
  $('#'+message_id).css('color','#54B948').html('Removing photo... Please wait while we<br/>update your listing.');
  var refreshId = setInterval(function() {
    $.ajax({
      url: '/listing/delete_photo?listing_id=' + url,
      success: function(data) {
        window.location.href=redirect;
      }
    });
  }, 1000);
}


/*
 * check_photo_status
 *
 * REQUIRES:    jquery
 * DESCRIPTION: This method calls the action to check the status of a photo
 *
 * PARAMETERS:
 *
 */
whitepages.results.check_photo_status = function() {
	var refreshId = setInterval(function() {
		$.ajax({
		  url: '/listing/check_photo',
		  success: function(data) {
		    console.log(data);
		  }
		});
	}, 1000);
}

/*
 * report_inappropriate_photo
 *
 * REQUIRES:    jquery
 * DESCRIPTION: This method calls the action to mark a photo as inappropriate in the logs.
 *
 * PARAMETERS:
 *	photo_id - ID path of photo that translates to location on LASS
 *  listing_id - ID of listing the photo is associated with
 *
 */
whitepages.results.report_inappropriate_photo = function(photo_id, listing_id) {
	$('#mark_photo').addClass('marked');
	$.ajax({
		url: '/report_photo/?listing_id=' + listing_id + '&photo_id=' + photo_id,
	  success: function(data) {
	    // Action for success
	  }
	});
}

