// Create namespaces
if (typeof(whitepages.mapping) == "undefined") whitepages.mapping = function() {};
whitepages.mapping.virth = function() {};

/** WP: Global Variables */
whitepages.mapping.virth.map   = null; /** WP: Map object */
whitepages.mapping.virth.init  = null; /** WP: Object for storing search params */
whitepages.mapping.virth.default_location;   /** WP: Default location as VELatLong */
whitepages.mapping.virth.target_element = 'map_target'; // ID of div that map will be placed into
whitepages.mapping.virth.distance_unit = 'mi' // Use miles for distance unit
whitepages.mapping.virth.listings = [] // Listing IDs (result_id) that have pins mapped
whitepages.mapping.virth.mapShapes = [] // Array of ShapeIDs for mapped pins

whitepages.mapping.virth.init_virth = function(init_values)
{
  whitepages.mapping.virth.init = init_values;
  whitepages.mapping.virth.show_virth();
};

// Uses init object to specify VEMap options
whitepages.mapping.virth.set_options = function(init) {

  // VEDashboard
  switch(init.menu) {
      case 'tiny':
        whitepages.mapping.virth.map.SetDashboardSize(VEDashboardSize.Tiny);
        break;
      case 'normal':
        whitepages.mapping.virth.map.SetDashboardSize(VEDashboardSize.Normal);
        break;
      case 'none':
        whitepages.mapping.virth.map.HideDashboard();
        break;
      default:
        whitepages.mapping.virth.map.SetDashboardSize(VEDashboardSize.Small);
        break;
  }
  whitepages.mapping.virth.default_location = init.search_query;
  whitepages.mapping.virth.full_map = init.full_map || false;
};

whitepages.mapping.virth.show_virth = function()
{ 
  
  var ffv = 0;
  var ffn = "Firefox/"
  var ffp = navigator.userAgent.indexOf(ffn);
  if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
  if (ffv >= 1.5) {Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }}
  
  var init = whitepages.mapping.virth.init;
  
  whitepages.mapping.virth.map = new VEMap(whitepages.mapping.virth.target_element);
  whitepages.mapping.virth.set_options(init);
  whitepages.mapping.virth.hide_loader();

  if (init.listing_hash) {
    // Multiple listings
    map_options = new VEMapOptions();
    map_options.EnableBirdseye = false;
    whitepages.mapping.virth.map.LoadMap(null, null, null, init.fixed, null, null, null, map_options);
    whitepages.mapping.virth.process_multiple_pins();
        
    $(document).ready(function() {
      whitepages.mapping.virth.attach_events();
    });
  }
  else {
    // Single listing
    if (init.latitude && init.longitude) 
    {
      // Single listing with lat and long
      latLng = new VELatLong(init.latitude, init.longitude);
      whitepages.mapping.virth.map.LoadMap(latLng, null, null, init.fixed);
      whitepages.mapping.virth.place_pin(latLng);
    }
    else if (init.address || init.zip || init.city || init.state || init.country)
    {
      // Load the map behind the scenes first so we don't see a US map view while the geo-locating is happening
      whitepages.mapping.virth.map.LoadMap(null, null, null, init.fixed);
      whitepages.mapping.virth.map.Find(null, whitepages.mapping.virth.search_type(), null, null, null, null, null, null, false, null, whitepages.mapping.virth.get_coordinates);
    }
    
    // Map Zoom Level
    if (init.zoom) {
      whitepages.mapping.virth.map.SetZoomLevel(whitepages.mapping.virth.init.zoom);
    } else {
      whitepages.mapping.virth.map.SetZoomLevel(15);
    }
    whitepages.mapping.virth.map.AttachEvent("onmouseover", function() { return true; });
  }
  
  if (init.infoBox && !init.infoBox) {
    whitepages.mapping.virth.map.HideInfoBox();
  }
  if (init.wheelZoom && !init.wheelZoom) {
    whitepages.mapping.virth.map.AttachEvent("onmousewheel", function() { return true; });
  }

};

// This is a callback function. map.Find calls back into this.
whitepages.mapping.virth.get_coordinates = function(layer, whatResults, whereResults, hasMore) {
  whitepages.mapping.virth.place_pin(whereResults[0].LatLong);
};

whitepages.mapping.virth.get_sequential_coordinates = function(layer, whatResults, whereResults, hasMore) {
  var current_geocode = whitepages.mapping.virth.geocoder_queue.shift();
  whitepages.mapping.virth.place_pin(whereResults[0].LatLong, current_geocode.index);
  if (whitepages.mapping.virth.geocoder_queue.length > 0) whitepages.mapping.virth.geocoder_queue[0].geocode();
};

whitepages.mapping.virth.view_default_location = function(layer, whatResults, whereResults, hasMOre) {
  whitepages.mapping.virth.map.SetMapView([ whereResults[0].LatLong ]);
  if (whitepages.mapping.virth.default_location.indexOf(",") > -1)
    whitepages.mapping.virth.map.SetZoomLevel(12);
  else
    whitepages.mapping.virth.map.SetZoomLevel(5);
};

whitepages.mapping.virth.place_pin = function(lat_lng, listingId)
{
  try
  {
    var offset = parseInt(whitepages.mapping.virth.init.offset) || 0;
    var single_pin = typeof(listingId) == "undefined";
    var shape = new VEShape(VEShapeType.Pushpin, lat_lng);
    var icon;
    if (single_pin)
      icon = "<div id=\"pinLink\" class=\"pinLink\"></div>"
    else
      icon = "<div id=\"pinLink" + listingId + "\" class=\"pinLink\"><span>" + (offset+listingId) + "</span><img src=\"/common/images/mapping/map_pin.png\" /></div>"

    shape.SetCustomIcon(icon);
    if (single_pin) {
      shape.SetTitle(whitepages.mapping.virth.init.name);
      shape.SetDescription(whitepages.mapping.virth.init.address);
    } else {
      shape.shapeNum = listingId;
      shape.shapeID = 'pinShape' + listingId;
    }

    whitepages.mapping.virth.map.AddShape(shape);
    whitepages.mapping.virth.mapShapes.push(shape);
    return;
  }
  catch (e)
  {
    window.onerror = whitepages.mapping.virth.stop_error;
  }
};

whitepages.mapping.virth.process_multiple_pins = function()
{
  whitepages.mapping.virth.listings = eval(whitepages.mapping.virth.init.listing_hash);
  var mapPinsArray = [];
  whitepages.mapping.virth.geocoder_queue = [];
  
  for(j = 0; j < whitepages.mapping.virth.listings.length; j++) {
    var listing = whitepages.mapping.virth.listings[j];
    if (listing.address != '') {
      if ((listing.latitude == '' && listing.longitude == '')||(listing.latitude == '0.000000' && listing.longitude == '0.000000')) {
        whitepages.mapping.virth.geocoder_queue.push({ index: j+1, geocode: function() {whitepages.mapping.virth.map.Find(null, whitepages.mapping.virth.build_address(listing), null, null, null, null, null, null, false, false, whitepages.mapping.virth.get_sequential_coordinates); } });
        if (whitepages.mapping.virth.geocoder_queue.length == 1) whitepages.mapping.virth.geocoder_queue[0].geocode();
      } else {
        var latLng = new VELatLong(listing.latitude, listing.longitude);
        // Skip placing pins for area_only maps (area code pages).
				if (!whitepages.mapping.virth.init.area_only) {
					whitepages.mapping.virth.place_pin(latLng, j+1);
				}
	      mapPinsArray.push(latLng);
      }
    }
  }

  if (mapPinsArray.length > 0) {
    whitepages.mapping.virth.map.SetMapView(mapPinsArray);
		/*
		if (whitepages.mapping.virth.init.area_only) {
			// Zoom in a litle more for area maps.
			whitepages.mapping.virth.map.SetZoomLevel(whitepages.mapping.virth.map.GetZoomLevel()+1);
		}
		*/
  } else {
    if (whitepages.mapping.virth.default_location)
      whitepages.mapping.virth.map.Find(null, whitepages.mapping.virth.default_location, null, null, null, null, null, null, false, false, whitepages.mapping.virth.view_default_location);
    else
      whitepages.mapping.virth.map.SetZoomLevel(3);
  }
};

/**
 * This builds a string for VEMap.Find from the data available to us.
 * This is distinct from .search_type because listing provides a less complete string in the address field.
 */
whitepages.mapping.virth.build_address = function(listing) {
  var retVal = "";
  var init = listing;
  if ('address' in init && whitepages.mapping.virth.valid_init(init.address)){retVal+=init.address;}
  if ('city' in init && whitepages.mapping.virth.valid_init(init.city)){retVal+=", "+init.city;}
  if ('state' in init && whitepages.mapping.virth.valid_init(init.state)){retVal+=", "+init.state;}
  if ('zip' in init && whitepages.mapping.virth.valid_init(init.zip)){retVal+=" "+init.zip;}
  if ('country' in init && whitepages.mapping.virth.valid_init(init.country)){retVal+=", "+init.country;}
  else retVal = "US";
  return retVal;
};

whitepages.mapping.virth.hide_loader = function() {
  $('#mapLoader').hide();
  $('#' + whitepages.mapping.virth.target_element).show();
};

// Attach events to the results list for map interaction
whitepages.mapping.virth.attach_events = function()
{
  if (whitepages.mapping.virth.full_map) { whitepages.page.attach_events(); return; }
  var shapes = whitepages.mapping.virth.mapShapes;
  if (whitepages.mapping.virth.geocoder_queue.length > 0 || $("div.pinLink").length < shapes.length) { setTimeout(whitepages.mapping.virth.attach_events, 100); return; }
  
  // Events for Small Map on MR listings page
  whitepages.mapping.virth.map.AttachEvent("onmouseover", function(e) { return true; } );
  var shapes = whitepages.mapping.virth.mapShapes;
  for (i = 0; i < shapes.length; i++) {
    $("div.result").hover(function() { whitepages.mapping.virth.map_pin_highlight(this.id, true); },
                          function() { whitepages.mapping.virth.map_pin_highlight(this.id, false); });
    $("#pinLink" + shapes[i].shapeNum).mouseover(function() {
      whitepages.mapping.virth.map_pin_highlight(this.id, true);
    });
    $("#pinLink" + shapes[i].shapeNum).mouseout(function() {
      whitepages.mapping.virth.map_pin_highlight(this.id, false);
    });
    $("#pinLink" + shapes[i].shapeNum).click(function() {
      whitepages.mapping.virth.map_pin_click(this.id);
      setTimeout(function(){$("#map_target").one("click", whitepages.mapping.virth.hide_info_box);}, 100);
    });
  }
};

// Select pin on map corresponding to given result_id
whitepages.mapping.virth.map_pin_highlight = function(result_id,isHover)
{
  if (!whitepages.mapping.virth.full_map) whitepages.mapping.virth.result_highlight(result_id, isHover);
  
  whitepages.mapping.virth.not_mapped(whitepages.mapping.virth.get_shape_by_id(result_id.match(/\d+/g)) == null && isHover);
  if (!whitepages.mapping.virth.is_id_visible(result_id.match(/\d+/g))) return;

  var pin = document.getElementById("pinLink" + result_id.match(/\d+/g));
  var shape = document.getElementById(pin.parentNode.parentNode.id);
  
  if (isHover) {
    shape.style.zIndex = "1001";
    pin.className = "pinLink_hover";
  } else {
    shape.style.zIndex = "1000";
    pin.className = "pinLink";
  }
};

// Click on a pin (Small Map Only)
whitepages.mapping.virth.map_pin_click = function(result_id)
{
  var listingId = result_id.match(/\d+/g);
  var listing = whitepages.mapping.virth.listings[listingId-1];
  $("#map_target").click();
  
  if (listing.address != '') {
  
    var pin = $("#pinLink" + listingId);
    var curleft = curtop = 0;
    
    var infoBox = $("#customInfoBox");
    //infoBox.find('a:first').href = whitepages.mapping.virth.listings[listingId-1].link;
    infoBox.find('.titleLink').attr('href',listing.link);
    infoBox.find('.titleLink').html(listing.name);
    infoBox.find('.address').html(listing.address);
    infoBox.find('.cityState').html(listing.city + ", " + listing.state);
    infoBox.find('.detailLink').attr('href',listing.link);
    infoBox.find('.home_work_indicator').attr('src','/common/images/details/ICON_'+listing.listing_type+'.gif');
    infoBox.find('.helpfulLabel').html(listing.helpful_label);
    infoBox.find('.helpfulValue').html(listing.helpful_value);
    detail_link = $("<a href=\"" + listing.link + "\"></a>");
    infoBox.find('.icon_cell').attr({src: '/common/images/' + listing.cell_icon + '.gif',title: 'No cell phone or text messaging available for this listing'});
    if (listing.cell_icon.indexOf("icon_no_") < 0) infoBox.find('.icon_cell').wrap(detail_link).attr('title', 'You can contact this person by cell phone or text message');
    infoBox.find('.icon_phone').attr({src:'/common/images/' + listing.phone_icon + '.gif',title: 'No phone number available for this listing'});
    if (listing.phone_icon.indexOf("icon_no_") < 0) infoBox.find('.icon_phone').wrap(detail_link).attr('title', 'You can contact this person by phone');
    infoBox.find('.icon_email').attr({src:'/common/images/' + listing.email_icon + '.gif',title: 'No email available for this listing'});
    if (listing.email_icon.indexOf("icon_no_") < 0) infoBox.find('.icon_email').wrap(detail_link).attr('title', 'You can contact this person by email');

    if (listing.listing_type=='home' && listing.age_range) {
      infoBox.find('.age_range').css('display','block'); 
      infoBox.find('.helpful_info').addClass('solo'); 
      infoBox.find('.ageRangeValue').html(listing.age_range);
    } else {
      infoBox.find('.age_range').css('display','none'); 
      infoBox.find('.helpful_info').removeClass('solo'); 
    }
      
    
    var top = pin.offset().top-$("#map_div").offset().top;
    var left = pin.offset().left-$("#map_div").offset().left;

    infoBox.css({'top':top+'px','left':left+'px'});
    
    if (whitepages.mapping.virth.full_map) {
      infoBox.attr('class','large');

      // Reverse offset of InfoBox if pin is clicked too close to the window's edge
      if ((pin.offset().left + 270) > document.body.clientWidth) {
            infoBox.attr('class','large left');
            infoBox.css('left',left-285+'px');
      }
    }
                  
    $("#customInfoBox").css({'visibility':'visible'});
  }
};

// Hide the CustomInfoBox
whitepages.mapping.virth.hide_info_box = function() 
{
	$("#customInfoBox").css({'visibility':'hidden'});
};

// Highlight a result corresponding to the selected pin
whitepages.mapping.virth.result_highlight = function(result_id,isHover)
{
  var result = document.getElementById("result_" + result_id.match(/\d+/g));
                                       
  if (isHover) {
    result.className = "result highlighted";
  } else {
    result.className = "result";
  }
};

whitepages.mapping.virth.not_mapped = function(display)
{
  display ? $("#no_address_found").show() : $("#no_address_found").hide();
};

// Grab the listing detail link from a listing
whitepages.mapping.virth.get_listing_link = function(listingId)
{
  var resultLink = document.getElementById("result_" + listingId).getElementsByTagName('p')[0].getElementsByTagName('a')[0];
  return resultLink.href;
};

// This method is called if we can't add a custom pin to the map.
// We'll just return true instead of stopping or showing any sort
// of error to the user.
whitepages.mapping.virth.stop_error = function()
{
  return true;
};

whitepages.mapping.virth.search_type = function()
{
  var retVal;
  var init = whitepages.mapping.virth.init;
  if ('address' in init && whitepages.mapping.virth.valid_init(init.address)){retVal=init.address;}
  else if ('zip' in init && whitepages.mapping.virth.valid_init(init.zip)){retVal=init.zip;}
  else if ('city' in init && whitepages.mapping.virth.valid_init(init.city)){retVal=init.city;}
  else if ('state' in init && whitepages.mapping.virth.valid_init(init.state)){retVal=init.state;}
  else if ('country' in init && whitepages.mapping.virth.valid_init(init.country)){retVal=init.country;}
  else retVal = "US";
  return retVal;
};

whitepages.mapping.virth.valid_init = function(x)
{
  return (typeof(x) != 'undefined' && x != '') ? true : false;
};


whitepages.mapping.virth.get_route = function()
{
  try
  {
    whitepages.mapping.virth.map.DeleteAllShapes();
    whitepages.mapping.virth.delete_route();
    var start_str = $('#where2').val();
    if ($('#address2').val() != '')
    {
      start_str = $('#address2').val() + ', ' + start_str;
    }
    if (start_str == '')
    {
      start_str = null;
    }
    
    var end_str = $('#where1').val();
    if ($('#address1').val() != '')
    {
      end_str = $('#address1').val() + ', ' + end_str;
    }
    if (end_str == '')
    {
      end_str = null;
    }
    
    distance_type = (whitepages.mapping.virth.distance_unit == 'mi') ? VEDistanceUnit.Miles : VEDistanceUnit.Kilometers;
    whitepages.mapping.virth.map.GetRoute(start_str, end_str, distance_type, VERouteType.Quickest, whitepages.mapping.virth.on_got_route);
  }
  catch (err)
  {
    whitepages.mapping.virth.map.ShowMessage(err.message);
  }
};

whitepages.mapping.virth.delete_route = function()
{
  try
  {
    whitepages.mapping.virth.map.DeleteRoute();
  }
  catch (err)
  {
    whitepages.mapping.virth.map.ShowMessage(err.message);
  }
};

whitepages.mapping.virth.on_got_route = function(route)
{
  try 
  {
    if (route == null)
    {
      whitepages.directions.error_message = "Could not find directions."
      whitepages.directions.show_general_input_error();
      return false;
    }
    var is_ie6 = ('ActiveXObject' in window && !('XMLHttpRequest' in window));
		// pin replacement for driving directions (done here so it's after the old pin spaces load
    if (is_ie6) {
			$(".MSVE_Map a:first img").attr('src', '/common/images/mapping/PIN_startDriving.gif');
    	$(".MSVE_Map a:last img").attr('src', '/common/images/mapping/PIN_stopDriving.gif');
		} else {
			$(".MSVE_Map a:first img").attr('src', '/common/images/mapping/PIN_startDriving.png');
    	$(".MSVE_Map a:last img").attr('src', '/common/images/mapping/PIN_stopDriving.png');
		}
    $('#directions_steps').html(whitepages.mapping.virth.print_route(route));
  }
  catch(err)
  {
    whitepages.mapping.virth.map.ShowMessage(err.message);
  }
};

whitepages.mapping.virth.print_route = function(route)
{
  // route is an object of type VERouteDeprecated
  var itin = route.Itinerary; // itin is a VERouteItineraryDeprecated object
  
  var html = '<h2>Driving Directions</h2>';
  
  html += '<p><strong>Total Distance:</strong> ' + itin.Distance + ' ' + whitepages.mapping.virth.distance_unit + '<br /><strong>Total Time:</strong> ' + itin.Time + '</p>';
  
  html += '<h2 class="start_label">Start</h2>';
  
  var segments = itin.Segments;
  
  // We ignore the first segment as it's just our starting point.
  
  var depart = segments[1].Instruction.replace(/Depart /, ''); // Remove the "Depart " from the beginning of the instruction
  html += '<p class="start_end_location">' + depart + '</p>';
  
  html += '<ol>';
  
  // Directions steps
  for (var i = 2, end_i = (segments.length - 1); i < end_i; i++)
  {
    html += '<li>';
    html += segments[i].Instruction;
    if (segments[i].Distance != null) {
	    html += ' --  (' + segments[i].Distance + ') ' + whitepages.mapping.virth.distance_unit;
    }
    html += '</li>';
  }
  
  html += '</ol>';
  
  html += '<h2 class="end_label">End</h2>';
  
  // End Location
  var arrive = route.EndLocation.Address;
  html += '<p class="start_end_location">' + arrive + '</p>';
  
  return html;
};

whitepages.mapping.virth.oas_refresh_onchangeview = function() {
  setTimeout(whitepages.mapping.virth.init.oas_ad_refresh, 1);
  //setTimeout("oas.refresh('1')",1);
};

// string_format is used for printing routes.
whitepages.mapping.virth.string_format = function()
{
  if (arguments.length == 0)
  {
    return null;
  }
  var str = arguments[0];
  for (var i=1;i<arguments.length;i++)
  {
    var re = new RegExp('\\{' + (i-1) + '\\}','gm');
    str = str.replace(re, arguments[i]);
  }
  return str;
};

/**
 * Convenience functions.
 */
whitepages.mapping.virth.get_shape_by_id = function(id)
{
  var shapes = whitepages.mapping.virth.mapShapes;

  for (i = 0; i < shapes.length; i++)
    if (shapes[i].shapeNum == id) return shapes[i];

  return null;
};

whitepages.mapping.virth.is_id_visible = function(id, buffer)
{
  if (buffer == null) buffer = 0;
  var shape = whitepages.mapping.virth.get_shape_by_id(id);
  if (shape == null) return null;

  pixel = whitepages.mapping.virth.map.LatLongToPixel(shape.GetPoints()[0]);
  if (pixel.x < buffer || pixel.y < buffer) return false;
  if (pixel.x > whitepages.mapping.virth.map.GetWidth() - buffer || 
      pixel.y > whitepages.mapping.virth.map.GetHeight() - buffer) return false;
  return true;
};

