// Copyright 2007, 2008 Zebek. All rights reserved.
// Duplication, reproduction or use of any kind without explicit written permission from
// Zebek is strictly prohibited.
// Map related variables
// This is an associative array containing pointers to the map and it's attributes
var main_map = new Array();
var COOKIE_NAME = "MAPVIEW=";
var ALL_GLOBAL_GROUPS = 0;
var NO_GROUPS = -1;
var DEFAULT_MAP_LATITUDE = 31.15;
var DEFAULT_MAP_LONGITUDE = -95.15;
var DEFAULT_MAP_ZOOM = 6;
var ERROR_MESSAGE_DISPLAY_DURATION = 6000;
var LOCALLITE_CONTENT_UPDATE_INTERVAL = 120000;
var MARQUEE_TIMEOUT = 1000;
var POPUP_HANG_TIMEOUT = 30000;
var MAP_CENTER_AND_SEARCH_INTERVAL = 1000;
var SEARCH_AREA_IN_MILES = 20;
var SEARCH_LIMIT = 10;
var TAG_CLOUD_AREA_IN_MILES = 5;
// Type constants
var SIMPLE_MAP = 17;
var MOBIKU_MAP = 19;
var FULL_MAP = 21;
// Constants for controlling actions and debugging
// XXXX: auto logout turned off - user will stay logged in
var DO_PERIODIC_LOGOUT=0;
// Miscellaneous variables
var search_offset = 0;
var selected_groups = null;
var errorboxheight=0;
var errorboxmargin=parseInt(GetWindowHeight());
var interval;
var logoutinterval;
var PopupDismissTimer;
var ErrorMsgAutoCloseInterval;
var tdg_oid = -1;
var curSelTag = null;
var curSelImg = null;
var curSelIcn = null;
var tagIndex = 1;
var searchzoom = 11;
var LocalliteActiveDiv = null;
// Variables related to searching
var searchTerm = null;
var searchLocation = null;
var searchWeb = false;
var searchResIndex = 0;
var searchResHtml = '';
var searchResBiz = '';
var searchIntervalTime = 2000;
var logoutIntervalTime = 100000;// 10 Minutes interval
// Variables related to the display of tag groups
var displayed_groups = new Array();
var checked_groups = new Array();
var max_map_zoom_allowed = null;
var locallite_json = null;
var locallite_index = null;
var locallite_controls = '';
var tab_elem = null;
var search_sort_type = null;
// XXXX: Main URL base and COMPANY_NAME defined in the site file. Site file
// automatically selected by php code
var IMAGE_URL_BASE = MAIN_URL_BASE + "common/images/";
// Variables needed to parse kml and gpx format POI files
var kml_parser_file_name = MAIN_URL_BASE + "parsekml.php";
var gpx_parser_file_name = MAIN_URL_BASE + "parsegpx.php";
var simple_request_url_base = MAIN_URL_BASE + "incomingrequesthandler_x.php?reqtype=";
// Variables needed to get locations of tags in groups
var disp_tag_group_url_base = simple_request_url_base + "getgrouptags&";
var disp_tag_group_html = null;
// Variables needed to get locations of tags in groups
var disp_all_groups_tags_url_base = simple_request_url_base + "getdisplayedgroupstags&";
var disp_all_groups_tags_html = null;
// Variables needed to delete a particular group object (tag)
var delete_tag_group_url_base = simple_request_url_base + "deletegrouptag&oid=";
// Variables for checking tags in proximity to moving objects
var proximity_check_timer = null;
var proximity_tag_check_url_base = MAIN_URL_BASE + "getproximitytags_x.php?";
// Variables for updating group display status
var update_gdisp_status_url_base = simple_request_url_base + "updategroupdisplay&";
// Variables related to updating tags;
var tag_update_url_base = MAIN_URL_BASE + "updatetag_x.php?";
var customized_tag_form_html = null;
// Variables needed to get moving object location
var get_loc_hist_url_base = simple_request_url_base + "locationhistory&";

// Variables needed for Business Search
var get_business_search_url_base = simple_request_url_base + "businesssearch&";
var business_search_html = null;

// Variables needed for Wall Search
var get_wall_search_url_base = simple_request_url_base + "wallsearch&";
var wall_search_html = null;

// variables for nearest business combo
var get_nearest_biz_url_base = simple_request_url_base + "nearestbizcombo&";

// variables for getting wall categories
var get_wall_cat_url_base = simple_request_url_base + "getwallcategorytags&";

// variables for getting and saving extra business information
var get_extra_business_information_url_base = simple_request_url_base + "getextrabizinfo&";

// variables for sending email links to graffiti page
var email_graffiti_url_base = simple_request_url_base + "emailgraffiti&";

//
// Miscellaneous php files referenced within HTML and Javascript
var manageaccount_file = "manageaccount.php";
var managewalls_file = "managewalls.php";
var changecos_file = "changecos.php";
var dash_file = "dash.php";
var downloadmobile_file = "downloadmobile.php";
var viewhaiku_file = "viewhaiku.php";
var viewgraffiti_file = "view_graffiti.php";
var yahooimsecondarywin_file = MAIN_URL_BASE + "yimsecondarywindow.php";

// The company icon - used as the icon of tags on maps
var company_pin = IMAGE_URL_BASE+'logo_small.png';
var blue_pin = IMAGE_URL_BASE+'blue-pin.png';
var green_pin = IMAGE_URL_BASE+'green-pin.png';
var orange_pin = IMAGE_URL_BASE+'orange-pin.png';
var red_pin = IMAGE_URL_BASE+'red-pin.png';
var yellow_pin = IMAGE_URL_BASE+'yellow-pin.png';
//

// Icon to show page loading
var LOADING_GIF = "../common/images/ajax-loader.gif";

// The instance of the Google local searcher
var gLocalSearch = null;
var maxbizsearchresults = 10;
//
// Other vars
var puw=null;
var currentdate = GMTDate();
var currentyear = currentdate.getYear();

//
// Related to login
var uid=null;
var upw=null;
var dtype=null;
var udgt=null;
var admap=null;
var ucurpos=null;
var utaggid=null;
var usermovinggid=null;
var gdir = null;
var business_category_html = null;
var geoxml = null;
//
// Pointer to instance of YM (primary or secondary window)
var ymessenger = null;
//

// Related to searching - the search string
var searchstring = null;

//
// The map functions
// Set 1 for Microsoft Virtual Earth
// Set 0 for Google Map

var MSFT = 0;

//
function NewMap(mapcontainer)
{
  if (!mapcontainer)
    return null;

  var map = null;
  if (MSFT == 1)
  {
    map = new VEMap(mapcontainer);
    if (map)
      map.LoadMap();
  }
  else
  {
    if (GBrowserIsCompatible())
    {
      map = new GMap2(GetDOMElement(mapcontainer));
      if (map)
      {
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());	
	map.enableScrollWheelZoom();
	GEvent.addListener(map, "move", function() { HideProgressBar(); });
	GEvent.addListener(map, "zoomend", function(oldz , newz) { ControlUserZoomLevel(oldz, newz, map); });
	GEvent.addListener(map, "dragend", function() { if(GetDOMElement('startlocation')) SetDOMElementValue('startlocation', ''); });
	main_map['geocoder'] = new GClientGeocoder();

	// XXXX: Add Wikipedia Info
	//var myLayer = new GLayer("org.wikipedia.en");
	//map.addOverlay(myLayer);

      }
    }
  }

  return map;
}

function NewPointOnMap(x, y)
{
  if (!x || !y)
    return null;

  return (MSFT==1) ? new VEPixel(x, y) : new GPoint(x, y);
}
function NewLatLongPoint(lat, lon)
{
  if (!lat || !lon || lat < -90 || lat > 90 || lon < -180 || lon > 180)
    return null;

  return (MSFT==1) ? new VELatLong(lat, lon) : new GLatLng(lat, lon);
}
function NewIcon(color)
{
  if (MSFT == 1)
    return null;

  var baseIcon = new GIcon();
  if (!baseIcon)
    return null;

  baseIcon.iconSize = new GSize(20, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
  baseIcon.infoShadowAnchor = new GPoint(18, 25);
  baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";

  var Icon = new GIcon(baseIcon);
  if(color!="yellow" && color!="purple" && color!="pink")
    Icon.image = IMAGE_URL_BASE+"marker/default-marker.png";

  if(color=="pink")
    Icon.image = IMAGE_URL_BASE+"marker/"+color+"-marker.png";

  if(color=="purple")
    Icon.image = IMAGE_URL_BASE+"marker/"+color+"-marker.png";


  return Icon;
}
function NewMarker(lat, lon, point, icon, color)
{
  if (MSFT == 1)
  {
    return NewLatLongPoint(lat, lon);
  }
  else
  {
    var ll = (point) ? point : NewLatLongPoint(lat, lon);
    var ic = (icon) ? icon : NewIcon(color);

    return new GMarker(ll, {icon:ic}, false);
  }
}
function NewMapPolyline(i, p, c, w)
{
  if (MSFT == 1)
  {
    return new VEPolyline(i, p, c, w);
  }
  else
  {
    arr = new Array();
    for(i=0; i<p.length; i++)
    {
      arr[i] = p[i].getLatLng();	
    }
    return new GPolyline(arr,  c,  w);
  }
}
function NewMapColor(r, g, b, x)
{
  return (MSFT==1) ? new VEColor(r, g, b, x) : "#ff0000";
}
function NewMapShape(t, p)
{
  if (!t || !p)
    return null;

  // In the case of Google, just return null for now.
  return (MSFT==1) ? new VEShape(t, p) : null;
}
function NewMapShapeLayer(t)
{
  if (MSFT == 1)
  {
    var l = new VEShapeLayer();
    if (t)
      l.SetTitle(t);
    return l;
  }
  else
  {
    // TODO: implement
    return null;
  }
}
function DeleteAllMapShapes(m, nokml)
{
  if (!m)
    return;

  if(MSFT==1)
  	m.DeleteAllShapes();
  else 
  	m.clearOverlays();
  if(nokml)
  	return null;
  KMLLoader();	
}
function DeleteAllMapPolylines(m)
{
  if (!m)
    return;

  if (MSFT == 1)
  {
    return m.DeleteAllPolylines();
  }
  else
  {
    // TODO: implement
    return null;
  }
}
function AddMapPolyline(m, p)
{
  if (!m || !p)
    return null;

  return (MSFT == 1)? m.AddPolyline(p) : m.addOverlay(p);
}
function GetMapCenter(m)
{
  return (!m) ? null : (MSFT) ? m.GetCenter() : m.getCenter();
}
function SetMapCenter(m, c, z)
{
  if (!m || !c)
    return null;

  var z = (!z) ? GetMapZoom(m) : z;
  if (!z || z==null) z = 10;

  return (MSFT == 1) ? m.SetCenter(c) : m.setCenter(c, z);
}
function GetMapMode(m)
{
  if (!m)
    return null;

  return (MSFT==1) ? m.GetMapMode() : null;
}
function GetMapStyle(m)
{
  // TODO: Is style and type the same thing?
  return GetMapType(m);
}
function GetMapType(m)
{
  if (!m)
    return null;

  return (MSFT==1) ? m.GetMapStyle() : null;
}
function SetMapStyle(m, s)
{
  // TODO: Is style and type the same thing?
  return SetMapType(m, s);
}
function SetMapType(m, t)
{
  return (!m || !t) ? null : (MSFT==1) ? m.SetMapStyle(t) : m.setMapType(t);
}
function SetMapView(m, p)
{
  if (!m || !p)
    return null;

  return (MSFT == 1) ? m.SetMapView(p) : null;
}
function GetMapZoom(m)
{
  return (!m) ? null : (MSFT) ? m.GetZoomLevel() : m.getZoom();
}
function SetMapZoom(m, z)
{
  return (!m || !z) ? null : (MSFT) ? m.SetZoomLevel(z) : m.setZoom(z);
}
function AddMapShapeLayer(m, l)
{
  if(MSFT == 1)
    return (!m || !l) ? null : m.AddShapeLayer(l);

  return null;
}
function AddMapShape(m, l, s, ll, d, i, color, isBusinessSearchTag, isGrpTag)
{
  var d = (d == null) ? null : d;
  var color = (color == null) ? null : color;
  if (MSFT == 1)
  {
    // On MSFT, shape (s) added to map layer (l)
    return (!l || !s) ? null : l.AddShape(s);
  }

  if (!ll)
    return null;

  // On Google, shape is added to map (m) at location (ll) with
  // description (d). So first a marker is created, then it is added to
  // the map
  var lat = GetLatitudeFromPoint(ll);
  var lon = GetLongitudeFromPoint(ll);
  if(SHOW_BIZNAME_IN_TAG_TOOLTIP)
  { var html = d; }
  else
    var html = "Latitude:"+lat+", Longitude:"+lon;
  var ic = null;
  if (i || color)
    ic = (i) ? i : NewIcon(color);

//   GeoAlert(13, "About to create new marker");
  //d = (!isBusinessSearchTag) ? d+'<input type="hidden" name="tagIndex" id="tagIndex" value="'+tagIndex+'">' : d;
  d = d+'<input type="hidden" name="tagIndex" id="tagIndex" value="'+tagIndex+'">';
  var gm = GetNewMarkerTag(ic, ll, html, d, isBusinessSearchTag);
  try
  {
    m.addOverlay(gm);
  }
  catch (e)
  {
    // TODO: Sherjeel can you see why this exception fires when clicking on
    // post wall question from Twitter?
    // GeoAlert(0, "Map shape not added. Exception. Message= " + e.message);
  }

//   GeoAlert(13, "Created and added marker. Now setting mouse action functions");
  if (d){
    GEvent.addListener(gm, "mouseover", function() { OnMouseOverListener(m, ll, d, gm, isBusinessSearchTag); });
    GEvent.addListener(gm, "mouseout", function() { RemoveInfoWindow(); });
  }
  GEvent.addListener(gm, "mouseout", function() { OnMouseOutListener(m, ll, d, gm, isBusinessSearchTag); });
  if(isGrpTag)
  {
    var l = displayed_groups["'"+isGrpTag+"'"]['pp'].length;
    displayed_groups["'"+isGrpTag+"'"]['pp'][l] = gm;
  }

  return gm;
}

function GetNewMarkerTag(ic, ll, html, d, isBusinessSearchTag)
{
  if(!ll)
    return null;

  var gm = null;
  if(ic)
  {
    if(isBusinessSearchTag)
    {
      if(!(main_map['find_biz_layer']))
      {
	main_map['find_biz_layer'] = new Array();
	main_map['find_biz_layer'][0] = null;
      }

      if(!(main_map['find_biz_description']))
      {
	main_map['find_biz_description'] = new Array();
	main_map['find_biz_description'][0] = null;
      }

      //main_map['find_biz_layer'][isBusinessSearchTag] = new GMarker(ll, {title:html,icon:ic, zIndexProcess:BringMarkerOnTopOfOtherMarkers});
      main_map['find_biz_layer'][isBusinessSearchTag] = new GMarker(ll, {icon:ic, zIndexProcess:BringMarkerOnTopOfOtherMarkers});
      main_map['find_biz_description'][isBusinessSearchTag] = d;
      gm = main_map['find_biz_layer'][isBusinessSearchTag];
      tagIndex++;
    }// end if(isBusinessSearchTag)
    else
    {
      gm = new GMarker(ll, {icon:ic});//title:html,
    }
  }// end if(ic)
  else	
  {
    gm = new GMarker(ll);//, {title:html}
  }

  if(!(isBusinessSearchTag))
  {
    if(!(main_map['wall_object_layer']))
    {main_map['wall_object_layer'] = new Array(); main_map['wall_object_layer'][0] = null;}

    if(!(main_map['wall_object_description']))
    {main_map['wall_object_description'] = new Array(); main_map['wall_object_description'][0] = null;}

    main_map['wall_object_layer'][tagIndex] = gm;
    main_map['wall_object_description'][tagIndex] = d;
    tagIndex++;
  }

  return gm;
}

function BringMarkerOnTopOfOtherMarkers(marker,b)
{
  return GOverlay.getZIndex(marker.getPoint().lat())*10000*-1;
}

function OnMouseOverListener(m, ll, d, gm, isBusinessSearchTag)
{
  if(!m || !ll || !SHOW_TAG_POPUP_INFO)
    return null;

  ShowMapInfoWindowPopup(m, ll, d);
  
  //main_map['map'].removeOverlay(gm);
  //main_map['map'].addOverlay(gm);

  var yellowMarker = "";
  if(isBusinessSearchTag)
  {
    yellowMarker = IMAGE_URL_BASE+'marker/yellow-marker'+isBusinessSearchTag+".png";
	//yellowMarker = "http://chart.apis.google.com/chart?cht=it&chs=32x32&chco=FFFF66,000000ff,ffffff01&chl="+isBusinessSearchTag+"&chx=000000,12&chf=bg,s,00000000&ext=.png";
  }
  else
    yellowMarker = IMAGE_URL_BASE+'marker/yellow-marker.png';

  //gm.openInfoWindowHtml(d, {maxWidth:100});
  curSelIcn = (gm) ? gm.getIcon() : null;
  curSelImg = (curSelIcn) ? curSelIcn.image : null;
  if(gm)
  {
    gm.setImage(yellowMarker);
    //gm.zIndexProcess
    curSelTag = gm;
  }
  // XXXX: No reverse geocode request made while user right click on map to add new graffiti
  //       As tagpopuptemplate already doing so (showing the address through reverse geocoding).
//	get_reverse_geocode(ll);
  return true;
}

function OnMouseOutListener(m, ll, d, gm, isBusinessSearchTag)
{
  return true;
}

function ShowMapInfoWindowPopup(m, ll, d)
{
  RemoveInfoWindow();
  if(!ll)
    return null;

  var div = document.createElement("div");
  if (!div)
    return null;

  div.setAttribute('id','777');
  //div.style.top = "285px;";
  div.style.position='absolute';
  div.style.width='250px';
  div.style.padding='1px';
  //div.style.backgroundColor='red';
  //div.style.left = "8px";
  //div.style.border = "none";
  div.style.fontFamily = "Arial";
  div.style.fontSize = "11px";
  var x = m.fromLatLngToContainerPixel(ll).x; // -0
  var y = m.fromLatLngToContainerPixel(ll).y; // -35
  /*
    Map Div
    =======================================================================
    |									|									|	
    |	   Part 1 - 1					|			Part 1 - 2				|	
    |									|									|	
    |									|									|	
    =======================================================================
    |									|									|	
    |		Part 2 - 1					|			Part 2 - 2				|	
    |									|									|	
    |									|									|	
    =======================================================================
  */
  var ht = parseInt(GetDOMElement('mapcontainer').style.height);
  ht = (!ht) ? parseInt(GetDOMElement("mapcontainer").clientHeight) : ht;
  if(!ht)
    ht = 360;
  var wt = parseInt(GetDOMElement('mapcontainer').style.width);
  wt = (!wt) ? parseInt(GetDOMElement("mapcontainer").clientWidth) : wt;
  if(!wt)
    wt = 465;

  if(x > 0 && x<=eval(wt/2) && y >0 && y<=eval(ht/2))	// Part 1 - 1			
  {
    div.style.left = (parseInt(x)+0)+"px";
    div.style.top = (parseInt(y)+0)+"px";
  }
  else if(x >eval(wt/2) && x<=eval(wt) && y >0 && y<=eval(ht/2))	// Part 1 - 2
  {
    div.style.left = (parseInt(x)-250)+"px";
    div.style.top = (parseInt(y)-0)+"px";
  }
  else if(x > 0 && x<=eval(wt/2) && y >eval(ht/2) && y<=eval(ht)) // Part 2 - 1
  {
    div.style.left = (parseInt(x)+9)+"px";
    div.style.top = (parseInt(y)-180)+"px";
  }
  else if(x >eval(wt/2) && x<=eval(wt) && y >eval(ht/2) && y<=eval(ht)) // Part 2 - 2
  {
    div.style.left = (parseInt(x)-257)+"px";
    div.style.top = (parseInt(y)-180)+"px";
  }

  //div.innerHTML = (main_map['type']==SIMPLE_MAP && d.indexOf('tagpopuptempHdng')>0) ? d : (main_map['type']==SIMPLE_MAP) ? GetPopupHTML(d, 'simplemapanswer') :  GetPopupHTML(d, 'graffitidescription');
//  div.innerHTML = (main_map['type']==SIMPLE_MAP && d.indexOf('tagpopuptempHdng')>0) ? d : GetPopupHTML(d, 'graffitidescription');
  var msg = GetPopupHTML(d, 'graffitidescription');
  div.innerHTML = '<div class="ui-dialog ui-widget ui-widget-content ui-corner-all" style="overflow: hidden; position: absolute; outline-color: -moz-use-text-color; outline-style: none; outline-width: 0px; height: auto; display: block; width: 238px;"> <div style="padding:0px; height: auto; width: auto; min-height: 20px;" class="ui-dialog-content ui-widget-content"> '+msg+' </div><div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"></div></div>';
  //div.innerHTML = msg;

  var mapcontainer = GetDOMElement('mapcontainer');
  if(mapcontainer)
    mapcontainer.appendChild(div);

  return true;
}

function RemoveInfoWindow(selTagOnly)
{
  if(GetDOMElement('777'))
  {
    var drtagIndex = GetDOMElementValue('tagIndex');
    if(selTagOnly && curSelTag && main_map['map'] && GetDOMElement('wallObject'+drtagIndex))
    {
      //SetDOMElementInnerHtml('wallObject'+drtagIndex, '');
      GetDOMElement('wallObject'+drtagIndex).style.display='none';
    }
    GetDOMElement('mapcontainer').removeChild(GetDOMElement('777'));
  }
  try
  {
   if(curSelTag && curSelImg)
    curSelTag.setImage(curSelImg);
   if(selTagOnly && curSelTag && main_map['map'])
    main_map['map'].removeOverlay(curSelTag);
  }
  catch(e)
  {}
/*	
	if(main_map['wall_object_layer'])	
	{
	alert(main_map['wall_object_layer'].length);	
	for(var i=0; i<main_map['wall_object_layer'].length; i++)
	{
	var gm = main_map['wall_object_layer'][i];	
	}
	}
*/
  curSelTag = null;
  curSelImg = null;
}
function MapPixelToLatLong(m, p)
{
  if (!m || !p)
    return null;

  return (MSFT == 1) ? m.PixelToLatLong(p) : m.fromContainerPixelToLatLng(p);
}
function LatLongToMapPixel(m, p)
{
  if (!m || !p)
    return null;

  return (MSFT == 1) ? null : m.fromLatLngToDivPixel(p);
}
function GetLatitudeFromPoint(p)
{
  if (!p)
    return null;

  return (MSFT==1) ? p.Latitude : p.lat();
}
function GetLongitudeFromPoint(p)
{
  if (!p)
    return null;

  return (MSFT==1) ? p.Longitude : p.lng();
}
function GetMapTopLeft(m)
{
  if (!m)
    return null;

  return (MSFT==1) ? m.GetMapView().TopLeftLatLong : null;
}
function GetMapBottomLeft(m)
{
  if (!m)
    return null;

  return (MSFT==1) ? null : m.getBounds().getSouthWest();
}
function GetMapBottomRight(m)
{
  if (!m)
    return null;

  return (MSFT==1) ? m.GetMapView().BottomRightLatLong : null;
}
function GetMapTopRight(m)
{
  if (!m)
    return null;

  return (MSFT==1) ? null : m.getBounds().getNorthEast();
}
function AddMapEventHandler(m, e, f)
{
  if (!m)
    return null;

  return (MSFT==1) ? m.AttachEvent(e, f) : GEvent.addListener(m, e, f);
}
function RemoveMapEventHandler(m, e, f, h)
{
  if (!m)
    return null;

  if(MSFT==1)
  {
    m.DetachEvent(e, f);
    return null;
  }
  else
  {
    // Needs to get the handler that addListener returned
    return GEvent.removeListener(h);
  }
}
//
//
//
//
function InitializeGlobals(u, p, t, dg, am, lg)
{
  uid = (u == null || u < 0) ? uid : u;
  upw = (p == null || p == "") ? upw : p;
  dtype = (t == null) ? 'web' : t;
  udgt = (dg == null) ? true : dg;
  admap = (am == null) ? false : am;
  utaggid = (lg == null) ? ALL_GLOBAL_GROUPS : lg;
}

function InitializeMainPage(mc, u, p, t, dg, am, lg)
{
  // If the user is not logged in and we are displaying the main
  // page where groups are displayed, return - nothing to do.
  // Otherwise show the map (probably showing locationhistory page)

//   if (u < 0 && (dg!=false || dg=='undefined'))
//     return null;
  // Set the map type
  main_map['type'] = (COMPANY_NAME == "Mobiku") ? MOBIKU_MAP : FULL_MAP;
  main_map['max_accurate_points'] = 25;
  main_map['default_shape_layer'] = null;
  main_map['find_biz_layer'] = null;

  InitializeGlobals(u, p, t, dg, am, lg);

  // XXXX: No Map div means no need to proceed further
  if(!GetDOMElement(mc))
    return null;

  // Limit max zoom in general case for unlogged in users
  max_map_zoom_allowed = (u && u > 0) ? 20 : 19;
  CreateMap(mc);

  // Now load all the checked groups for this device/user (unless
  // specifically not to
  if (udgt && main_map['map']) {
    if (utaggid == ALL_GLOBAL_GROUPS)
    {
      if(SEARCH_FOR_WALL_WITH_ONE_SEARCH)
      {
	// Unless this is a simple map (utaggid would be the gid or -1),
	// display all the checked groups for the device for the user
	DisplayAllDeviceCheckedGroups();
      }
      else
      {
	InitializeJQDialog();
	var elem = (GetDOMElement('wallObject0')) ? GetDOMElement('wallObject0') : (GetDOMElement('wallObject1')) ? GetDOMElement('wallObject1') : null;
	if(elem)
	{
	  //eval(elem.getAttribute('onClick'));
	  elem.className = 'user_block selected';
	  LocalliteActiveDiv = elem;
	}
      }
    }
  }
  SetUserLogOutInterval();
  KMLLoader();
}

function SetUserLogOutInterval()
{
  logoutinterval = setInterval('clearInterval(logoutinterval);LogOutUser();', logoutIntervalTime);
}

function InitializeSimpleMap(mc, u, p, lat, lon, zoom, query, gid, movinggid)
{
  var gid = (gid) ? gid : NO_GROUPS;
  usermovinggid = (movinggid) ? movinggid : null;
  selected_groups = gid;

  InitializeMainPage(mc, u, p, "web", true, false, gid);

  // Set the map type (do this after above call to set to simple map)
  main_map['type'] = SIMPLE_MAP;

  // In this case allow users to get max zoom
  max_map_zoom_allowed = 20;

  // OK, position the map and show a popup?
  if (lat && lat!=-500 && lon && lon!=-500)
  {
    ucurpos = new GLatLng(lat, lon);
    SetMapCenter(main_map['map'], ucurpos, zoom);

    var description = '<table width="100%"><tr><td>';
    description += "<div style='margin-top:-15px; width:216px;'>";
    description += "<strong>Sender Current Location</strong></div>";
    description += "<br/>";
    description += "<div style='text-align:left;'>Sender's Question: "+query+"</div>";

    description += '</td></tr></table>';
    AddMapShape(main_map['map'], null, null, ucurpos, description, null, null, false);
  }

  AddMapEventHandler(main_map['map'], "singlerightclick", MouseOnRightClickSimpleHandler);

  // Show all the tags for this group
  if (utaggid > ALL_GLOBAL_GROUPS)
    GetGroupTags(utaggid);
}

function CreateMap(mapcontainer)
{
  main_map['map'] = NewMap(mapcontainer);
  RestoreMapViewFromCookie();
}

function InitializeMapPolicies()
{
  if (MSFT == 1)
  {
    // This function is called when zoom has been restored from
    // RestoreMapInitialZoomLevel. Therefore, now detach the event handlers
    RemoveMapEventHandler(main_map['map'], "onendzoom", InitializeMapPolicies);

    // Now set some map policies
    // Don't try to show extra shapes
    main_map['map'].SetFailedShapeRequest(VEFailedShapeRequest.DoNotDraw);

    // Convert pushpins accurately
    main_map['map'].SetShapesAccuracy(VEShapeAccuracy.Pushpin);

    // The maximum number of points to convert accurately.
    main_map['map'].SetShapesAccuracyRequestLimit(main_map['max_accurate_points']);

    // Set the event handlers
    AddMapEventHandler(main_map['map'], "onclick", MouseOnClickHandler);
    if (udgt)
    {
      // Update display of all group tags when map moves only if this
      // particular map displays group tags.
      AddMapEventHandler(main_map['map'], "onendpan", UpdateDisplayOfAllGroupTags);
      AddMapEventHandler(main_map['map'], "onendzoom", UpdateDisplayOfAllGroupTags);
    }

    // Tags are added to this layer by default for display purposes.
    main_map['default_shape_layer'] = NewMapShapeLayer("Default shape for mouse-clicked tags");
    // Adding the layer does not do anything in of itself - it's only
    // when shapes are added to the layer that you can "see" the layer
    AddMapShapeLayer(main_map['map'], main_map['default_shape_layer']);
  }
  else
  {
    if(main_map['type']!=SIMPLE_MAP)
      AddMapEventHandler(main_map['map'], "singlerightclick", MouseOnRightClickHandler);	

    // TODO: only set this for cases where singlerightclick does not work
    AddMapEventHandler(main_map['map'], "onclick", MouseOnClickHandler);

    if (udgt)
    {
      // Update display of all group tags when map moves only if this
      // particular map displays group tags.
      AddMapEventHandler(main_map['map'], "moveend", UpdateDisplayOfAllGroupTags);
    }
  }

  GetMapView();
}

function GetMapView()
{
  // TODO: add the relevant attributes for BirdsEye and 3D modes
  // XXXX: in GoogleMaps may be possible save map state with savePosition();

  var c = GetMapCenter(main_map['map']);
  main_map['lat'] = GetLatitudeFromPoint(c);
  main_map['lon'] = GetLongitudeFromPoint(c);
  main_map['zoom'] = GetMapZoom(main_map['map']);
  if(MSFT==1)
  {
    main_map['mode'] = GetMapMode(main_map['map']);
    main_map['topleft'] = GetMapTopLeft(main_map['map']);
    main_map['bottomright'] = GetMapBottomRight(main_map['map']);
    main_map['style'] = GetMapStyle(main_map['map']);
    main_map['view'] = main_map['lat']+":"+main_map['lon']+":"+main_map['mode']+":"+main_map['style']+":"+main_map['zoom'];
  }
  else
  {
    main_map['topleft'] = GetMapBottomLeft(main_map['map']);
    main_map['bottomright'] = GetMapTopRight(main_map['map']);
    main_map['view'] = main_map['lat']+":"+main_map['lon']+":"+main_map['zoom'];
  }

  // Store the current view in a cookie
  var expire = GMTDate();
  expire.setTime(expire.getTime()+(24*30*3600*1000));
  document.cookie = COOKIE_NAME + main_map['view'] + "; expires=" + expire.toGMTString();
  GeoAlert(15, "Set Cookie:" + document.cookie);
}

function ExtractMapViewFromCookie()
{
  var c = document.cookie;
  if (! c)
    return false;

  var cookiepre=null;
  var cookiepost=null;
  var b = c.indexOf("; " + COOKIE_NAME);
  if (b == -1)
  {
    b = c.indexOf(COOKIE_NAME);
    if (b != 0)
    {
      cookiepre=c;
      return false;
    }
  }
  else
  {
    cookiepre = c.substring(0, b);
    b += 2;
  }

  var e = c.indexOf(";", b);
  if (e == -1)
    e = c.length;
  else
    cookiepost = c.substring(e+1);

  var v = unescape(c.substring(b + COOKIE_NAME.length, e));
  if (! v)
    return false;

  var s = v.split(":");
  if (! s)
    return false;

  main_map['lat'] = (s.length>0 && s[0]) ? s[0] : null;
  if (!Number(parseInt(main_map['lat']))) main_map['lat'] = DEFAULT_MAP_LATITUDE;
  main_map['lon'] = (s.length>1 && s[1]) ? s[1] : null;
  if (!Number(parseInt(main_map['lon']))) main_map['lon'] = DEFAULT_MAP_LONGITUDE;

  if (MSFT==1)
  {
    main_map['mode'] = (s.length>2 && s[2]) ? s[2] : null;
    main_map['style'] = (s.length>3 && s[3]) ? s[3] : null;
    main_map['zoom'] = (s.length>4 && s[4]) ? s[4] : null;
  }
  else
  {
    main_map['mode'] = null;
    main_map['style'] = null;
    main_map['zoom'] = (s.length>2 && s[2]) ? s[2] : null;
    if (!Number(parseInt(main_map['zoom']))) main_map['zoom'] = DEFAULT_MAP_ZOOM;
  }

  GeoAlert(15, "CookieString:"+v+"Lat:"+main_map['lat']+" Lon:"+main_map['lon']+
 	   " Mode:"+main_map['mode']+" Style:"+main_map['style']+" Zoom:"+main_map['zoom']);
  return true;
}

function RestoreMapViewFromCookie()
{
  ExtractMapViewFromCookie();
  // XXXX: in GoogleMaps may be possible restore map state with
  // returnToSavedPosition();

  if(MSFT==1)
  {
    // TODO: add the relevant attributes for BirdsEye and 3D modes
    if (main_map['mode'] != null)
      main_map['map'].SetMapMode(main_map['mode']);
    if (main_map['style'] != null)
      SetMapStyle(main_map['map'], main_map['style']);

    AddMapEventHandler(main_map['map'], "onchangeview", RestoreMapInitialZoomLevel);
  }

  var latlon = null;
  if (main_map['lat']!=null && main_map['lon']!=null)
  {
    latlon = NewLatLongPoint(main_map['lat'], main_map['lon']);
    if (latlon != null)
    {
      // When the map's center has changed, restore the zoom level
      if (MSFT == 1)
      {
 	SetMapCenter(main_map['map'], latlon);
 	return;
      }
      else
      {
 	if(main_map['zoom'] != null)
 	  SetMapCenter(main_map['map'], latlon, parseInt(main_map['zoom']));
 	else
 	  SetMapCenter(main_map['map'], latlon, GetMapZoom(main_map['map']));
      }
    }
  }
  else
  {
	  try
	  {
		MallSpecificOnly();
	  }
	  catch(e)
	  {	  
		var url = simple_request_url_base+'iptolocation';
		var ggai = new AJAXInteraction(url, SetCoordinatesFromIPLocation);
		ggai.Post();
		if (MSFT == 1) return;
	  }
  }

  RestoreMapInitialZoomLevel();
}

function SetCoordinatesFromIPLocation(rstr)
{
  var json = GetJson(rstr);
  if(json && json.Latitude && json.Longitude){
    main_map['lat'] = json.Latitude;
    main_map['lon'] = json.Longitude;
  }
  else{
    main_map['lat'] = DEFAULT_MAP_LATITUDE;
    main_map['lon'] = DEFAULT_MAP_LONGITUDE;	
  }
  main_map['zoom'] = DEFAULT_MAP_ZOOM;
  latlon = NewLatLongPoint(main_map['lat'], main_map['lon']);	
  SetMapCenter(main_map['map'], latlon, parseInt(main_map['zoom'])); 		
}

function RestoreMapInitialZoomLevel()
{
  if (MSFT==1)
  {
    // Now that the zoom level has been restored, unset the event handler
    //main_map['map'].DetachEvent("onchangeview", RestoreMapInitialZoomLevel);
    RemoveMapEventHandler(main_map['map'], "onchangeview", RestoreMapInitialZoomLevel);
    AddMapEventHandler(main_map['map'], "onendzoom", InitializeMapPolicies);
  }

  if (main_map['zoom'] != null)
  {
    // Go back to setting the map policies once done zooming
    SetMapZoom(main_map['map'], main_map['zoom']);
    if (MSFT == 1) return;
  }

  InitializeMapPolicies();
}

// This variable is just used to change map center and zoom level
var newzoom = -1;
function SetMapCenterAndZoomLevel(lat, lon, zoom, data, adpin)
{
  newzoom = zoom;

  AddMapEventHandler(main_map['map'], "onchangeview", SetMapZoomLevel);
  var latlon = NewLatLongPoint(lat, lon);
  if (latlon != null)
  {
    SetMapCenter(main_map['map'], latlon, zoom);
    if(adpin)
    {
      RemoveInfoWindow();
	  DeleteAllMapShapes(main_map['map']);
      var icon = NewIcon("pink");
      AddLatLonPin(0, 0, latlon, data, icon, 0, null, null, 1);
    }
  }
  else
    SetMapZoomLevel();

  GetMapView();
}

function SetMapZoomLevel()
{
  // Now that the zoom level has been restored, unset the event handler
  RemoveMapEventHandler(main_map['map'], "onchangeview", SetMapZoomLevel);
  if (newzoom != -1)
  {
    SetMapZoom(main_map['map'], newzoom);
    newzoom = -1;
  }

  GetMapView();
}

function ControlUserZoomLevel(oldzoomlevel, newzoomlevel, m)
{
  // XXXX: newzoomlevel means current zoom level (after zooming, always
  // return a number) and oldzoomlevel means previous zoom level (before
  // zooming, can be undefined).
  if(newzoomlevel>max_map_zoom_allowed)
  {
    if(oldzoomlevel)
      SetMapZoom(m, oldzoomlevel);
    else
      SetMapZoom(m, max_map_zoom_allowed);

    ShowError("You have reached your maximum allowed zoom level.");
  }
  //if(GetDOMElement('startlocation')) 
  //	SetDOMElementValue('startlocation', '');
}

function MouseOnRightClickSimpleHandler(point, source, overlay)
{
  if(!point)
    return;

  var latlon = main_map['map'].fromContainerPixelToLatLng(point);
  distance = (ucurpos) ? (ucurpos.distanceFrom(latlon) * 0.62137) / 1000.0 : null;

  var lat = GetLatitudeFromPoint(latlon);
  var lon = GetLongitudeFromPoint(latlon);
  var html = '';

  var Icon = NewIcon("orange");
  var point_marker = MapPixelToLatLong(main_map['map'], point);
  AddLatLonPin(0, 0, point_marker, '', Icon, 0, admap);

}

function MouseOnClickHandler(one, two, three)
{
  if (MSFT == 1)
  {
    if (one.rightMouseButton == true)
    {
      MouseOnRightClickHandler(one);
    }
  }
  else
  {
    var overlay = one;
    var latlong = two;
    var overlaylatlng = three;
    if (latlong != null)
    {
      var Icon = NewIcon("orange");
      AddLatLonPin(0, 0, latlong, '', Icon, 0, admap);
    }
  }
}

function MouseOnRightClickHandler(point, source, overlay)
{
  if (!PLACE_TAG_ON_RIGHT_CLICK)
    return null;
  if (MSFT == 1)
  {
    var tl = MapPixelToLatLong(main_map['map'], NewPointOnMap(point.mapX, point.mapY));
    AddLatLonPin(0, 0, tl, '', company_pin, 0, admap);
  }
  else
  {
    if(point != null)
    {
      var Icon = NewIcon("orange");
      var point_marker = MapPixelToLatLong(main_map['map'], point);
      AddLatLonPin(0, 0, point_marker, '', Icon, 0, admap);
    }
  }

  RemoveInfoWindow();
  GetMapView();
}

// mp stands for "Moving Pin" - it is either 0 or 1.
// If it is set to 1, the tag is moving and it's
// location should be fetched regularly and the
// map panned to keep the tag centered.
function AddGroupPin(lat, lon, pdesc, gicon, mp, gid, oid)
{
  if (mp == 1)
  {
    GeoAlert(11, "Adding moving object");
    GetObjectLocation(gid, oid);
  }
  else
  {
    GeoAlert(11, "Adding static object");
    var vll = NewLatLongPoint(lat, lon);
    AddLatLonPin(gid, oid, vll, pdesc, gicon, 0);
  }
}

function CreateGrayOverlay()
{
  SetUserLogOutInterval();
  var ol = GetDOMElement('ol');
  if(!ol)
    return null;
  ol.style.display = '';
  ol.style.width = GetWindowWidth()+'px';
  ol.style.height = GetWindowHeight()+'px';
  ol.style.backgroundImage = 'url(../common/images/assets/overlay.png)';
  ol.style.position = 'fixed';
  ol.style.float = 'left';
  // TODO: Anshu please set the hide time and Error Msg to show, currently is 2 minutes

  return ol;
}

function ClearGrayOverlay()
{
  if(GetDOMElement('ol') && GetDOMElement('ol').style.display == '')
    HideElement('ol');

  // Now clear the timer that would dismissed the popup
  clearTimeout(PopupDismissTimer);	
}

// Use this function to display the contents of url in a popup
function DisplayPopup(url)
{
  if(!url || url=='')	
    return null;

  window.onresize =  function(){
    var ol = GetDOMElement('ol');
    if(ol && ol.style.display == '')
    {
      CreateGrayOverlay();
      var mbox = GetDOMElement('mbox');
      if(mbox){
	mbox.style.left = 0+'px';
	mbox.style.width = GetWindowWidth()+'px';
	mbox.align = "center";
      }
    }
  }
  CreateGrayOverlay();
  var mbox = CreateModalDialogBox();
  SetDOMElementInnerHtml('mbox', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px;"></div>');
  //var left = eval(parseInt(GetWindowWidth()) - 220) / 2;
  var disTop = typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;

  mbox.style.left = 0+'px';
  mbox.style.width = GetWindowWidth()+'px';
  mbox.align = "center";
  mbox.style.top = eval(parseInt(disTop)+50)+'px';
  /////////////////////////////////////
  var url = MAIN_URL_BASE +''+url;  
  
  var ggai = new AJAXInteraction(url, FillPopupWithResponseHtml);
  ggai.Get();
  try{
	  HideElement('chart');
	  HideElement('chart1');
  }
  catch(e){
  }
}

function FillPopupWithResponseHtml(response)
{
  SetDOMElementInnerHtml('mbox', response);
  var script = GetDOMElementValue('script');
  if(script)
    eval(script);

}

function CreateModalDialogBox()
{
  var mbox = GetDOMElement('mbox');
  if (!mbox)
    return null;

  SetDOMElementInnerHtml('mbox', '');
  mbox.style.display = 'block';
  mbox.style.left = '280px';
  mbox.style.top = '100px';
  mbox.style.minWidth = '80px';
  mbox.style.minHeight = '150px';
  mbox.style.color = '#bed63a';
  mbox.style.position = 'absolute';
  mbox.style.float = 'left';

  // Set a timer a to dismiss the popup if it hung
  PopupDismissTimer=setInterval('ClearGrayOverlay();ClearModalDialogBox();ShowError("Sorry, server timed out.")',
				POPUP_HANG_TIMEOUT);
  return mbox;
}

function ClearModalDialogBox(hidembox)
{
  if(GetDOMElement('mbox') && GetDOMElement('mbox').style.display == 'block')
  {
    HideElement('mbox');
    customized_tag_form_html = null;

    if(!(hidembox))
      SetDOMElementInnerHtml('mbox', "");
  }
}

function AddLatLonPin(gid, oid, ll, pdesc, picon, moving, adpin, isBusinessSearchTag,
		      isHistoryLocationTag, havegraffiti, name, address)
{
  if (ll == null)
    return;

  pdesc += (main_map['type']==MOBIKU_MAP) ? GetPopupHTML('<input type=hidden id=txtlat value="'+GetLatitudeFromPoint(ll)+'" /><input type=hidden id=txtlon value="'+GetLongitudeFromPoint(ll)+'" />', 'MobikuPopup') : "";

  var adpin = (adpin == null) ? false : adpin;
  var isBusinessSearchTag = (isBusinessSearchTag == null) ? false : isBusinessSearchTag;
  var isHistoryLocationTag = (isHistoryLocationTag == null) ? false : isHistoryLocationTag;
  var havegraffiti = (havegraffiti == null) ? false : havegraffiti;
  var pindesc = "<div id='fortest' style='font-size:8pt;font-family=:Arial;margin-top:0px;'>";
  pindesc += "<div style='max-height:100px;overflow-y:auto;overflow-x:none;width:235px;'>"+decodeURI(pdesc)+"</div>";
  pindesc += "<table width=100%><tr>";
  if (main_map['type'] != MOBIKU_MAP)
    pindesc += "<td colspan=\"2\"><br></td></tr><tr>";
  if (oid > 0 && !isHistoryLocationTag && main_map['type']!=SIMPLE_MAP && SHOW_TAG_POPUP_INFO)
  {
    var formstr = "";
    formstr += '<td><form name="frmView" action="';
    if (main_map['type']==MOBIKU_MAP)
      formstr += viewhaiku_file;
    else
      formstr += viewgraffiti_file;
    formstr += '?oid='+oid+'" method="post">';
    formstr += "<a title=";
    if (main_map['type']==MOBIKU_MAP)
      formstr += "'View All Haiku'";
    else
      formstr += "'View All Graffiti'";
    formstr += " href='javascript:void(0)' onClick='document.frmView.submit()'>Expand &raquo;</a>";
    formstr += "<input type=hidden name=oid id=oid value="+oid+">";
    formstr += "<input type=hidden name=i id=i value="+uid+">";
    formstr += "<input type=hidden name=c id=c value="+upw+">";
    formstr += "<input type=hidden name=zoom id=zoom value="+GetMapZoom(main_map['map'])+">";
    formstr += "</form></td>";
    pindesc += formstr;
  }

  if (uid != null  && !isHistoryLocationTag && main_map['type']!=MOBIKU_MAP && SHOW_TAG_POPUP_INFO)
  {
    pindesc += "<td align=\"right\" colspan='3' ><a href=\"javascript:AddTagModalDialog(" + GetLatitudeFromPoint(ll);
    pindesc += "," + GetLongitudeFromPoint(ll) + ", 0, ";
    pindesc += (isBusinessSearchTag) ? (-1+","+isBusinessSearchTag) : (oid+",-1");
    pindesc += ", " + adpin + ")" + "\">";
    pindesc += (adpin) ? "Create Ad &raquo;" : "Add Graffiti Here &raquo;";
    pindesc += "</a></td></tr><tr style='height:5px'><td colspan=\"2\"></td></tr>";
    if (oid > 0)
    {
      pindesc += "<tr><td><td><td align=\"right\" colspan='2'></td></tr>";
    }
    else
    {
      pindesc += "<tr><td ";
      pindesc += (isBusinessSearchTag) ? "" : "id='geocodeDiv'";
      pindesc += " colspan='3' align=left><td></tr>";
    }
  }
  else if(uid == null)
  {
    // XXXX: User should have to log in to our server to add graffiti
    //if(main_map['type']!=SIMPLE_MAP)
    pindesc += "<tr><td colspan='2' align='center'><b>Log in to tag.</b></td></tr>";
  }

  if(isHistoryLocationTag)
  {
    pindesc += "<tr><td colspan='3' align=right><td></tr>";
  }
  pindesc += "</table></div>";

  var pp = null;
  if(MSFT==1)
  {
    pp = NewMapShape(VEShapeType.Pushpin, ll);
    if (pp && picon)
      pp.SetCustomIcon(picon);
  }
  if(SHOW_BIZNAME_IN_TAG_TOOLTIP)
  {
    pindesc = (name) ? "<b>"+name+"</b>" : "";
    pindesc += (address) ? "<hr>"+address+"<br>" : "";
  }

  GeoAlert(13, "Adding pin with information " + pindesc);
  if (gid <= 0 && oid <= 0)
  {
    AddMapShape(main_map['map'], main_map['default_shape_layer'], pp, ll, pindesc, picon, null, isBusinessSearchTag);
    return;
  }

  if (displayed_groups["'"+gid+"'"] == null)
    displayed_groups["'"+gid+"'"] = new Array();

  displayed_groups["'"+gid+"'"]['gid'] = gid;
  displayed_groups["'"+gid+"'"]['moving'] = moving;
  if (moving == 1)
  {
    if (displayed_groups["'"+gid+"'"]['oid'] == null)
      displayed_groups["'"+gid+"'"]['oid'] = new Array();

    displayed_groups["'"+gid+"'"]['oid'][displayed_groups["'"+gid+"'"]['oid'].length]= oid;
  }
  if (!(displayed_groups["'"+gid+"'"]['pp']))
    displayed_groups["'"+gid+"'"]['pp'] = new Array();

  var shape = null;
  return shape = AddMapShape(main_map['map'], main_map['default_shape_layer'], pp, ll, pindesc, picon, null, isBusinessSearchTag, gid);
}

function MapSearchedLocation(ll)
{
  var ll = (ll == null) ? GetDOMElementValue('startlocation') : ll;
  if (!ll || ll == "")
    ll = GetDOMElementValue('destlocation');

  if (ll && ll != "")
  {
    if (MSFT == 1)
    {
      main_map['map'].Find(null, ll);
      GetMapView();
    }
    else
    {
      if (main_map['geocoder'])
 	main_map['geocoder'].getLatLng(ll, HandleFindAddress);
    }
    ClearErrorBox();
  }
  else
    GeoAlert(3, "Please enter address to center map on.");
	
  SetDOMElementInnerHtml('businessResultsdiv', '');
  HideElement('businessResultsdiv');
  HideElement('businessResultsclrbtn');	
}

function HandleFindAddress(point)
{
  var validAddress = true;
  if (!point)
  {
    validAddress = false;
    ShowError("Address not found!");
  }
  else
  {
    AddLatLonPin(0, 0, point, GetDOMElementValue('startlocation'), null, 0,0,0,0,0,null,GetDOMElementValue('startlocation'));
    var z = main_map['zoom'];
    z = searchzoom;
    SetMapCenter(main_map['map'], point, z);
  }
  GetMapView();
  if(validAddress){
    if(GetDOMElementValue('biznametype')!="" && GetDOMElementValue('startlocation')!="")
	{
	  if(search_sort_type)
	  	OneSearch(null, search_sort_type);
      else
		OneSearch();
	}
  }
}

function OneSearch(what, searchsort)
{
  RemoveInfoWindow();
  SetUserLogOutInterval();
  
  var what = (what == null) ? GetDOMElementValue('biznametype') : what;
  if(what.indexOf('<')>0 || what.indexOf('>')>0) {
    ShowError('Enter Valid Search String Like Pizza, Hotel, Restaurants etc. ');
    return false;
  }
  
  try
  {
  	MallSpecificOnly();
  }
  catch(e)
  {}
  SetDOMElementValue('biznametype', what);

  if (what)
    what = Trim(what) ;
  if (what == null || what == "")
  {
    GeoAlert(3, "Enter search terms...");
    return;
  }
  GeoAlert(10, "One search for "+what);
/*************************/
  //SetDOMElementInnerHtml('mastersummary', '<div id="loading_gif" style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div><div style="display:none; height:30px;" id="controls"></div><div style="display:none" id="Listing"></div><div style="display:none" id="User"></div><div style="display:none" id="Review"></div>');
  SetDOMElementInnerHtml('mastersummary', '<div style="display:none" id="Listing"></div>');
  ShowElement('notready');HideElement('ready');
/*************************/
  searchstring = what;
  locallite_controls = '<p>';

  // Issue a search for walls
  if(SEARCH_FOR_WALL_WITH_ONE_SEARCH)
    SearchForWall(searchstring);
	
  locallite_controls += '<a id="tab1" style="width:230px; float:left; font-weight:bold; color:#FFFFFF; background-image:url(local/images/l_post_review.gif)" class="l_ask" href="Javascript:void(0)" onclick="SearchPageTabs(1);">Listing</a>';

  searchTerm = searchstring;
  searchLocation = GetDOMElementValue('startlocation');

  searchResIndex = 0;
  searchWeb = true;
  searchResBiz = '';
  searchResHtml = '';
  search_offset = 0;
  main_map['map'].clearOverlays();
  // Simultaneously issue a search for businesses
  FindBusinesses(searchstring, null, null, searchsort);
  //if(SEARCH_FOR_USER_WITH_ONE_SEARCH){
  // SearchForUser(searchstring);
  //  locallite_controls += '<a id="tab2" style="width:230px; float:left; color:DarkGray; background-image:url(local/images/l_post_review.gif)" class="l_ask" href="Javascript:void(0)" onclick="SearchPageTabs(2);">Users</a>';
  //}

  //if(SEARCH_FOR_REVIEWS_WITH_ONE_SEARCH){
  //  SearchForReviews(searchstring);  
  //  locallite_controls += '<a id="tab3" style="width:150px; float:left; color:DarkGray; background-image:url(local/images/l_post_review.gif)" class="l_ask" href="Javascript:void(0)" onclick="SearchPageTabs(3);">Reviews</a>';
  //}
  locallite_controls += '</p>';
  SetDOMElementInnerHtml('controls', locallite_controls);
}

function FindBusinesses(what, search_index, localsearch, searchsort)
{
  if(!searchsort && GetDOMElement('searchsort'))
  	searchsort = GetDOMElementValue('searchsort');
  var search_index = (search_index == null) ? 0 : search_index;
  searchResIndex = search_index;
  var localsearch = (localsearch==null) ? true : localsearch;

//  if(SHOW_LOADING_GIF_ON_LEFT_CONTENT)
  if(false)
  {
    curSelIcn = null;
    curSelImg = null;
    curSelTag = null;
    LocalliteActiveDiv = null;
    ShowHideLocalliteSummary(0, 1);
	ShowElement('loading_gif');
	HideElement('Review');
	HideElement('User');
	HideElement('Listing');
	HideElement('controls');
    if(main_map['map'] && searchWeb)
		DeleteAllMapShapes(main_map['map']);
  }
  if(searchWeb)
    ClearBusinessTags();
  ClearErrorBox();

  div = CreateProgressBar();
  if (div)
    GetDOMElement('mapcontainer').appendChild(div);

  GeoAlert(10, "One search for "+what+" from index "+search_index);

  // Issue a search for businesses
  SendBusinessSearchRequest(what, search_index, localsearch, searchsort);
}

function SendBusinessSearchRequest(what, search_index, our_db, searchsort)
{
  GetMapView();

  var clat = main_map['lat'];
  var clon = main_map['lon'];
  //var tllat = (main_map['topleft']) ? GetLatitudeFromPoint(main_map['topleft']) : "";
  //var tllon = (main_map['topleft']) ? GetLongitudeFromPoint(main_map['topleft']) : "";
  //var brlat = (main_map['bottomright']) ? GetLatitudeFromPoint(main_map['bottomright']) : "";
  //var brlon = (main_map['bottomright']) ? GetLongitudeFromPoint(main_map['bottomright']) : "";
  var zoom = main_map['zoom'];
  var gg_url = get_business_search_url_base + "i=" + uid + "&c=" + upw + "&terms=" + encodeURI(what);
  gg_url += "&lat=" + clat + "&lon=" + clon  + "&dtype="+dtype;//+ "&sindex="+search_index
  //gg_url += "&miles="+SEARCH_AREA_IN_MILES;
  gg_url += "&sindex="+search_offset+ "&limit="+SEARCH_LIMIT;
  if(searchsort)
  	gg_url += "&searchsort="+searchsort;
  gg_url += "&zoom="+zoom;
  //gg_url += "&tllat="+tllat + "&tllon="+tllon + "&brlat="+brlat + "&brlon="+brlon;
  if(searchLocation)
    gg_url += "&location="+encodeURI(searchLocation);
  //if (our_db)
  //  gg_url += "&srchweb=1";

  var ggai = new AJAXInteraction(gg_url, ParseGetBusinessSearchResponse);
  ggai.Get();

   // XXXX: Commenting the "Search More" option that get more business from Google
  /*if (our_db)
  {
    var div = CreateSearchMoreLink();
    if (div)
      GetDOMElement('mapcontainer').appendChild(div);
  }//*/
}

function SearchForBizCategory(catid, index, bk, category)
{
  if(bk)
  	business_category_html = GetDOMElementInnerHtml('mastersummary');
  DeleteAllMapShapes(main_map['map']);
  SetDOMElementInnerHtml('mastersummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
  index = (index) ? index : 0;
  var gg_url = MAIN_URL_BASE+"bizcategorysearch.php?i=" + uid + "&c=" + upw + "&categoryid=" + catid+"&lat="+main_map['lat']+"&lon="+main_map['lon']+"&index="+index+"&category="+encodeURI(category)+"&miles="+TAG_CLOUD_AREA_IN_MILES;
  var ggai = new AJAXInteraction(gg_url, ParseGetBizCategoryResponse);
  ggai.Get();
}

function ParseGetBizCategoryResponse(response)
{
  if(response){
    var response = '<div class="grad"><a onclick="SetDOMElementInnerHtml(\'mastersummary\', business_category_html);" href="Javascript:void(0)" class="l_back">Back</a></div>'+response;
    SetDOMElementInnerHtml('mastersummary', response);
    if(GetDOMElement('script')){
      var script = GetDOMElementValue('script');
	  eval(script);
	  //var script = '{"result":['+GetDOMElementValue('script')+']}';
      //locallite_json = GetJson(text);
    }
  }
  else
    SetDOMElementInnerHtml('mastersummary', '');

  LocalliteActiveDiv = (GetDOMElement('wallObject0')) ? GetDOMElement('wallObject0') : (GetDOMElement('wallObject1')) ? GetDOMElement('wallObject1') : null;
}

// ashraf code
function SearchForBizCategoryAlphabatic(alphabit)
{
  ShowElement('mastersummary');
  HideElement('detailsummary');
  DeleteAllMapShapes(main_map['map']);
  SetDOMElementInnerHtml('mastersummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
  try{
	MallSpecificOnly(1);
  }
  catch(e)
  {}
  
  var gg_url = simple_request_url_base+"bizcategorysearchalphabitwiz&dtype="+dtype+"&word="+alphabit+"&i=" + uid+"&lat="+main_map['lat']+"&lon="+main_map['lon']+"&miles="+TAG_CLOUD_AREA_IN_MILES;
  var ggai = new AJAXInteraction(gg_url, ParseGetBizCategoryAlphabitResponse);
  ggai.Get();
}

function ParseGetBizCategoryAlphabitResponse(response)
{
    SetDOMElementInnerHtml('mastersummary', response);
    business_category_html = response;
}
// end ashraf code

function ParseGetBusinessSearchResponse(rstr)
{
  if (!rstr)
  {
    //searchstring = null;
    ShowElement('ready');HideElement('notready');
    if(searchWeb){
      FindBusinesses(searchTerm, 0, false);
      searchWeb = false;
      return null;
    }
    return DisplayNoSearchResultsMessage(0);
  }

  business_search_html = rstr;
  ShowElement('Listing');
  rstr = GetDOMElementInnerHtml('Listing')+""+rstr;
  SetDOMElementInnerHtml('Listing', rstr);
  ShowElement('ready');
  HideElement('notready');
  ShowElement('businessResults');
  ShowElement('businessResultsdiv');
  ShowElement('businessResultsclrbtn');
  DisplayNoSearchResultsMessage(1);
  var script = GetDOMElementValue('script');
  if(script)
    eval(script);
  search_offset++;
  return null;
}

function PrepareBusinessDescriptionHTML(tagIndex, j, title, info)
{
  var listingtxt = "";
  if(IPHONE_LOOK_LIKE_STYLE)
  {
    var latlon = NewLatLongPoint(info['lat'], info['lon']);
    var c = GetMapCenter(main_map['map']);
    var distance = (latlon) ? parseFloat((c.distanceFrom(latlon) * 0.62137) / 1000.0).toFixed(1) : null;
    var stars = '';
    var rating = parseInt(info['rating']);
    for(var s=1; s<=5; s++)
      stars += (s<=rating) ? '<img src="local/images/stars_small.png">' : '<img src="local/images/stars_small-02.png">';
    var className = '';
    if(j==1)
    {className = 'user_block selected';}
    else
    {className = 'user_block not_selected';}

    if(info['name'])
    {
      listingtxt = '<div id="wallObject'+tagIndex+'" ';

      if (info['ad'])
	listingtxt += ' class="user_block" style="background-color:#87E099;" onClick="ChangeLocalliteInActiveDivClass(null, '+info['bizid']+', null, null, null, '+info['adid']+');DisplayLocalliteSelectedTagInformation('+tagIndex+', -1, null, '+info['lat']+', '+info['lon']+', 1);" ';
      else
	listingtxt += ' onClick="ChangeLocalliteInActiveDivClass(this, '+info['bizid']+');DisplayLocalliteSelectedTagInformation('+tagIndex+', -1, null, '+info['lat']+', '+info['lon']+', 1);" class="'+className+'" ';

      listingtxt += '><div id="user_stars"><div id="stars" title="Business Rating">'+stars+'</div><div id="more"><div style="font-size:17px; float:left; padding-left:20px; color:#9FA2A5;"><strong>Tag '+ j +'.</strong></div><img height="21" width="13" alt="" src="local/images/user_arrow.png" title="Click to see description"/></div></div><div id="user_thumb"><img height="54" width="57" alt="" src="local/images/user_ico.png"  title="Business Category"/></div><div id="user_pic"><img height="51" width="51" alt="" src="local/images/user_pic.gif"  title="User Image"/></div><div id="user_description">'+info['graffitiownername'] +'-'+ info['timeupdate']+'<br/><strong>'+info['name']+'</strong><br/><span>'+info['address']+'</span></div><div id="icons"><div id="icons_right"><ul><li><img height="25" align="absmiddle" width="25" alt="" src="local/images/user_icons.png" title="Reviews" /> '+info['numreview']+'</li><li><img height="26" align="absmiddle" width="30" alt="" src="local/images/user_icons-02.png" title="Voice Notes"/> 0</li><li><img height="21" align="absmiddle" width="27" alt="" src="local/images/user_icons-03.png" title="Images"/> '+info['numpics']+'</li><li style="text-align: right; width:100px;" title="Distance" >'+distance+' miles</li></ul></div><div id="icons_left">';
      var Favorite = '';
      if(info['favorite']==1)
	Favorite += '<img src="local/images/user_icos_colored.png" title="User Favorite" width="21" height="19" alt="" />';
      else
	Favorite += '<img src="local/images/user_icons-04.png" title="Not User Favorite" width="20" height="19" alt="" />';
      
      listingtxt += Favorite+'<img height="19" width="21" alt="" src="local/images/user_icons-05.png" title="Not User Followee"/></div></div>';
      if(info['ad'])
	listingtxt +=  '<div class="marquee"><marquee title="Business Ad" behavior="scroll" direction="left" scrollamount="2"><font color="#ff0066"><b>'+ info['ad'] +'</b></font></marquee></div></div>';
      else if(info['bizad'])
	listingtxt +=  '<div class="marquee"><marquee title="Business Ad" behavior="scroll" direction="left" scrollamount="2"><font color="#ff0066"><b>'+ info['bizad'] +'</b></font></marquee></div></div>'; 	
      else
	listingtxt += '</div>';
    }
    else if(info['ad'])	
    {
      // Ad only - no information about business!!
      listingtxt = '<div id="wallObject'+tagIndex+'" onClick="ChangeLocalliteInActiveDivClass(null, null, null, null, null, '+info['adid']+');DisplayLocalliteSelectedTagInformation('+tagIndex+', -1, null, '+info['lat']+', '+info['lon']+', 1);" class="user_block" style="background-color:#87E099; "><div id="user_stars"><div id="stars">'+stars+'</div><div id="more"><div style="font-size:17px; float:left; padding-left:20px; color:#9FA2A5;"><strong>Tag '+ j +'.</strong></div><img height="21" width="13" alt="" src="local/images/user_arrow.png"/></div></div><div id="user_thumb"><img height="54" width="57" alt="" src="local/images/user_ico.png"/></div><div id="user_pic"><img height="51" width="51" alt="" src="local/images/user_pic.gif"/></div><div id="user_description">'+info['graffitiownername'] +'-'+ info['timeupdate']+'<br/><strong>'+info['ad']+'</strong><br/><span>-</span></div><div id="icons"><div id="icons_right"><ul><li><img height="25" align="absmiddle" width="25" alt="" src="local/images/user_icons.png"/> '+info['numreview']+'</li><li><img height="26" align="absmiddle" width="30" alt="" src="local/images/user_icons-02.png"/> 0</li><li><img height="21" align="absmiddle" width="27" alt="" src="local/images/user_icons-03.png"/> 0</li><li style="text-align: right; width:100px;">'+distance+' miles</li></ul></div><div id="icons_left"><img height="19" width="20" alt="" src="local/images/user_icons-04.png"/><img height="19" width="21" alt="" src="local/images/user_icons-05.png"/></div></div></div>';
    }
  }
  else
  {
    listingtxt = '<table id="wallObject'+tagIndex+'"><tr><td><div style="float:left; width:46px; text-align:center;" id="rankarrow">'+j+'</div><div id="business'+j+'" style="text-align:left; height:40px; float:left; width:260px;"><label onmouseover="OpenInfoWindowForList('+j+', 1)" style="float:none;width:260px;" for="inp1">'+title+'</label></div></td></tr></table>';
  }

  return listingtxt;
}

function ChangeLocalliteInActiveDivClass(elem, bizid, oid, graffitiid, alisid, adid, qryid, ispromotion, islivepage, level_string)
{
  if(curSelTag && curSelImg)
    curSelTag.setImage(curSelImg);
  curSelTag = null;
  curSelImg = null;	
  
  if(level_string)
  {
	  try
	  {
		  if(level_string=="Level 1"){
			KMLLoader(GOOGLE_MAP_KMZ_FILE_LEVEL_ONE);
			ShowLevelBaseTags(1);
			}
		  else if(level_string=="Level 2"){
			KMLLoader(GOOGLE_MAP_KMZ_FILE_LEVEL_TWO);
			ShowLevelBaseTags(2);
		  }
		  else if(level_string=="Level 3"){
			KMLLoader(GOOGLE_MAP_KMZ_FILE_LEVEL_THREE);
			ShowLevelBaseTags(3);
		  }
	   } 
	   catch(e){}
  }
  if(LocalliteActiveDiv && !adid)
  {
    LocalliteActiveDiv.className = 'user_block not_selected';
    if(bizid)
      //ShowHideLocalliteSummary(1, 0, bizid, oid, graffitiid, alisid, adid, qryid);
      ShowHideLocalliteSummary(1, 0, bizid, oid, graffitiid, alisid, adid, qryid, false, ispromotion, islivepage);
  }
  else
  {
    var divelem = (GetDOMElement('wallObject0')) ? GetDOMElement('wallObject0') : (GetDOMElement('wallObject1')) ? GetDOMElement('wallObject1') : null;
    if(divelem && !adid)
    {		
      if(divelem.className!="user_block")
	divelem.className = 'user_block not_selected';
      if(bizid)
	//ShowHideLocalliteSummary(1, 0, bizid, oid, graffitiid, alisid);
	ShowHideLocalliteSummary(1, 0, bizid, oid, graffitiid, alisid, null, null, false, ispromotion);
    }
  }
  if(adid)	
  {
    // Just Call Ajax No Class Change
    //ShowHideLocalliteSummary(1, 0, bizid, oid, graffitiid, alisid, adid);
    ShowHideLocalliteSummary(1, 0, bizid, oid, graffitiid, alisid, adid, null, false, ispromotion);
  }
  if(elem && !adid)
  {
    elem.className = 'user_block selected';
    LocalliteActiveDiv = elem;
  }
}

function OpenInfoWindowForList(bizindex, isBusinessSearch)
{
  if(bizindex<0)
    return null;

  if(isBusinessSearch)
  {
    var gm = main_map['find_biz_layer'][bizindex];
    OnMouseOverListener(main_map['map'], gm.getLatLng(), main_map['find_biz_description'][bizindex], gm, bizindex);
  }
  else
  {
    var gm = main_map['wall_object_layer'][bizindex];
    OnMouseOverListener(main_map['map'], gm.getLatLng(), main_map['wall_object_description'][bizindex], gm);
  }
}

function SearchForWall(what)
{
  var sfw_url = get_wall_search_url_base+ "i=" + uid + "&c=" + upw;
  sfw_url += "&terms="+encodeURI(what);
  var sfwai = new AJAXInteraction(sfw_url, ParseGetWallResponse);
  sfwai.Get();	
}

function ParseGetWallResponse(rstr)
{
  var json = GetJson(rstr);
  var gnum = (json) ? json.result.length : 0;
  var html = "";
  var total = 0;
  if(window.location.href && window.location.href.indexOf(managewalls_file) > 0)
  {
    SetDOMElementInnerHtml('grpGroups', '');
  }
  for(var g=0; g<gnum; g++)
  {
    var elem = json.result[g]; 	
    var gid =   elem.gid;
    if(!gid)
      continue;
    total++;
    var gname =   elem.gname;
    var gowner =   elem.gowner;
    var gtype = (elem.gtype) ? elem.gtype : null;
    var selected =   elem.selected;
    selected = (selected!="") ? true : false;
    var title = gowner+" : "+ gname;

    if(window.location.href && window.location.href.indexOf(managewalls_file) > 0)
    {
      var option = document.createElement('option');
      option.value = gid;
      option.appendChild(document.createTextNode(title));
      GetDOMElement('grpGroups').appendChild(option);
      continue;
    }
    var gtypestyle = "";
    if(gtype && gtype=='biz')
      gtypestyle = "color:ForestGreen;font-weight:bold;";
    if(selected)
    {
      html += '<div id='+g+' style="text-align:left; height:20px;'+gtypestyle+'"><input id="inp1" name="" type="checkbox" value="'+ gid+'"  checked onclick="ToggleTagGroupDisplay('+ gid +');" /><label style="margin-left:25px; float:none;" for="inp1">'+title+'</label></div>';
    }
    else	
    {
      html += '<div id='+g+' style="text-align:left; height:20px;'+gtypestyle+'"><input id="inp1" name="" type="checkbox" value="'+gid+'"  onclick="ToggleTagGroupDisplay('+gid+'); nid = GetDOMElementValue(\'maxWallDisp\'); if(nid==0) {SetDOMElementInnerHtml(\'grpList\', \'\');}  SetDOMElementValue(\'maxWallDisp\', (parseInt(nid)+1)); this.id = \'chk\'+(parseInt(nid)); this.checked; ddiv = GetDOMElement(\'grpList\').innerHTML; this.parentNode.style.display=\'none\';  ddiv += (\'<div style=text-align:left;height:20px;'+gtypestyle+' ><input type=checkbox checked name=chk id=\'+this.id+\' value=\'+this.value+\' onclick=ToggleTagGroupDisplay('+gid+'); /><label style=margin-left:25px;float:none; for=inp1>\'+this.parentNode.childNodes.item(1).innerHTML+\'</label></div>\'); SetDOMElementInnerHtml(\'grpList\', ddiv);" /><label style="margin-left:25px; float:none;" for="inp1">'+title+'</label></div>';
    }
  }
  if(total==0)
    html += '<div style="text-align:left; height:20px;"><label style="margin-left:25px; float:none;" for="inp1">No Matching Walls!</label></div>';

  SetDOMElementInnerHtml('searchResultsdiv', html);
  ShowElement('searchResultsdiv');
  ShowElement('searchResultsclrbtn');
}

function SearchForUser(searchstring)
{  
  var sfw_url = simple_request_url_base+ "usersearch&i=" + uid + "&c=" + upw+"&dtype="+dtype;
  sfw_url += "&terms="+ encodeURI(searchstring);
  var sfwai = new AJAXInteraction(sfw_url, ParseGetUserResponse);
  sfwai.Get();
}

function ParseGetUserResponse(rstr)
{
  var string = '';
  if(rstr=="")
    string = '<div class="user_block not_selected" style="height:100px;font-size:20px;">No matching users found.</div>';
  var json = GetJson(rstr);
  var resultlen = (json && json.result) ? json.result.length : 0;
  for(var u=0; u<resultlen; u++){
    if(json.result[u].name)
      string += '<div class="user_block not_selected"><div id="user_stars"></div><div id="user_thumb"></div><div id="user_pic"><img height="51" width="51" title="User Image" src="'+json.result[u].image+'" alt=""/></div><div id="user_description">-<br/><strong>'+json.result[u].name+'</strong><br/><span>&nbsp;</span></div><div id="icons"><div id="icons_right"></div><div id="icons_left"></div></div></div>';
  }
  SetDOMElementInnerHtml('User', string);
}

function SearchForReviews(searchstring)
{
  var clat = main_map['lat'];
  var clon = main_map['lon'];	
  var tllat = (main_map['topleft']) ? GetLatitudeFromPoint(main_map['topleft']) : "";
  var tllon = (main_map['topleft']) ? GetLongitudeFromPoint(main_map['topleft']) : "";
  var brlat = (main_map['bottomright']) ? GetLatitudeFromPoint(main_map['bottomright']) : "";
  var brlon = (main_map['bottomright']) ? GetLongitudeFromPoint(main_map['bottomright']) : "";
  var zoom = main_map['zoom'];	

  var sfw_url = simple_request_url_base+ "reviewsearch&i=" + uid + "&c=" + upw+"&dtype="+dtype;
  sfw_url += "&terms="+encodeURI(searchstring);
  sfw_url += "&lat="+clat+"&lon="+clon+"&tllat="+tllat+"&tllon="+tllon+"&brlat="+brlat+"&brlon="+brlon+"&zoom="+zoom;
  var sfwai = new AJAXInteraction(sfw_url, ParseGetReviewsResponse);
  sfwai.Get();
}

function ParseGetReviewsResponse(rstr)
{
  var string = '';
  if(rstr=="")
    string = '<div class="user_block not_selected" style="height:100px;font-size:20px;">No matching reviews found.</div>';
  var json = GetJson(rstr);
  var resultlen = (json && json.result) ? json.result.length : 0;
  for(var u=0; u<resultlen; u++){
    if(json.result[u].graffitiid)
      string += '<div class="user_block_small" onClick="HideElement(\'Review\');ShowHideLocalliteSummary(1, 0, '+json.result[u].bizid+', '+json.result[u].oid+', '+json.result[u].graffitiid+', null, null, null, '+json.result[u].gmdid+');"><div class="descr"><div title="User Rating" class="stars"><img src="local/images/stars_small-02.png"/><img src="local/images/stars_small-02.png"/><img src="local/images/stars_small-02.png"/><img src="local/images/stars_small-02.png"/><img src="local/images/stars_small-02.png"/>  <img height="10" width="10" src="local/images/ico_mini.png" alt=""/><p><img height="15" align="absmiddle" width="10" src="local/images/user_arrow_sm.png" alt=""/></p>	</div>	<div class="icon"><img height="13" width="14" alt="" src="local/images/user_icons-05.png"/></div>	<div class="thumb"><img height="33" width="33" title="User Image" src="'+  json.result[u].image +'" alt=""/></div>	<div class="description">'+json.result[u].uname+'  &nbsp;  '+json.result[u].timeadded+'<br/>	</div>	</div>	<div class="note">	<img height="16" align="absmiddle" width="20" src="local/images/ico_note.gif" alt=""/> Review: '+json.result[u].review+'<br/></div></div>';
  }
  SetDOMElementInnerHtml('Review', string);
}

function GetExtraBizInfo(searchstring, business_ids)
{
  var gg_url = get_extra_business_information_url_base+ "i=" + uid + "&c=" + upw;
  gg_url += "&terms="+encodeURI(searchstring)+"&businesssearchresultxml="+business_ids;

  var ggai = new AJAXInteraction(gg_url, ParseGetExtraBusinessInformation);
  ggai.Get();	
}

function ParseGetExtraBusinessInformation(rstr)
{
  //alert(rstr);
}

function CreateNextPreviousLinks(next, previous)
{
  var div = document.createElement("div");
  if (!div)
    return null;

  div.setAttribute('id','searchBusinessNextPrevLink');
  div.style.top = "285px";
  div.style.position='absolute';
  div.style.width='60px';
  div.style.left = "8px";
  div.style.border = "solid";
  div.style.borderWidth = "thin";
  div.style.fontFamily = "Arial";
  div.style.fontSize = "11px";

  var Divhtml = "";
  if (next > 0)
    Divhtml += "<div align=center style='background:white;padding-top:5px;height:25px;'><a href=\"Javascript: FindBusinesses(null, "+ next +")\">Next</a></div>";
  else
    Divhtml += "<div align=center style='background:white;padding-top:5px;height:25px;'>Next</div>";

  if (previous >= 0)
    Divhtml += "<div align=center style='background:white;padding-top:5px;height:25px;'><a href=\"Javascript: FindBusinesses(null, "+ previous +")\">Previous</a></div>";
  else
    Divhtml += "<div align=center style='background:white;padding-top:5px;height:25px;'>Previous</div>";

  div.innerHTML = Divhtml;
  return div;
}

function CreateSearchMoreLink()
{
  var elem = GetDOMElement("searchBusinessSearchMoreLink");
  if(elem)
  {
    var divhtml = "<div align=center style='background:white;padding-top:5px;height:40px;'><a href=\"Javascript: FindBusinesses('"+ GetDOMElementValue('biznametype') +"', 0, false)\">Search More >> </a></div>";

    elem.innerHTML = divhtml;
    ShowElement("searchBusinessSearchMoreLink");
    return null;
  }

  var div = document.createElement("div");
  if (!div)
    return null;

  div.setAttribute('id','searchBusinessSearchMoreLink');
  div.style.top = "285px";
  div.style.position='absolute';
  div.style.width='60px';
  div.style.left = "8px";
  div.style.border = "solid";
  div.style.borderWidth = "thin";
  div.style.fontFamily = "Arial";
  div.style.fontSize = "11px";

  var divhtml = "";
  divhtml += "<div align=center style='background:white;padding-top:5px;height:40px;'><a href=\"Javascript: FindBusinesses('"+ GetDOMElementValue('biznametype') +"', 0, false)\">Search More >> </a></div>";

  div.innerHTML = divhtml;
  return div;
}

function CreateProgressBar()
{
  if(!SHOW_LOADING_GIF_ON_MAP)
    return null;
  if(GetDOMElement("progressBar"))
  {
    HideElement("progressBar", true);
    return null;
  }
  else
  {
    var div = document.createElement("div");
    if (!div)
      return null;

    div.setAttribute('id','progressBar');
    div.style.position='absolute';
    div.style.width='auto';
    div.style.height='75px';
    div.style.top = "270px";
    div.style.left = "145px";
    div.style.borderStyle = "none";
    div.style.backgroundColor = "skyblue";
    div.style.color = "white";
    //div.innerHTML = "<img height='50px' width='50px' src='" + IMAGE_URL_BASE+"progressbar.gif'>";
    div.innerHTML = GetProgressBarObject()+'<center><b>Working...</b></center>';

    return div;
  }
}

function GetProgressBarObject()
{
  return '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="200" height="60" id="logo" align="top"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="' + IMAGE_URL_BASE+'logo.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#58b1ff" /><embed src="' + IMAGE_URL_BASE+'logo.swf" quality="high" bgcolor="#58b1ff" width="200" height="60" name="logo" align="top" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
}

function HideProgressBar()
{
  HideElement("progressBar");
}

function CreateLetterIcon(index, color)
{
  if(MSFT==1)
    return null;
  else
  {
    var baseIcon = new GIcon();
    if (!baseIcon)
      return null;

    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);

    // Create a lettered icon for this point using our icon class
    var letter = String.fromCharCode("A".charCodeAt(0) + index);
    var letteredIcon = new GIcon(baseIcon);
    if(color)
		if(index)
	      letteredIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/"+ color +"/marker" + index + ".png";
		else
		  letteredIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/"+ color +"/blank.png";
    else
      letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
    return letteredIcon;
  }
}


function ClearBusinessTags()
{
  //XXXX: close infoWindow if open	
  RemoveInfoWindow();

  // TODO: Aftab: the purpose of this function is just to clear the
  // results of the last set of tags added by the call of FindBusinesses
  // and not the tags that the user may be currently displaying (such
  // as the tags associated with a group, for example).
  if(MSFT==1)
  {
    if (main_map['find_biz_layer'] != null)
      main_map['find_biz_layer'].DeleteAllShapes();
  }
  else
  {
    if(main_map['find_biz_layer'])
    {
      for(var btag=0; btag<(main_map['find_biz_layer'].length); btag++)
      {
	if(main_map['find_biz_layer'][btag])
	{
	  main_map['map'].removeOverlay(main_map['find_biz_layer'][btag]);
	}
      }
    }
//    if(main_map['map']!=null)
//      main_map['map'].clearOverlays();
  }

  HideElement("div");
  HideElement("searchBusinessNextPrevLink");
  //HideElement("searchBusinessSearchMoreLink");

  SetDOMElementInnerHtml('businessResultsdiv', '');
  HideElement('businessResultsdiv');
  HideElement('businessResultsclrbtn');
}

function SetMapDisplayedArea(clatid, clonid, tllatid, tllonid, brlatid, brlonid, zoomid)
{
  var clat = GetDOMElement(clatid);
  var clon = GetDOMElement(clonid);
  var tllat = GetDOMElement(tllatid);
  var tllon = GetDOMElement(tllonid);
  var brlat = GetDOMElement(brlatid);
  var brlon = GetDOMElement(brlonid);
  var zid = GetDOMElement(zoomid);

  // Do not submit the form if can not find the DOM elements
  if (!clat || !clon || !tllat || !tllon || !brlat || !brlon || !zid)
    return false;

  GetMapView();

  clat.value = main_map['lat'];
  clon.value = main_map['lon'];

  tllat.value = (main_map['topleft']) ? GetLatitudeFromPoint(main_map['topleft']) : "";
  tllon.value = (main_map['topleft']) ? GetLongitudeFromPoint(main_map['topleft']) : "";
  brlat.value = (main_map['bottomright']) ? GetLatitudeFromPoint(main_map['bottomright']) : "";
  brlon.value = (main_map['bottomright']) ? GetLongitudeFromPoint(main_map['bottomright']) : "";
  zid.value = main_map['zoom'];

  return true;
}

function AddAreaOfExpertise(nameid, clatid, clonid, tllatid, tllonid, brlatid, brlonid, zoomid)
{
  var nid = GetDOMElement(nameid);
  if (!nid)
    return false;

  if (!nid.value || nid.value=="")
  {
    GeoAlert(0, "Please enter a string to refer to this map view with.");
    return false;
  }

  return SetMapDisplayedArea(clatid, clonid, tllatid, tllonid, brlatid, brlonid, zoomid);
}

function DisplayAreaOfExpertise(clat, clon, zf)
{
  if (!clat || !clon)
    return false;

  return SetMapCenterAndZoomLevel(clat, clon, zf);
}

function IsGroupBeingDisplayed(gid)
{
  if (checked_groups["'"+gid+"'"] == null)
    return false;

  return true;
}

function DeleteGroupPins(gid)
{}

function ClearGroupPushPins(gid)
{
  if (displayed_groups["'"+gid+"'"] == null)
    return;
	
  if (displayed_groups["'"+gid+"'"]['pp'] != null)
  {
    var count=0;
    for (var gp in displayed_groups["'"+gid+"'"]['pp'])
    {
      var pp = displayed_groups["'"+gid+"'"]['pp'][gp];
      if (pp != null)
      {
	(MSFT==1) ? main_map['map'].DeleteShape(pp) : main_map['map'].removeOverlay(pp);
	count++;
      }
      displayed_groups["'"+gid+"'"]['pp'][gp] = null;
    }
    displayed_groups["'"+gid+"'"]['pp'] = null;
    GeoAlert(12, "Hid "+count+" pins");
  }
}

function SendXMLHTTPRequest(url, read_ftn)
{
  var req = null;
  if (window.XMLHttpRequest){ //Mozilla, Firefox, Opera 8.01, Safari
    req = new XMLHttpRequest();
  }
  else if(window.ActiveXObject){ //IE
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else { //Older Browsers
    GeoAlert(0, "Argh! Unable to display tags because your browser does not support Ajax. Sorry.");
    return null;
  }

  if (req) {
    GeoAlert(13, "Sending HTTP request: " + url);
    req.open("GET", url, true);
    req.send(null);
    req.onreadystatechange = read_ftn;
    return req;
  }

  return null;
}

function AJAXInteraction(url, callback)
{
  var req = init();
  req.onreadystatechange = processRequest;

  function init()
  {
    if (window.XMLHttpRequest)
    {
      return new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
  }

  function processRequest ()
  {
    if (req.readyState == 4)
    {
      if (req.status == 200)
      {
	if (callback)
	  callback(req.responseText);
      }
    }
  }

  this.Get = function()
    {
      req.open("GET", url, true);
      req.send(null);
    }

  this.Post = function(body)
    {
      req.open("POST", url, true);
      req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      req.send(body);
    }
}

// TODO: this function is called when the map moves. Now what happens
// with moving objects? Well the map moves. So you get into an endless
// cycle of moving map, causing new group tags fetches, which causes the
// map to move, which causes new fetches, etc.
function UpdateDisplayOfAllGroupTags(forlocalliteupdateonly)
{
  RemoveInfoWindow(1);

  SetDOMElementInnerHtml('dispWallGrftidiv', '');
  // Store the current view in a cookie
  GetMapView();
  if(IPHONE_LOOK_LIKE_STYLE)
  {
    if(forlocalliteupdateonly)
    {
      CancelTagUpdate();
      ShowHideLocalliteSummary(1, 0, GetDOMElementValue('bizid'), GetDOMElementValue('oid'), GetDOMElementValue('graffitiid'), GetDOMElementValue('writeraliasid'));
    }
    return null;
  }

  if (utaggid > ALL_GLOBAL_GROUPS)
  {
    // Remove the old pins
    DeleteGroupPins(utaggid);

    // Put new tags
    //GetGroupTags(utaggid);
  }
  else
  {
    for (var gid in checked_groups)
    {
      var gnum = checked_groups[gid];
      if (gnum != null)
      {
	// Remove the old pins
	DeleteGroupPins(gnum);

	// Put new tags
	//GetGroupTags(gnum);
      }
    }
  }

  GetAllDisplayedGroupsTags();
}

var ol = null;
var mbox  = null;
function DeleteGroupTag(oid, graffitiid)
{
  if (oid <= 0)
    return null;

  ol = CreateGrayOverlay();
  mbox = CreateModalDialogBox();

  customized_tag_form_html = null;

  var desc = (main_map['type']!=MOBIKU_MAP) ? '<div style="height:20px;width:420px;background-color:#DEEA9B;color:#336600;text-align:center;padding-top:3px;">Delete Graffiti</div><br/><br/><table width="100%"><tr  style="height:28px;"><td style="font-weight:normal; color:#bed63a;">Please confirm that you really want to delete this graffiti.</td></tr></table><input type="hidden" name="hdnOid" id="hdnOid" value="'+oid+'" /><br /><br /><div><a onclick="CancelTagUpdate();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_cancel.png"/></a><a onclick="DeleteTag();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_submit.png"/></a></div>' : '<br/><table width="100%"><tr  style="height:28px;"><td style="font-weight:normal;">Please confirm that you really want to delete this graffiti.</td></tr></table><input type="hidden" name="hdnOid" id="hdnOid" value="'+oid+'" /><br /><br /><div><a onclick="CancelTagUpdate();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_cancel.png"/></a><a onclick="DeleteTag();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_submit.png"/></a></div>';
  desc += '<input type="hidden" name="oid" id="oid" value="'+oid+'" />';
  desc += '<input type="hidden" name="graffitiid" id="graffitiid" value="'+graffitiid+'" />';

  var html = GetPopupHTML(desc, 'deletegraffiti');
  if(mbox)
    mbox.style.left = '350px';

  SetDOMElementInnerHtml('mbox', html);
}


function DeleteTag()
{
  var gid = GetDOMElementValue("selGroup");
  var oid = GetDOMElementValue("oid");
  var graffitiid = GetDOMElementValue("graffitiid");

  if(gid && parseInt(gid)<0)
  {
    var dt_url = delete_tag_group_url_base + oid+"&i="+uid+"&c="+upw;
  }
  else
  {
    var dt_url = delete_tag_group_url_base + oid+"&i="+uid+"&c="+upw;
    dt_url += (gid) ? "&gid="+gid : "";
  }
  dt_url += (graffitiid) ? "&graffitiid="+graffitiid : "";

  //   if(document.getElementById("div"+graffitiid))
  //     DisplayBoxError("Graffiti Deleted Successfully");

  var dtai = new AJAXInteraction(dt_url, ParseDeleteTagResults);
  if (dtai)
    dtai.Get();
}

function ParseDeleteTagResults(rstr)
{
  var gid = GetDOMElementValue("selGroup");
  var oid = GetDOMElementValue("oid");
  var graffitiid = GetDOMElementValue("graffitiid");

  if(GetDOMElement("div"+graffitiid))
  {
    DisplayBoxError("Graffiti Deleted Successfully");

    HideElement("div"+graffitiid);
    CancelTagUpdate(1);

    if(document.frmViewGraffiti)
      document.frmViewGraffiti.submit();

    return true;
  }

  ClearBusinessTags();
  GetGroupTags(gid);
  CancelTagUpdate();

  UpdateDisplayOfAllGroupTags();
}

function CreateDomDocumentObject(xmlString)
{
  var xmlDoc = null;
  if((navigator.appName).indexOf("Microsoft Internet Explorer")>=0) //Internet Explorer
  {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(xmlString);
  }
  else
  { //Firefox, Mozilla, Opera, etc.
    var parser=new DOMParser();
    var xmlDoc=parser.parseFromString(xmlString,"text/xml");
  }
  return xmlDoc;
}

function CleanTagString(str)
{
  if (!str)
    return null;

  str = str.replace(/#/g, " ");
  str = str.replace(/&/g, " ");
  str = str.replace(/\|==\|/g, " ");
  str = str.replace(/<br>/g, " ");
  str = str.replace(/<br\/>/, " ");
  str = str.replace(/<br \/>/, " ");
  str = str.replace(/\s+/g, " ");

  str = str.replace(/%0A/g, "");	
  str = str.replace(/%2B/g, " ");	
  str = str.replace(/%2C/g, "");
  str = str.replace(/%0D/g, "");
  str = str.replace(/%5Ct/g, "");	// for /t
  str = str.replace(/%5Cn/g, "<br>");   // for /n
  str = str.replace(/%5Ch/g, "");   // for /h

  var l = str.indexOf("<![CDATA[");
  return (l >= 0) ? str.substr(l + 9, str.length - 12) : str;
}

function CleanBizContactInformation(str)
{
  return CleanTagString(str);
}

function StartObjectProximityCheckTimer()
{
  proximity_check_timer = setInterval("CheckForTagsInProximityToMovingObjects()", 20000);
}

function GetProximityTags(oid, last_lat, last_lon)
{
  var pt_url = proximity_tag_check_url_base + "i=" + uid + "&c=" + upw + "&oid=" + oid;
  pt_url += "&lat=" + last_lat;
  pt_url += "&lon=" + last_lon;

  var ptai = new AJAXInteraction(pt_url, ParseGetProximityTagsResults);
  if (ptai)
    ptai.Get();
}

function ParseGetProximityTagsResults(rstr)
{
  var poid = nth_xml_tag(rstr, "oid", 0);
  var pnum = str_num_occurrences(rstr, "<Tag>");

  GeoAlert(10, "There are "+pnum+" tags in proximity to object "+poid);
  for (var i=0; i<pnum; i++)
  {
    var ptgname = nth_xml_tag(rstr, "GroupName", i);
    var ptname = nth_xml_tag(rstr, "Name", i);
    var ptdesc = nth_xml_tag(rstr, "Description", i);

    GeoAlert(2, "Tag "+ptname+" ("+ptdesc+") of group ("+ptgname+") near object "+poid);
  }
}

// used to get the instant messages for the user.
function GetInstantMessages()
{
  SendRequestToGetInstantMessages();
  setTimeout('GetInstantMessages()', 10000);
}

function ShowError(m, show_error_time_interval)
{
  SetUserLogOutInterval();
  if(SHOW_ERROR_WITH_JQUERY_DIALOG)
  {
    if(m.length>1)
    {
      OpenJQDialog(m, show_error_time_interval);
    }
    return null;
  }
  SetDOMElementValue('output_msg_box', m);

  clearTimeout(ErrorMsgAutoCloseInterval);
  if(!(GetDOMElement('errorBox')) && m!=" ")
  {
	  alert(m);
	  return null;
    var dist = GetDistanceFromTop();
    var div = document.createElement('div');	
    div.setAttribute('id', 'errorBox');
    div.style.width = '470px';
    div.style.height = '50px';
    div.style.position = 'fixed';
    div.style.backgroundColor = 'lightGoldenRodYellow';

    div.style.top = '0px';
    div.style.marginLeft = '40px';
    if(main_map['type']!=MOBIKU_MAP) div.style.color = '#BED63A';
    div.style.display = 'none';
    div.style.zIndex = '1000';
    div.style.float = 'left';
    div.innerHTML = GetPopupHTML(m, 'errorbox');
    var obody=document.getElementsByTagName('body')[0];
    obody.insertBefore(div,obody.firstChild);
    interval=setInterval('ShowErrorBox()',2);
    AutoCloseErrorBox();
    return false;
  }
  else
  {
    var  div = GetDOMElement('errorBox');

    if(m==" ")
    {
      interval=setInterval('HideErrorBox()',2);
      return false;
    }

    div.innerHTML = GetPopupHTML(m, 'errorbox');

    if(div.style.display != 'block')
    {
      interval=setInterval('ShowErrorBox()',2);
    }

    AutoCloseErrorBox();
    return false;
  }
}

function SetMarqueeTimeout()
{}

function GetPopupHTML(m, popupname)
{
  if(!popupname)
    return null;

  if (!m)
    m = "";

  var returnString = "";
  switch (popupname)
  {
      case 'errorbox':
	returnString = (main_map['type']!=MOBIKU_MAP) ? "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login' style='height:50px'><div style='float:left;height:inherit;width:95%;text-align:left;'><b>"+m+"</b></div><div style='float:left;width:5%;'><img title='Close Popup' src='"+IMAGE_URL_BASE+"help_close.gif' onClick='interval=setInterval(\"HideErrorBox()\",2);return false;'></div></div></div></div></div></div></div></div></div></div>" : '<div class="post"><div class="ct"><div class="l"><div style="height:auto; padding-left:5px;" class="r"/>'+m+'</div></div><div style="padding-top:5px;text-align:right;" class="entry"><img title="Close Popup" src="'+IMAGE_URL_BASE+'help_close.gif" onClick="interval=setInterval(\'HideErrorBox()\',2);return false;"></div><div class="cb"><div class="l"><div class="r"/></div></div></div>';
	break;
      case 'createwall':
	returnString = "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login'><div style='height:15px;'></div><div id='tagpopuptempHdng' style='margin-top:-15px; width:375px;'><strong>Create Graffiti Wall</strong></div>";
	break;
      case 'existingwallquestion':
	returnString = "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login'><div style='height:15px;'></div><div id='tagpopuptempHdng' style='margin-top:-15px; width:375px;'><strong>Post Question To Facebook</strong></div>";
	break;
      case 'graffitidescription':

	returnString = (main_map['type']!=MOBIKU_MAP) ? "<div class='tcbg6'><div class='bcbg6'><div class='lcbg6'><div class='rcbg6'><div class='tlbg6'><div class='trbg6'><div class='blbg6'><div class='brbg6' style='height:130px;'><div><div style='padding-top:0px; padding-bottom:5px; padding-left:10px; padding-right:10px; '>"+m+"</div></div></div></div></div></div></div></div></div></div>" : "<div style='height:150px;background-color:#E2DE9E;'><div><div style='height:16px; width:auto; padding-top:5px; margin-left:211px;'>&nbsp;</div><div style='padding-top:0px; padding-bottom:5px; padding-left:10px; padding-right:10px; '>"+m+"</div></div></div>";
	break;
      case 'simplemapanswer':
	returnString = "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login'><div style='height:15px;'><img src='"+IMAGE_URL_BASE+"btn_minimize.gif' title='Close Popup and Hide Tag' onClick='RemoveInfoWindow(1);'>&nbsp;<img src='"+IMAGE_URL_BASE+"help_close.gif' onClick='RemoveInfoWindow();'></div><div id='tagpopuptempHdng' style='margin-bottom:0px;margin-top:-15px; width:216px;'><strong>Answer Tag</strong></div><br/><div style='height:75px;color:#bed63a; text-align:left;'>"+m+"<div>";
	break;
      case 'userloginreg':
	returnString = "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login' style='height:250px;width:420px;'><div style='float:left;height:inherit;width:95%;text-align:left;'><b>"+m+"</b></div><div style='float:left;width:5%;'><img title='Close Popup' src='"+IMAGE_URL_BASE+"help_close.gif' onClick='CancelTagUpdate();'></div></div></div></div></div></div></div></div></div></div>";
	break;
      case "edittag":
	returnString = "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login' style='height:250px;width:390px;'><div style='float:left;height:inherit;width:95%;text-align:left;'><b>"+m+"</b></div><div style='float:left;width:5%;'></div></div></div></div></div></div></div></div></div></div>";
	break;
      case 'simplemboxbox':
	returnString = "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login' style='height:50px'><div style='float:left;height:inherit;width:95%;text-align:left;'><b>"+m+"</b></div><div style='float:left;width:5%;'></div></div></div></div></div></div></div></div></div></div>";
	break;
      case 'emailgraffiti':
	returnString = (main_map['type']!=MOBIKU_MAP) ? "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login' style='height:250px;width:420px;'><div style='float:left;height:inherit;width:95%;text-align:left;'><b>"+m+"</b></div><div style='float:left;width:5%;'></div></div></div></div></div></div></div></div></div></div>" : '<div class="post"><div class="ct"><div class="l"><div class="r"/></div></div><h3 class="title">Email Graffiti To A Friend</h3><p class="byline"/><div class="entry">'+m+'</div><div class="cb"><div class="l"><div class="r"/></div></div></div>';
	break;
      case 'deletegraffiti':
	returnString = (main_map['type']!=MOBIKU_MAP) ? "<div class='tcbg2'><div class='bcbg2'><div class='lcbg2'><div class='rcbg2'><div class='tlbg2'><div class='trbg2'><div class='blbg2'><div class='brbg2'><div class='login' style='height:250px;width:420px;'><div style='float:left;height:inherit;width:95%;text-align:left;'><b>"+m+"</b></div><div style='float:left;width:5%;'></div></div></div></div></div></div></div></div></div></div>" : '<div class="post"><div class="ct"><div class="l"><div class="r"/></div></div><h3 class="title">Delete Graffiti</h3><p class="byline"/><div class="entry">'+m+'</div><div class="cb"><div class="l"><div class="r"/></div></div></div>';
	break;	
      case 'MobikuPopup':
	returnString = "<br><form id=frmMobiku method=post target=uploadResponseHandler><table style='width:205px;'><tr><td><b>Add haiku here:</b></td></tr><tr><td><input style='width:200px' type=text name=txtmobiku id=txtmobiku value='' /></td></tr><tr><td align=right><a href='Javascript:void(0)' onClick='AddMobiku()'><img src='"+IMAGE_URL_BASE+"button_add.png' /></a></td></tr></table>"+m+"</form><iframe id='uploadResponseHandler' name='uploadResponseHandler' style='height:0px; width:0px; display:none;'></iframe>";
	break;
  }

  return returnString;
}

function ShowErrorBox()
{
  if(errorboxheight==50)
  {
    clearInterval(interval);
    errorboxmargin=eval(parseInt(GetWindowHeight())-50);
    obj.style.marginTop = eval(parseInt(GetWindowHeight())-50)+'px';
    return;
  }

  obj = GetDOMElement("errorBox");
  errorboxheight=eval(parseInt(errorboxheight)+2);
  errorboxmargin=eval(errorboxmargin-2);
  if(obj)
  {
    obj.style.marginTop = errorboxmargin+'px';
    obj.style.display = 'block';
  }
}

//same way as above but reversed
function HideErrorBox(h)
{
  obj = GetDOMElement("errorBox");
  if(!(obj))
  {
    errorboxmargin=parseInt(GetWindowHeight());
    errorboxheight=0;
    clearInterval(interval);
    clearTimeout(ErrorMsgAutoCloseInterval);
    return null;
  }

  if(h)
    errorboxheight=2;

  if(errorboxheight==2)
  {
    obj.style.display = 'none';
    errorboxmargin=parseInt(GetWindowHeight());
    errorboxheight=0;
    clearInterval(interval);
    clearTimeout(ErrorMsgAutoCloseInterval);
    return;
  }
  errorboxheight=eval(parseInt(errorboxheight)-2);
  errorboxmargin=eval(parseInt(errorboxmargin)+2);
  obj.style.marginTop = errorboxmargin+ 'px';
}

function GetDistanceFromTop()
{
  disTop = typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;

  var  div = GetDOMElement('errorBox');
  if(div)
    return disTop;

  return null;
}

function GetWindowWidth()
{
  if( document.documentElement && ( document.documentElement.clientWidth) ) //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientWidth;
  else if( document.body && ( document.body.clientWidth) ) //IE 4 compatible
    return document.body.clientWidth;
  else if( typeof( window.innerWidth ) == 'number' ) 		//Non-IE
    return window.innerWidth;

  return 1024;
}

function GetWindowHeight()
{
  if( document.documentElement && (document.documentElement.clientHeight ) ) //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientHeight;
  else if( document.body && ( document.body.clientHeight ) ) //IE 4 compatible
    return document.body.clientHeight;
  else if( typeof( window.innerHeight ) == 'number' ) //Non-IE
    return window.innerHeight;

  return 900;
}

function AutoCloseErrorBox()
{
  ErrorMsgAutoCloseInterval = setTimeout("ShowError(' ')", ERROR_MESSAGE_DISPLAY_DURATION);
  return false;		
}

function OpenPopUp(note, delay)
{
  if (dtype == 'ym')
  {
    if (! ymessenger)
      return;

    ymessenger.toastShow(1, delay, note);
  }

  SetDOMElementValue('popupwindowtext', note);

  var f = GetDOMElement('popupwindow');
  if (f)
    f.style.visibility='visible';

  StartPopUpCloseTimer("popupwindow", delay);
}

function StartPopUpCloseTimer(ppwid, delay)
{
  // TODO: again, this has to be a global var - put in an array
  // This is hackery to deal with passing parameters into the
  // function set up with setTimeOut

  // TODO: it should be possible to display multiple popup
  // windows - stacked on each other
  einstein = new ClosePopUp();
  einstein.wid = ppwid;
  var t = setTimeout("einstein.ClosePUW()", 1000*delay);
}

function ClosePopUp()
{
  // Part of the hackery to deal with parameter passing
  this.wid = null;
  this.ClosePUW = function() {
    var e = GetDOMElement(this.wid);
    if (e)
      e.style.visibility='hidden';
  }
}

function GeoAlert(code, str)
{
  switch (code)
  {
      case 0:
	alert(str);
     	break;
      case 1:
     	//OpenPopUp(str, 5);
	ShowError(str);
     	break;
      case 2:
     	//OpenPopUp(str, 1);
	ShowError(str);
     	break;
      case 3:
  	ShowError(str);
  	break;
      case 4:
     	//OpenPopUp(str, 10);
	ShowError(str);
     	break;
      case 10:

	  case 11:
  	// Dont do anything - add appropriate display method
  	// when ready to display all such messages.
  	// TODO: patcher is in yimprimarywindow.php - not sure if it's used
      	var obj = GetDOMElement("patcher");
  	if (obj)
  	{
  	  obj.value = obj.value - 0 + 1;
  	}
  	break;
      default:

     	break;
  }
}

////////////////////////////////////////////////////////////////////////////////
//
//    Miscellaneous Utility Functions
//
////////////////////////////////////////////////////////////////////////////////
// Date validation functions courtesy of
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
// Checks for the following valid date format:
// YYYY-MM-DD HH:MM::SS
function ReturnValidDateTime(dtstr)
{
  var matchPat = /^(\d{4})(\/|-)(\d{1,2})\2(\d{1,2})(\ )(\d{1,2}):(\d{2}):(\d{2})$/;;
  var matchArray = dtstr.match(matchPat);
  if (matchArray == null)
    return null;

  var year = matchArray[1];
  var month = matchArray[3];
  var day = matchArray[4];
  var hour = matchArray[6];
  var minute = matchArray[7];
  var second = matchArray[8];

  if (month < 1 || month > 12)
    return null;

  if (day < 1 || day > 31)
    return null;

  if ((month==4 || month==6 || month==9 || month==11) && day==31)
    return null;

  if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap))
      return null;
  }

  if (second=="")
    second = null;

  if (hour < 0  || hour > 23)
    return null;

  if (minute < 0 || minute > 59)
    return null;

  if (second != null && (second < 0 || second > 59))
    return null;

  // XXXX: the Date constructor assumes that month goes from 0 to 11, not
  // from 1 to 12!!
  month--;
  return new Date(year, month, day, hour, minute, second);
}

function GMTDate()
{
  var tnow = new Date();
  var gmttime = new Date(tnow.getTime() + (tnow.getTimezoneOffset() * 60000));
  return gmttime;
}

function DiffFormatDate(od)
{
  if (!od)
    return null;

  d = new Date(od);
  var year = d.getFullYear();
  var month = eval(d.getMonth()+1);	//as return range 0 - 11
  var day = d.getDate();
  var hour = d.getHours();
  var mts = d.getMinutes();
  var sec = d.getSeconds();
  var dstr = month+" "+day+","+year+" "+hour+":"+mts+":"+sec+" GMT";
  dd = new Date(dstr);
//   alert ("Old date format: " + od + " New format: " + dd);
//  return dd;

  return d;
}

var i=0;
function DateDifference(dtold, dtnew)
{
  var d_old = DiffFormatDate(ReturnValidDateTime(dtold));
  var d_new = DiffFormatDate(dtnew);

  if (!d_old || !d_new)
    return null;

  // Absolute value of difference between 2 dates
  var diff  = new Date();
  diff.setTime(Math.abs(d_new.getTime() - d_old.getTime()));

  var timediff = diff.getTime();
  var weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
  timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

  var days = Math.floor(timediff / (1000 * 60 * 60 * 24));
  timediff -= days * (1000 * 60 * 60 * 24);

  var hours = Math.floor(timediff / (1000 * 60 * 60));
  timediff -= hours * (1000 * 60 * 60);

  var mins = Math.floor(timediff / (1000 * 60));
  timediff -= mins * (1000 * 60);

  var secs = Math.floor(timediff / 1000);
  timediff -= secs * 1000;

  var difference = (weeks > 0) ? weeks + " Weeks, " : "";
  difference += (days > 0) ? days + " Days, " : "";
  difference += (hours > 0) ? hours + " Hours, " : "";
  difference += (mins > 0) ? mins + " Minutes, " : "";
  difference += (secs > 0) ? secs + " Seconds " : "";
  difference += " Ago";
  //alert(difference);
  return difference;
}

function str_num_occurrences(base, str)
{
  if (base == "" || str == "" || base == null || str == null)
    return 0;

  var n = 0;
  var s = 0;
  while (s != -1)
  {
    s = base.indexOf(str, s+1);
    n++;
  }
  n--;

  return n;
}

function GetDOMElement(item_id)
{
  if (!item_id)
    return null;

  var elem = null;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById(item_id);
  else if( document.all ) // this is the way old msie versions work
    elem = document.all[item_id];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[item_id];

  return elem;
}

function GetDOMElementValue(item_id)
{
  var e = GetDOMElement(item_id);
  return (e) ? e.value : null;
}

function SetDOMElementValue(item_id, val)
{
  var e = GetDOMElement(item_id);
  if (e)
    e.value = val;
}

function SetDOMElementInnerHtml(item_id, val)
{
  var e = GetDOMElement(item_id);
  if (e)
  {
	if (item_id == "f1" || item_id == "f2" || item_id == "f4" || item_id == "f5")
	{
		//var re= /<\S[^><]*>/g;
		//return val.replace(re, "");
		e.innerHTML = val.replace(/<\S[^><]*>/g,"");
	}
	else
	e.innerHTML = val;
  }

  // Dismiss the timer that would have cleared the popup
  if(item_id=='mbox')
    clearTimeout(PopupDismissTimer);
}

function GetDOMElementInnerHtml(item_id)
{
  var e = GetDOMElement(item_id);
  return (e) ? e.innerHTML : null;
}

function HideAllElements(item_id, new_id)
{
  var e = GetDOMElement(item_id);
  while (e)
  {
    e.style.display = 'none';
    e.id = new_id;
    e = GetDOMElement(item_id);
  }
}

function ShowAllElements(item_id, new_id)
{
  var e = GetDOMElement(item_id);
  while (e)
  {
    e.style.display = 'block';
    e.id = new_id;
    e = GetDOMElement(item_id);
  }
}

function HideElement(item_id, set_to_blank)
{
  var value = (set_to_blank == null) ? 'none' : 'block';
  var e = GetDOMElement(item_id);
  if (! e)
    return null;

  e.style.display = value;
  return e;
}

function ShowElement(item_id, display)
{
  var e = GetDOMElement(item_id);
  if (! e)
    return null;

  var display = (display) ? display : 'block';
  e.style.display = display;
  return e;
}

function ToggleDisplay(item_id)
{
  var e = GetDOMElement(item_id);
  if (! e)
    return;

  var vis = e.style;

  // if the style.display value is blank we try to figure it out here
  if(vis.display == 'block' && e.offsetWidth != undefined && e.offsetHeight != undefined)
    vis.display = (e.offsetWidth != 0 && e.offsetHeight != 0) ? 'block' : 'none';

  vis.display = (vis.display == '' || vis.display == 'block') ? 'none' : 'block';
}

function CheckForInt(e, nospace, nopaste, ishint, isphone, object)
{
  var key = (window.event) ? event.keyCode : e.which;

  if(ishint)
  {
	  //if(key==38)//Up
	  if(key==40)//Down
	  {
		  var func = GetDOMElement('hintbox0').onmouseover();
	  }
	  return null;
  }
  
  if(nopaste)
  {
    if (window.event) //IE
      window.event.returnValue = null;
    else //Firefox
      e.preventDefault();
  }
  
  if(nospace)
  {
    if ( key != 32)
      return; // if so, do nothing
    else	// otherwise, discard character
    {
      if (window.event) //IE
        window.event.returnValue = null;
      else //Firefox
        e.preventDefault();
    }		
  }
  if(isphone)
  {
	  var fldlength = object.value.length;
	  if(fldlength==0)
	  {
		  if(key==107)
		  	return ;
	  }
  }
  // Was key that was pressed a numeric character (0-9) or backspace (8)?
  if ( key > 47 && key < 58 || key == 8 || key > 95 && key < 106 || key==37 || key==39)
    return; // if so, do nothing
  else		// otherwise, discard character
  {
    if (window.event) //IE
      window.event.returnValue = null;
    else //Firefox
      e.preventDefault();
  }		
}

function checkspecialcharofusername(tnt)
{
  var s = document.getElementById(tnt).value;
  var len = s.length;
  var strString = "";
  for(var i=0; i<len; i++)
  {
    
    
    if(s.charAt(i) != ' ' && s.charAt(i) != '~' && s.charAt(i) != '`' && s.charAt(i) != '!' && s.charAt(i) != '@' && s.charAt(i) != '#' && s.charAt(i) != '$' && s.charAt(i) != '%' && s.charAt(i) != '^' && s.charAt(i) != '&' && s.charAt(i) != '*' && s.charAt(i) != '(' && s.charAt(i) != ')' && s.charAt(i) != '+' && s.charAt(i) != '=' && s.charAt(i) != '}' && s.charAt(i) != '{' && s.charAt(i) != '[' && s.charAt(i) != ']' && s.charAt(i) != ']' && s.charAt(i) != ']' && s.charAt(i) != ']' && s.charAt(i) != ']' && s.charAt(i) != ']' && s.charAt(i) != ':' && s.charAt(i) != ';' && s.charAt(i) != '"' && s.charAt(i) != "'" && s.charAt(i) != "\\" && s.charAt(i) != '|' && s.charAt(i) != '/' && s.charAt(i) != '?' && s.charAt(i) != '>' && s.charAt(i) != '<' && s.charAt(i) != ',' )
    {
        HideElement('usernamespan');
      if((s.charAt(i-1) == s.charAt(i)) && s.charAt(i) == '-'){
	  ShowElement('usernamespan');break;}
      if((s.charAt(i-1) == s.charAt(i)) && s.charAt(i) == '_'){
	  ShowElement('usernamespan');break;}
      if((s.charAt(i-1) == s.charAt(i)) && s.charAt(i) == '.'){
	  ShowElement('usernamespan');break;}
      
      strString +=s.charAt(i); 
    }
  }
  document.getElementById(tnt).value = strString;
}

function LTrim(str) {
  var whitespace = new String(" \t\n\r ");
  var s = new String(str);
  if (whitespace.indexOf(s.charAt(0)) != -1) {
    var j = 0, i = s.length;
    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
      j++;
    s = s.substring(j, i);
  }
  return s;
}

function RTrim(str) {
  var whitespace = new String(" \t\n\r ");
  var s = new String(str);
  if (whitespace.indexOf(s.charAt(s.length - 1)) != -1) {
    var i = s.length - 1;
    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
      i--;
    s = s.substring(0, i + 1);
  }
  return s;
}

function Trim(str) {
  return RTrim(LTrim(str));
}

function GetJson(text)
{
  if (!text || text=="")
    return null;

  var json = null;
  text = text.replace(/<NoData\/>/g, "");
  text = text.replace(/'/g, "\'");
  text = text.replace(/\n/g, "");

  if(window.ActiveXObject){ //IE
    try{
      var JSONFile = eval("var json = "+text);
    }
    catch(e){
      //alert(e);
    }	
  }
  else { //Mozilla, Firefox, Opera 8.01, Safari
    try{
      json = eval("("+text+")");
    }
    catch(e){
      //alert(e);
    }
  }

  return json;
}

/////////////////////////////////////////////////////////////////////
function ValidateUserRegistration(registration)
{
  if (! document.getElementById)
    return false;

  var fname = GetDOMElementValue('fname');
  var lname = GetDOMElementValue('lname');
  var remail = GetDOMElementValue('remail');
  var rlogin = GetDOMElementValue('rlogin');
  var pw = GetDOMElementValue('passw');
  var cpw = GetDOMElementValue('confirm');
  var tos = (GetDOMElement('readtos')) ? GetDOMElement('readtos').checked : null;

  if (registration == true)
  {
    // This is a new user registration - check a bunch of stuff
    if (!fname || fname=="" || !lname || lname=="")
    {
      DisplayBoxError("Please enter your first and last name.");
      return false;
    }
    if (!remail || remail=="")
    {
      DisplayBoxError("Please enter a valid email address.");
      return false;
    }
    if ((COMPANY_NAME!="Mobiku") && (!rlogin || (rlogin.length < 4)))
    {
      DisplayBoxError("Login name must be at least 4 characters long.");
      return false;
    }
    if (pw == null || (pw.length < 8))
    {
      DisplayBoxError("Password must be at least 8 characters long.");
      return false;
    }
    if (cpw == null || cpw != pw)
    {
      DisplayBoxError("Passwords do not match.");
      return false;
    }
    if (!tos || tos == false)
    {
      DisplayBoxError("You must read and accept the Terms of Service and Privacy Policy.");
      return false;
    }
    DisplayBoxError("Submitting registration. Please wait.");
  }
  else
  {
    // Update profile
    if (!rname || rname=="")
    {
      DisplayBoxError("Please enter your name.");
      return false;
    }
    if (!remail || remail=="")
    {
      DisplayBoxError("Please enter a valid email address.");
      return false;
    }
    DisplayBoxError("Updating profile. Please wait.");
  }
  return true;
}

function EchoPublicProfile(elem, val)
{
  if (!elem || !val)
    return;

  SetDOMElementValue(elem, val);
}

function UpdatePassword(f, reg)
{
  if (! document.getElementById)
    return false;

  var pw = GetDOMElementValue('passw');
  var cpw = GetDOMElementValue('confirm');

  if (pw == null || (pw.length < 8))
  {
    DisplayBoxError("Password must be at least 8 characters long.");
    return false;
  }
  if (cpw == null || cpw != pw)
  {
    DisplayBoxError("Passwords do not match.");
    return false;
  }

  DisplayBoxError("Updating password. Please wait.");
  return true;
}

function DisplayRegistrationError(str)
{
  SetDOMElementValue('registrationerroroutput', str);
}

function ClearRegistrationError()
{
  DisplayRegistrationError("");
}

function SetTextFieldValue(field, value)
{
  if (!field)
    return false;

  SetDOMElementValue(field, value);
  return true;
}

function ClearTextFieldValue(field)
{
  return SetTextFieldValue(field, "");
}

function DisplayNoSearchResultsMessage(simple)
{
  if (simple)
  {
    HideElement('loading_gif');
    ShowElement('controls');
    ShowElement('Listing');	  
    return null;
  }
  
  HideProgressBar();
  if(SHOW_ONE_SEARCH_RESULT_ON_LEFT_CONTENT)
  {
    //SetDOMElementInnerHtml('mastersummary', '<div class="user_block not_selected" style="height:100px;font-size:20px;">No matching businesses. Try zooming out to search in a broader area.</div>');
    SetDOMElementInnerHtml('Listing', '<div class="user_block not_selected" style="height:100px;font-size:20px;">No matching businesses. Try zooming out to search in a broader area.</div>');
    HideElement('loading_gif');
    ShowElement('controls');
    ShowElement('Listing');
    return null;
  }
  DisplayBoxError("No business matches found. Try zooming out the map to search in a larger area.");	
  return null;
}

function DisplayBoxError(str)
{
  SetTextFieldValue('output_msg_box', str);
  ShowError(str);
}

function ClearErrorBox()
{
  DisplayBoxError(" ");
  HideErrorBox(1);
}

function CancelTagUpdate(hidembox)
{
  ClearGrayOverlay();
  ClearModalDialogBox(hidembox);
  try{
	  ShowElement('chart');
	  ShowElement('chart1');
  }
  catch(e){
  }  
}

var refrshInterval = null;
function SubmitPopupTemplateForm(rand, bizresultid, forupdatetag)
{
  var businessInfo = "";
  if(bizresultid>0 && bizresultid<=maxbizsearchresults)
  {
    bizresultid = parseInt(bizresultid)-1;
    var xmlDoc = CreateDomDocumentObject(business_search_html);
    if(xmlDoc.getElementsByTagName("Tag"))
    {
      var Node = (xmlDoc.getElementsByTagName("Tag")[bizresultid]);
      if (Node)
      {
	if(Node.getElementsByTagName("Name") && Node.getElementsByTagName("Name")[0])
	  businessInfo += "&bname="+(encodeURI(CleanBizContactInformation(Node.getElementsByTagName("Name")[0].textContent)));
	if(Node.getElementsByTagName("Address")[0])
	  businessInfo += "&baddress="+(encodeURI(CleanBizContactInformation(Node.getElementsByTagName("Address")[0].textContent)));
	if(Node.getElementsByTagName("Phone")[0])
	  businessInfo += "&bphone="+(encodeURI(CleanBizContactInformation(Node.getElementsByTagName("Phone")[0].textContent)));
	if(Node.getElementsByTagName("Coordinates")[0])
	  businessInfo += "&blatlon="+Node.getElementsByTagName("Coordinates")[0].textContent;
      }
    }
  }

  var tu_url = PrepareTagUpdateUrlString(1, forupdatetag);
  if(!tu_url)
    return false;

  document.frmPopUpGraffiti.action += tu_url;

  if (businessInfo != "")
    document.frmPopUpGraffiti.action += businessInfo;

  document.frmPopUpGraffiti.submit();

  var hidembox = 1;
  CancelTagUpdate(hidembox);

  DisplayBoxError('Sending update request...');
}

var Question = null;

function ValidateUploadGroupTagsForm(frmName)
{
  var tagFile = GetDOMElementValue("kmlFiles");
  tagFile = tagFile.split("\.")[1];
		
  if (tagFile == "kml" || tagFile == "KML" || tagFile == "gpx" || tagFile == "GPX")
  {
    if (tagFile == "kml" || tagFile == "KML")
    {
      document.forms[frmName].action = kml_parser_file_name;
    }
    else
    {
      document.forms[frmName].action = gpx_parser_file_name;
    }
    return true;
  }
  else
  {
    GeoAlert(0, "Invalid file type only *.kml or *.gpx files are alowed");
    return false;
  }
}
//
function SubmitCOSChange(rb, count)
{
  if (!rb || rb == "" || count <= 0)
    return;

  var newcosid=-1;
  for (var i=0; i<count; i++)
  {
    var but = GetDOMElement(rb+i);
    if (but && but.checked)
      newcosid = but.value;
  }

  if (newcosid >= 0)
    window.location=changecos_file+"?nc="+newcosid;
  else
    GeoAlert(0, "Please select the service level you want to change to.");
}
//

function ProcessCOSChange(cb, cp, np, nn, pf, cuf)
{
  if (!cb || cb == "")
    return;

  if (cp == np)
  {
    GeoAlert(0, "You have selected the same new membership level as your current membership level. Please try again.");
    window.location=manageaccount_file;
    return;
  }

  var box = GetDOMElement(cb);
  if (!box)
    return;

  if (! box.checked)
  {
    Geoalert(0, "You must accept the change in charges to proceed");
    return;
  }

  if (!pf)
  {
    GeoAlert(0, "Error processing payment. Please contact "+COMPANY_NAME+" customer support.");
    return;
  }

  if (cp > 0)
  {
    GeoAlert(0, "Since "+COMPANY_NAME+" processes subscriptions through Paypal we are unable to directly unsubscribe you from your current premimum membership level. Please cancel your previous membership level directly from your Paypal account or you will be billed by Paypal for both subscription levels. We apologize for this inconvenience. We are working on streamlining this.");
    if (np <= 0)
    {
      GeoAlert(0, "We will change your Membership level to Basic but you will continue to be billed for your old membership level unless you explicitly cancel your subscription from Paypal. We apologize for the inconvenience. We are working on streamlining this process.");

      // Change cos in our db.
      var cucf = GetDOMElement(cuf);
      var cucfs = GetDOMElement(cuf+"submit");
      if (cucfs) cucfs.value=1;
      if (cucf && cucfs) cucf.submit();
      return;
    }
  }

  GeoAlert(0, "We will now connect you to Paypal to process your new subscription level. ");
  var paypalform = GetDOMElement(pf);
  var pfn = GetDOMElement(pf+"item_name");
  var pfa3 = GetDOMElement(pf+"a3");
  if (!paypalform || !pfn || !pfa3 || !nn)
  {
    GeoAlert(0, "Error processing payment. Please contact "+COMPANY_NAME+" customer support.");
    return;
  }

  pfn.value = COMPANY_NAME+" " + nn + " Membership";
  pfa3.value = np;
  paypalform.submit();

  // Change cos in our db.
  var cucf = GetDOMElement(cuf);
  var cucfs = GetDOMElement(cuf+"submit");
  if (cucfs) cucfs.value=1;
  if (cucf && cucfs) cucf.submit();
}

function StartViewUserLocationTemporarilyTimer(acode)
{
  DisplayBoxError("Location will update automatically every 30 seconds until access expires.");
  var t = setTimeout("ViewUserLocationTemporarily('"+acode+"')", 30000);
}

function ValidateSendSupportEmail()
{
  var subname = GetDOMElement("subname");
  if (!subname || !subname.value || subname.value=="" || subname.value==" ")
  {
    alert("Please enter your name.");
    return false;
  }

  var subemail = GetDOMElement("subemail");
  if (!subemail || !subemail.value || subemail.value=="" || subemail.value==" ")
  {
    alert("Please enter your email address.");
    return false;
  }

  var subject = GetDOMElement("subject");
  var subbrowser = GetDOMElement("subbrowser");
  var subos = GetDOMElement("subos");

  var submsg = GetDOMElement("submsg");
  if (!submsg || !submsg.value || submsg.value=="" || submsg.value==" ")
  {
    alert("Please enter a message.");
    return false;
  }
  return true;
}

function DisplayAdArea(tllat, tllon, brlat, brlon, zf, clat, clon, data, adpin)
{
  if ((!tllat || !tllon || !brlat || !brlon) && (!clat || !clon))
    return false;

  var clat = (clat) ? clat : (tllat - brlat)/2 + brlat;
  var clon = (clon) ? clon : (tllon - brlon)/2 + brlon;
  var zf = (zf) ? zf : 4;
  var adpin = (adpin) ? adpin : false;
  var data = (data) ? data : 'Ad Location';

  SetMapCenterAndZoomLevel(clat, clon, zf, data, adpin);

  return true;
}

function AddNewLocationAd(nadid, clatid, clonid, tllatid, tllonid, brlatid, brlonid, zoomid)
{
  return SetMapDisplayedArea(clatid, clonid, tllatid, tllonid, brlatid, brlonid, zoomid);
}

function PostWallFaceBookQuestion(gid)
{
  if(!gid)
    return null;

  SetDOMElementValue("grp_id", gid);

  if(!main_map['lat'] && !main_map['lon'])
    ExtractMapViewFromCookie();
  if(main_map['lat'])
    SetDOMElementValue("lat", main_map['lat']);
  if(main_map['lon'])	
    SetDOMElementValue("lon", main_map['lon']);

  var existingwall = true;
  ShowWallCreationDialog(1, existingwall);
}

function RenameWall()
{
  SetDOMElementValue("submitcreategrp", 0);
  SetDOMElementValue("submitrenamegrp", 1);
  SetDOMElementValue("submitdeletegrp", 0);

  document.grpactionform.submit();
}
function DeleteWall()
{
  SetDOMElementValue("submitcreategrp", 0);
  SetDOMElementValue("submitrenamegrp", 0);
  SetDOMElementValue("submitdeletegrp", 1);

  document.grpactionform.submit();
}

function ShowUserLoginPopup(forReg)
{
  var ol = CreateGrayOverlay();
  var mbox = CreateModalDialogBox();

  if(GetDOMElement("returnUrl") &&
     GetDOMElementValue("returnUrl") != "" &&
     GetDOMElement("serviceId") &&
     GetDOMElementValue("serviceId") != "")
    var formfields = '?serviceId='+GetDOMElementValue("serviceId")+'&returnUrl='+GetDOMElementValue("returnUrl");

  if(GetDOMElement("deletedash"))
    var formfields = '?deletedash=1';

  if(!forReg)
  {
    var desc = '<div style="height:20px;width:250px;background-color:#DEEA9B;color:#336600;text-align:center;padding-top:3px;">Sign In To '+COMPANY_NAME+'</div><br/><br/><form style="height:115px;" name="frmMain" method="post" action="'+dash_file+'"><input type="hidden" name="current_page" value="'+dash_file+formfields+'" /><input type="hidden" name="SignIn" value="1" /><div><label for="login">Name</label><input id="login" name="login" type="text" value="" /></div><div><label for="password">Password</label><input id="password" name="password" type="password" value="" /></div><br/><div><a href="Javascript:void(0)"><img style="bottom:auto;" alt="" class="png sign_in" src="'+IMAGE_URL_BASE+'button_sign_in.png" onclick="SendUserLoginRequest('+forReg+');" /></a></div></form><br/><div><a href="Javascript:void(0)" onClick="ShowUserLoginPopup(1);">Sign Up</a></div>';
  }
  else
  {
    var desc = '<div style="height:20px;width:300px;background-color:#DEEA9B;color:#336600;text-align:center;padding-top:3px;">Sign Up On '+COMPANY_NAME+'</div><br/><br/><form style="height:200px;" name="frmMain" method="post" action="'+dash_file+'"><input type="hidden" name="current_page" value="'+dash_file+formfields+'" /><input type="hidden" name="SimpleSubmitRegistration" id="SimpleSubmitRegistration" value="1" /><div style="height:25px"><label for="rname">Full Name:</label><input id="rname" name="rname" onClick="ClearRegistrationError();" type="text" value="" /> *</div><div style="height:25px"><label for="remail">Email:</label><input id="remail" name="remail" onClick="ClearRegistrationError();" type="text" value="" /> *</div><div style="height:25px"><label for="rlogin">Login:</label><input id="rlogin" name="rlogin" onClick="ClearRegistrationError();" title="Minimum 4 chars" type="text" value="" /> *</div><div style="height:25px"><label for="passw">Password:</label><input id="passw" name="passw" onClick="ClearRegistrationError();" type="password" title="Minimum 8 chars" value="" /> *</div><div style="height:25px"><label for="confirm">Re-enter  Password:</label><input id="confirm" name="confirm" onClick="ClearRegistrationError();" type="password" value="" /> *</div><div style="height:25px"><input type="checkbox" id="readtos" style="width:auto;background:none; border-style:none;" /><span style="margin-left:7px;">I accept the <a href="docs/legal/us/tos.html">Terms of Service</a> and <a href="docs/legal/us/privacy.html">Privacy Policy</a></span></div><div style="height:auto;">* Mandatory fields</div><div><a href="Javascript:void(0)"><img style="bottom:auto;" alt="" class="png sign_in" width="97" height="37" src="'+IMAGE_URL_BASE+'button_sing_up.png" onclick="SendUserLoginRequest('+forReg+');" /></a></div></form><div><a href="Javascript:void(0)" onClick="ShowUserLoginPopup();">Sign In</a></div>';
  }

  var html = GetPopupHTML(desc, 'userloginreg');
  if(mbox)
    mbox.style.left = '350px';
  SetDOMElementInnerHtml('mbox', html);
}

function SendUserLoginRequest(forReg)
{
  if(!forReg)
  {
    var name = GetDOMElementValue('login');
    var pass = GetDOMElementValue('password');
    if(!name || !pass)
    {
      DisplayBoxError("Invalid User Name or Password.");
      return null;
    }
  }
  else
  {
    var name = GetDOMElementValue('rname');
    var email = GetDOMElementValue('remail');
    var login = GetDOMElementValue('rlogin');
    var passw = GetDOMElementValue('passw');
    var cpassw = GetDOMElementValue('confirm');
    var tos = GetDOMElement('readtos');

    if(!name || !email || !login || !passw || !cpassw || !(tos.checked))
    {
      DisplayBoxError("Please Fill All Mandatoey Fields First.");
      return null;
    }
  }
  if(document.frmMain)
    document.frmMain.submit();
}

function EmailGraffitiPopup(oid, gid)
{
  if(!oid)
    return null;

  var ol = CreateGrayOverlay();
  var mbox = CreateModalDialogBox();
  var desc = (main_map['type']!=MOBIKU_MAP) ? '<div style="height:20px;width:420px;background-color:#DEEA9B;color:#336600;text-align:center;padding-top:3px;">Email Graffiti To A Friend</div><br/><br/><table width="100%"><tr  style="height:28px;"><td style="font-weight:normal; color:#bed63a;">Email</td><td><input type="text" name="txtEmailTo" id="txtEmailTo" style="width: 250px;" value=""/></td></tr><tr style="height:28px;"><td style="font-weight:normal; color:#bed63a;">Subject</td><td><input type="text" name="txtTitle" style="width: 250px;" id="txtTitle" value="" /></td></tr><tr  style="height:28px;"><td style="font-weight:normal; color:#bed63a;">Message</td><td><textarea name="txtEmailMsg" cols="40" rows="2" style="background-color:#DEEA9B;" id="txtEmailMsg"></textarea></td></tr></table><input type="hidden" name="hdnOid" id="hdnOid" value="'+oid+'" /><br /><br /><div><a onclick="CancelTagUpdate();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_cancel.png"/></a><a onclick="EmailGraffiti();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_submit.png"/></a></div>' : '<br/><table width="100%"><tr  style="height:28px;"><td style="font-weight:normal;">Email</td><td><input type="text" name="txtEmailTo" id="txtEmailTo" style="width: 250px;" value=""/></td></tr><tr style="height:28px;"><td style="font-weight:normal;">Subject</td><td><input type="text" name="txtTitle" style="width: 250px;" id="txtTitle" value="" /></td></tr><tr  style="height:28px;"><td style="font-weight:normal;">Message</td><td><textarea name="txtEmailMsg" cols="40" rows="2" style="background-color:#DEEA9B;" id="txtEmailMsg"></textarea></td></tr></table><input type="hidden" name="hdnOid" id="hdnOid" value="'+oid+'" /><br /><br /><div><a onclick="CancelTagUpdate();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_cancel.png"/></a><a onclick="EmailGraffiti();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_submit.png"/></a></div>';
  if(gid)
    desc += '<input type="hidden" name="hdnGid" id="hdnGid" value="'+gid+'" />';
  var html = GetPopupHTML(desc, 'emailgraffiti');

  if(mbox)
    mbox.style.left = '350px';

  SetDOMElementInnerHtml('mbox', html);
}

function EmailGraffiti()
{
  var oid = GetDOMElement('hdnOid');
  if(!oid)
    return null;

  var gid = GetDOMElement('hdnGid');
  var bizid = GetDOMElementValue('hdnBizid');
  var graffitiid = GetDOMElementValue('hdnGraffitiid');
  var title = GetDOMElement('txtTitle');
  var emailto = GetDOMElement('txtEmailTo');
  var emailmsg = GetDOMElement('txtEmailMsg');

  if(!emailto || !oid || !title)
  {ShowError("Error Sending Email"); CancelTagUpdate(); return null;}

  if(Trim(GetDOMElementValue('txtEmailTo'))=="")
  {ShowError("Enter Recipient Email Address"); return null;}
  else if(Trim(GetDOMElementValue('txtTitle'))=="")
  {ShowError("Enter Email Subject"); return null;}
  else if(Trim(GetDOMElementValue('txtEmailMsg'))=="")
  {ShowError("Enter Some Message in Email"); return null;}

  var emails = emailto.value.split(",");
  for(i=0; i<emails.length; i++)
  {
    if(!(ValidateEmailAddress(null, emails[i])))	
      return null;
  }

  var gg_url = email_graffiti_url_base + "i="+uid+"&c="+upw+"&oid="+oid.value+"&title="+encodeURI(title.value)+"&emailto="+emailto.value;

  if (emailmsg && emailmsg.value)
    gg_url += "&emailmsg="+encodeURI(emailmsg.value);

  gg_url += (bizid) ? "&bizid="+bizid : "";
  gg_url += (graffitiid) ? "&graffitiid="+graffitiid : "";
  if(gid)
    gg_url += "&gid="+gid.value;

  var ggai = new AJAXInteraction(gg_url, ParseSendGraffitiLinkByEmail);
  ggai.Get();
  CancelTagUpdate();
}

function ParseSendGraffitiLinkByEmail(rstr)
{
  var msg = nth_xml_tag(rstr, "sent", 0);

  msg = (msg==1) ? "Email Successfully Sent" : (msg==0) ? "Error Sending Email" : msg;
  ShowError(msg);
}

function CreateGrayOverlyToDisableSocialUpdates()
{
  var ol = CreateGrayOverlay();
  if(!ol)
    return null;

  ol.style.width = '685px';
  ol.style.height = '270px';
  ol.style.position = 'absolute';
  ol.style.marginLeft = '161px';
  ol.style.marginTop = '410px';

  var mbox = CreateModalDialogBox();
  if (!mbox)
    return null;

  mbox.style.position = 'absolute';
  mbox.style.marginTop = '485px';
  mbox.style.left = '170px';
  var desc = '<br/>This feature is available once you install and run the <a href="'+downloadmobile_file+'">mobile application</a> on your cell phone.<br/>';
  var html = GetPopupHTML(desc, 'simplemboxbox');
  SetDOMElementInnerHtml('mbox', html);

  return true;
}

function UpdateTagsOfParentWindow(msg)
{
  var URL = null;
  try
  {
    URL = (window.parent.location.href);
  }
  catch(e)
  {
    return null;
  }
  var printmsg = (msg) ? msg : 'Updated Successfully!';
  if(URL && (URL.indexOf(viewgraffiti_file) > 0 || URL.indexOf(viewhaiku_file) > 0))
  {
    window.parent.DisplayBoxError(printmsg);
    window.parent.location = URL;
  }
  else
  {
    window.parent.DisplayBoxError(printmsg);
    window.parent.UpdateDisplayOfAllGroupTags(1);
  }
}

function ChangeRatingClass(indx, className)
{	
  if(IPHONE_LOOK_LIKE_STYLE)
  {
    SetDOMElementValue('tagRating', indx);
    for(var i=1; i<=5; i++)
    {
      var elem = GetDOMElement("star"+i);
      if(i<=indx)
      {elem.src = 'local/images/stars_large.gif';}
      else
      {elem.src = 'local/images/stars_large-02.gif';}
    }
  }
  else
  {
    if(className=='ratingstarselected')
    {
      var count = 0;	
      for(var i=1; i<=5; i++)
      {
	var elem = GetDOMElement("ratingstar"+i);
	if(!elem)
	  continue;
	if(i<=indx && !(indx==1 && elem.className=='ratingstarselected'))
	{elem.className = className; count++;}
	else
	{elem.className = 'ratingstar';}
      }
      SetDOMElementValue('ratingstar', count);
    }
    else
    {
      for(var i=1; i<=indx; i++)
      {
	var elem = GetDOMElement("ratingstar"+i);
	if(!elem || (elem.className=='ratingstarselected'))
	{continue;}
	elem.className = className;
      }
    }
  }
}

function RateGraffiti(graffitiid, rating)
{
  if(!graffitiid)
    return null;

  var ol = CreateGrayOverlay();
  var mbox = CreateModalDialogBox();
  var desc = '<div style="height:20px;width:420px;background-color:#DEEA9B;color:#336600;text-align:center;padding-top:3px;">Rate Graffiti</div><br/><br/><table width="100%"><tr  style="height:28px;"><td style="font-weight:normal; color:#bed63a;">Rate Graffiti?</td></tr></table><br /><br /><div><a onclick="CancelTagUpdate();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_no.png"/></a><a onclick="GetDOMElement(\'frmrategraffiti\').submit();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'buttobn_yes.png"/></a></div>';

  SetDOMElementValue('graffitiid', graffitiid);
  SetDOMElementValue('rating', rating);
  var html = GetPopupHTML(desc, 'emailgraffiti');

  if(mbox)
    mbox.style.left = '350px';

  SetDOMElementInnerHtml('mbox', html);
  if(mbox.getElementsByTagName('div')[8])
    mbox.getElementsByTagName('div')[8].style.height = '150px';
}

function AddMobiku()
{
  var value = GetDOMElementValue('txtmobiku');
  if(value=="")
  {
    ShowError('Please write something!');
    return null;
  }
  var lat = GetDOMElementValue('txtlat');
  var lon = GetDOMElementValue('txtlon');
  var form = GetDOMElement('frmMobiku');

  form.action = tag_update_url_base+"i="+uid+"&c="+upw+"&lat="+lat+"&lon="+lon+"&alt=0&txtmobiku="+encodeURI(value);
  form.submit();
}

function CallFunctionOnEnterPress(e, call)
{
  if (!e)
    return;

  var key = (window.event) ? event.keyCode : e.which;

  if ( key!=13)
    return;
  else
  {
    if (call)
      eval(call);
    if (window.event)
      window.event.returnValue = null;
    else
      e.preventDefault();
  }		
}

function DisplayLocalliteSelectedTagInformation(index, oid, description, lat, lon, isbiztag, name)
{
  RemoveInfoWindow();
  if(!isbiztag) 
  	DeleteAllMapShapes(main_map['map']);
  var point = NewLatLongPoint(lat, lon);
  SetMapCenter(main_map['map'], point);
  
  if(!isbiztag) AddLatLonPin(0, 0, point, null, null, 0, null, null, 1, null, name);
  if(isbiztag)
  {
    if(!(main_map['find_biz_layer'] && main_map['find_biz_layer'][index]))
    {
      var letteredIcon = CreateLetterIcon(index, "blue");
      AddLatLonPin(0, oid, point, '', letteredIcon, 0, null, index, null, 1, name);
    }
    var tag = main_map['find_biz_layer'][index];
	main_map['map'].removeOverlay(tag);
	main_map['map'].addOverlay(tag);
    var yellownumberedtag = IMAGE_URL_BASE+'marker/yellow-marker'+index+".png";

    curSelIcn = (tag) ? tag.getIcon() : null;
    curSelImg = (curSelIcn) ? curSelIcn.image : null;
    if(tag) {tag.setImage(yellownumberedtag);curSelTag = tag;}
  }
  GetMapView();
}

function ShowHideLocalliteSummary(getinfo, hidedetail, bizid, oid, graffitiid, alisid, adid, qryid, isreview, ispromotion, islivepage)
{
  if(GetDOMElement('mastersummary'))
  {
	if(isreview)
		GetDOMElement('reviewsummary').style.display = (hidedetail) ? 'none' : 'block';
	else
	    GetDOMElement('detailsummary').style.display = (hidedetail) ? 'none' : 'block';

    if(tab_elem && tab_elem=='tab1'){
      GetDOMElement('userown').style.display = (getinfo) ? 'none' : 'block';
      GetDOMElement('userfavorite').style.display = (getinfo) ? 'none' : 'block';		
      GetDOMElement('askquestion').style.display = (getinfo) ? 'none' : 'block';
      GetDOMElement('answeredquestion').style.display = (getinfo) ? 'none' : 'block';
      if(!getinfo)
	return null;		
    }
    else if(tab_elem && tab_elem=='tab2'){
    }
    else if(tab_elem && tab_elem=='tab3'){
      GetDOMElement('userown').style.display = (getinfo) ? 'none' : 'block';
      hidedetail = (hidedetail) ? 1 : 0;
      if(!getinfo)
	return null;
    }	
    else if(tab_elem && tab_elem=='tab5'){
      GetDOMElement('userfavorite').style.display = (getinfo) ? 'none' : 'block';
      hidedetail = (hidedetail) ? 1 : 0;
      if(!getinfo)
	return null;
    }
    else if(tab_elem && tab_elem=='tab6'){
      if(!getinfo)
	return null;		
    }
    else if(tab_elem && tab_elem=='tab11'){
      GetDOMElement('askquestion').style.display = (getinfo) ? 'none' : 'block';
      if(!getinfo)
	return null;
    }

    if(!hidedetail && qryid){
      HideElement('askquestion');
      //HideElement('answeredquestion');
      HideElement('askquestiondetail');
    }
    else if(hidedetail && qryid){
      //HideElement('answeredquestion');
      ShowElement('askquestiondetail');
      if(!getinfo)
	return null;		
    }
    GetDOMElement('mastersummary').style.display = (hidedetail) ? 'block' : 'none';
    if(hidedetail && GetDOMElement('Review') && isreview)
      ShowElement('Review');
    if(getinfo)
    {
	if(isreview){
		HideElement('detailsummary');
      SetDOMElementInnerHtml('reviewsummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
	}
	else{
		HideElement('reviewsummary');
	  SetDOMElementInnerHtml('detailsummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
	}
      url = MAIN_URL_BASE+'graffiti_dropdown.php?req=1';
      url += (graffitiid) ? "&graffitiid="+graffitiid : "";
      url += (oid) ? "&oid="+oid : "";
      url += (alisid) ? "&writeraliasid="+alisid : "";
      url += (bizid) ? "&bizid="+bizid : "";
      url += (adid) ? "&adid="+adid : "";
      url += (qryid) ? "&qryid="+qryid : "";
      url += (main_map['lat']) ? "&hdnlat="+main_map['lat'] : "";
      url += (main_map['lon']) ? "&hdnlon="+main_map['lon'] : "";
      url += (isreview) ? "&gmdid="+isreview : "";
      url += (ispromotion) ? "&ispromotion="+ispromotion : "";
	  url += (islivepage) ? "&islivepage="+islivepage : "";
	  url += "&sindex=0";

	  if(isreview)
		  var ggai = new AJAXInteraction(url, FillReviewSummaryWithResponseHtml);
	  else
		  var ggai = new AJAXInteraction(url, FillLocalliteSummaryWithResponseHtml);
      ggai.Get();
    }
  }
}

function FillLocalliteSummaryWithResponseHtml(response)
{
  if(response)
    SetDOMElementInnerHtml('detailsummary', response);
  else
    SetDOMElementInnerHtml('detailsummary', '');
}
function FillReviewSummaryWithResponseHtml(response)
{
  if(response)
    SetDOMElementInnerHtml('reviewsummary', response);
  else
    SetDOMElementInnerHtml('reviewsummary', '');
}

function LocalliteBusinessSearch(searchsort)
{ 
  search_sort_type = searchsort;
  if(GetDOMElement('biznametype') && GetDOMElement('startlocation'))
  {
    if(GetDOMElementValue('biznametype')!="" && GetDOMElementValue('startlocation')!="")
    {
      MapSearchedLocation();
      // XXXX: This interval will let the map center the to given point and
      // update its array of points
      //interval = setInterval('clearInterval(interval);OneSearch();', MAP_CENTER_AND_SEARCH_INTERVAL);
    }
    else if(GetDOMElementValue('biznametype')=="" && GetDOMElementValue('startlocation')!="")
    {
      MapSearchedLocation();
    }
    else if(GetDOMElementValue('biznametype')!="" && GetDOMElementValue('startlocation')=="")
    {
      OneSearch(null, searchsort);
    }
    else
    {
      ShowError('Please enter search keywords or location!');
    }
  }
  KMLLoader();
}

function DisplayLocalliteAskQuestionDetails(hidedetail, getinfo, answer, queryid, isanswer)
{
  if(isanswer)	 	
    GetDOMElement('answeredquestion').style.display = (hidedetail) ? 'none' : 'block';
  else
    GetDOMElement('askquestion').style.display = (hidedetail) ? 'none' : 'block';
  GetDOMElement('askquestiondetail').style.display = (hidedetail) ? 'block' : 'none';

  if(tab_elem && tab_elem=='tab1'){
    GetDOMElement('userown').style.display = (hidedetail) ? 'none' : 'block';
    GetDOMElement('userfavorite').style.display = (hidedetail) ? 'none' : 'block';
    GetDOMElement('askquestion').style.display = (hidedetail) ? 'none' : 'block';
    GetDOMElement('answeredquestion').style.display = (hidedetail) ? 'none' : 'block';
    GetDOMElement('mastersummary').style.display = (hidedetail) ? 'none' : 'block';
  }
//*/

  if(getinfo)
  {
    if(answer)
    {
      SetDOMElementInnerHtml('askquestiondetail', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:30px; margin-bottom:30px; margin-left:100px;"></div>');
      url = MAIN_URL_BASE+'question_dropdown.php?req=1&answer=1';
      url += (queryid && GetDOMElement(queryid)) ? "&query="+GetDOMElementValue(queryid) : "";
      var ggai = new AJAXInteraction(url, FillLocalliteQuestionDetailHtml);
      ggai.Get();
    }
    else
    {
      SetDOMElementInnerHtml('askquestiondetail', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:30px; margin-bottom:30px; margin-left:100px;"></div>');
      url = MAIN_URL_BASE+'question_dropdown.php?req=1';
      url += (queryid && GetDOMElement(queryid)) ? "&query="+GetDOMElementValue(queryid) : "";
      url += (queryid && GetDOMElement("sender"+queryid)) ? "&sender="+GetDOMElementValue("sender"+queryid) : "";
      url += (queryid && GetDOMElement("senderpic"+queryid)) ? "&senderpic="+GetDOMElementValue("senderpic"+queryid) : "";
      url += (queryid && GetDOMElement("senttime"+queryid)) ? "&senttime="+GetDOMElementValue("senttime"+queryid) : "";
      url += (queryid) ? "&queryid="+queryid : "";
      url += (isanswer) ? "&isanswer=1" : "&isanswer=0";

      var ggai = new AJAXInteraction(url, FillLocalliteQuestionDetailHtml);
      ggai.Get();
    }
  }
}

function FillLocalliteQuestionDetailHtml(response)
{
  if(response)
    SetDOMElementInnerHtml('askquestiondetail', response);
  else
    SetDOMElementInnerHtml('askquestiondetail', '');
}

function StartLocalliteTimeBasedLeftContentUpdateProc(destination, startproc)
{
  if(destination)
  {
    if(startproc)
    {
      var url = simple_request_url_base+''+destination;
      url += "&i="+uid+"&c="+upw+ "&dtype="+dtype;
      var ggai = new AJAXInteraction(url, FillLocalliteLeftContentHtml);
      ggai.Get();
    }
    else
    {
      // Update left-side content after 2 minutes (default)
      interval = setInterval('StartLocalliteTimeBasedLeftContentUpdateProc("'+destination+'", 1)', LOCALLITE_CONTENT_UPDATE_INTERVAL);
      /////////////////////////////////////////////////////////////////////////////////////////
    }
  }

  locallite_index=1;
}

function FillLocalliteLeftContentHtml(response)
{
  SetDOMElementInnerHtml('mastersummary', response);
  if(GetDOMElement('script')){
    var text = '{"result":['+GetDOMElementValue('script')+']}';
    locallite_json = GetJson(text);
  }
  if(GetDOMElement('eval'))
    eval(GetDOMElementInnerHtml('eval'));
}

function CharCountDown(item_id, respond_id, allowed_length, e)
{
 var text = GetDOMElementValue(item_id); 
 var textlength = parseInt(text.length);
 if(textlength > allowed_length)
 {
  SetDOMElementInnerHtml(respond_id, 'You cannot write more then '+allowed_length+' character(s).');
  SetDOMElementValue(item_id, text.substr(0,allowed_length)); 
  return false;
 }
 else
 {
   SetDOMElementInnerHtml(respond_id, ' '+ (allowed_length - textlength) +' Character(s) Remaining.');
   return true;
 }
}

function SubmitLocalliteCreateAd()
{
  SetDOMElementValue("tllat", GetLatitudeFromPoint(main_map['topleft']));
  SetDOMElementValue("tllon", GetLongitudeFromPoint(main_map['topleft']));
  SetDOMElementValue("brlat", GetLatitudeFromPoint(main_map['bottomright']));
  SetDOMElementValue("brlon", GetLongitudeFromPoint(main_map['bottomright']));
  SetDOMElementValue("lat", main_map['lat']);
  SetDOMElementValue("lon", main_map['lon']);

  if(GetDOMElementValue("hdnnew")==1)
  {
    if(Trim(GetDOMElementValue("adtext"))=="")
    {ShowError("Please enter some ad text!"); return null;}
    if(Trim(GetDOMElementValue("adkeywords"))=="")
    {ShowError("Please enter ad keywords!"); return null;}
  }
  document.mainForm.submit();
}

function SubmitLocalliteAskQuestion()
{
  SetDOMElementValue("clat", main_map['lat']);
  SetDOMElementValue("clon", main_map['lon']);	
  SetDOMElementValue("zoom", main_map['zoom']);	
  if(GetDOMElement("txtquestion")){
    if(Trim(GetDOMElementValue("txtquestion"))=='')
    {ShowError("Enter Valid Question Text To Post!"); return null;}
  }
  if(GetDOMElement("reviewtext")){
    if(Trim(GetDOMElementValue("reviewtext"))=='')
    {ShowError("Enter Answer Text To Post!"); return null;}
  }
  document.mainForm.submit();
}

function OpenJQDialog(desc, show_error_time_interval)
{
  InitializeJQDialog();
  $('#dialog').text(desc);
  $('#dialog').dialog('open');
  if(show_error_time_interval)
    var time_interval = show_error_time_interval;
  else
    var time_interval = ERROR_MESSAGE_DISPLAY_DURATION;
  setTimeout("CloseJQDialog()", time_interval);
}
	
function CloseJQDialog()
{
  $('#dialog').dialog('close');
}

function InitializeJQDialog()
{
  // Dialog			
  $('#dialog').dialog({
    autoOpen: false,
	width: 300,
	buttons: {
	"Close": function() {
	  $(this).dialog("close");
	}
      }
    });
}

function GetDirections(mc, fromAddress, toAddress)
{
  var map = new GMap2(mc);
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  HideWhiteTextOnMap();
  gdir = new GDirections(map, GetDOMElement('directions'));
  GEvent.addListener(gdir, "load", onGDirectionsLoad);
  GEvent.addListener(gdir, "error", handleErrors);
  setDirections(fromAddress, toAddress, "en_US");
}

function setDirections(fromAddress, toAddress, locale)
{
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

function HideWhiteTextOnMap()
{
  var smc = GetDOMElement("smc");
  if(smc && smc.previousSibling)
  {
	var obj = smc.previousSibling;
	obj.style.display = 'none';
	obj.innerHTML = '';
  }	
}

function onGDirectionsLoad()
{
}

function handleErrors()
{
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    ShowError("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    ShowError("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);	
  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    ShowError("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);	
  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    ShowError("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    ShowError("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
  else 
  	ShowError("Get directions request could not be successfully processed.");
}

function MyPageTabs(no)
{
  if(no==2){
    HideElement('askquestion');
    ShowElement('mastersummary');
    HideElement('askquestiondetail');
    HideElement('answeredquestion');
    HideElement('detailsummary');
    HideElement('userown');
    HideElement('userfavorite');	
  }
  else if(no==3){
    HideElement('mastersummary');
    HideElement('askquestion');
    HideElement('answeredquestion');
    HideElement('detailsummary');
    ShowElement('userown');
    HideElement('userfavorite');
    HideElement('askquestiondetail');
  }
  else if(no==4){
    HideElement('mastersummary');
    ShowElement('askquestion');
    HideElement('detailsummary');
    HideElement('answeredquestion');
    HideElement('askquestiondetail');
    HideElement('userown');
    HideElement('userfavorite');
  }
  else if(no==5){
    HideElement('mastersummary');
    HideElement('askquestion');
    HideElement('answeredquestion');
    HideElement('detailsummary');
    ShowElement('userfavorite');
    HideElement('userown');
    HideElement('askquestiondetail');
  }
  else if(no==6){
    ShowElement('answeredquestion');
    HideElement('mastersummary');
    HideElement('askquestion');
    HideElement('detailsummary');
    HideElement('userfavorite');
    HideElement('userown');
    HideElement('askquestiondetail');
  }
  else if(no==7){
    HideElement('lists');
    ShowElement('secondryControls');
    ShowElement('mastersummary');
    HideElement('detailsummary');
    GetDOMElement('maintab2').style.fontWeight='normal';
    GetDOMElement('maintab1').style.fontWeight='bold';
    GetDOMElement('maintab1').style.color='#FFFFFF';
    GetDOMElement('maintab2').style.color='DarkGray';
    return null;
  }
  else if(no==8){
    ShowElement('lists');
    HideElement('secondryControls');
    HideElement('mastersummary');
    HideElement('detailsummary');

    HideElement('askquestion');
    HideElement('askquestiondetail');
    HideElement('answeredquestion');
    HideElement('userfavorite');
    HideElement('userown');

    GetDOMElement('maintab2').style.fontWeight='bold';
    GetDOMElement('maintab1').style.fontWeight='normal';
    GetDOMElement('maintab2').style.color='#FFFFFF';
    GetDOMElement('maintab1').style.color='DarkGray';
    return null;
  }
  else{

	ShowElement('mastersummary');
    
    //if(GetDOMElementValue('htab3')>0)
      ShowElement('userown');
    //if(GetDOMElementValue('htab4')>0)
      ShowElement('askquestion');
    //if(GetDOMElementValue('htab5')>0)
      ShowElement('userfavorite');
    //if(GetDOMElementValue('htab6')>0)
      ShowElement('answeredquestion');
  }
  
  ShowElement('controls');

  GetDOMElement(tab_elem).style.fontWeight = 'normal';
  GetDOMElement(tab_elem).style.color='DarkGray';
  GetDOMElement('tab'+no).style.color='#FFFFFF';
  GetDOMElement('tab'+no).style.fontWeight = 'bold';

  tab_elem = 'tab'+no;
}

function LivePageTabs(no)
{
  if(no==1){
    ShowElement('mastersummary');
    HideElement('askquestiondetail');
    HideElement('askquestion');
    HideElement('detailsummary');
	HideElement('rssfeed');
    GetDOMElement('tab1').style.color='#FFFFFF';
    GetDOMElement('tab2').style.color='DarkGray';
    GetDOMElement('tab1').style.fontWeight = 'bold';
    GetDOMElement('tab2').style.fontWeight = 'normal';
	GetDOMElement('tab3').style.fontWeight = 'normal';
    GetDOMElement('tab3').style.color='DarkGray';
    tab_elem = 'tab12';
  }
  else if(no==2){
    HideElement('mastersummary');
    ShowElement('askquestion');
    HideElement('detailsummary');
	HideElement('rssfeed');
	
    GetDOMElement('tab1').style.color='DarkGray';
    GetDOMElement('tab2').style.color='#FFFFFF';
    GetDOMElement('tab1').style.fontWeight = 'normal';		
    GetDOMElement('tab2').style.fontWeight = 'bold';
	GetDOMElement('tab3').style.fontWeight = 'normal';
    GetDOMElement('tab3').style.color='DarkGray';
	tab_elem = 'tab11';
  }
  else if(no==3){
    HideElement('mastersummary');
    HideElement('askquestiondetail');
    HideElement('askquestion');
    HideElement('detailsummary');
	ShowElement('rssfeed');
    GetDOMElement('tab1').style.color='DarkGray';
    GetDOMElement('tab2').style.color='DarkGray';
    GetDOMElement('tab1').style.fontWeight = 'normal';		
    GetDOMElement('tab2').style.fontWeight = 'normal';		
	GetDOMElement('tab3').style.fontWeight = 'bold';
    GetDOMElement('tab3').style.color='#FFFFFF';
  }
}

function SearchPageTabs(no)
{
  if(no==1){
    ShowElement('Listing');
    HideElement('User');
    HideElement('Review');
    
    GetDOMElement('tab1').style.color='#FFFFFF';
    GetDOMElement('tab1').style.fontWeight = 'bold';
    if(GetDOMElement('tab2')){
      GetDOMElement('tab2').style.color='DarkGray';
      GetDOMElement('tab2').style.fontWeight = 'normal';
    }
    if(GetDOMElement('tab3')){
      GetDOMElement('tab3').style.color='DarkGray';
      GetDOMElement('tab3').style.fontWeight = 'normal';
    }
  }
  else if(no==2){
    ShowElement('User');
    HideElement('Listing');
    HideElement('Review');
    
    GetDOMElement('tab2').style.color='#FFFFFF';
    GetDOMElement('tab2').style.fontWeight = 'bold';
    if(GetDOMElement('tab1')){
      GetDOMElement('tab1').style.color='DarkGray';
      GetDOMElement('tab1').style.fontWeight = 'normal';
    }
    if(GetDOMElement('tab3')){
      GetDOMElement('tab3').style.color='DarkGray';
      GetDOMElement('tab3').style.fontWeight = 'normal';
    }
  }
  else if(no==3){
    ShowElement('Review');
    HideElement('Listing');
    HideElement('User');
    
    GetDOMElement('tab3').style.color='#FFFFFF';
    GetDOMElement('tab3').style.fontWeight = 'bold';
    if(GetDOMElement('tab1')){
      GetDOMElement('tab1').style.color='DarkGray';
      GetDOMElement('tab1').style.fontWeight = 'normal';
    }
    if(GetDOMElement('tab2')){
      GetDOMElement('tab2').style.color='DarkGray';
      GetDOMElement('tab2').style.fontWeight = 'normal';
    }
  }
}

function Fill_Locallite_Left_Content_Page(pos)
{
  if(!locallite_index)
    locallite_index = 1;

  var i = eval(locallite_index*10);

  if(pos && locallite_index<parseInt(locallite_json.result.length)){
    locallite_index = eval(locallite_index+1);
  }
  else if(!pos && locallite_index>0){
    locallite_index = eval(locallite_index-1);
    i = eval((locallite_index-1)*10);
  }
  if(!locallite_json || locallite_index==0 || locallite_index>eval(Math.ceil(parseInt(locallite_json.result.length)/10))){
    ShowError('No more records to display!');
    if(locallite_index>eval(Math.ceil(parseInt(locallite_json.result.length)/10)))
      locallite_index = eval(locallite_index-1);
    return null;
  }
  SetDOMElementInnerHtml('mastersummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
  var fillhtml = '';
  var x = 0;
  for(; i<eval(locallite_index*10); i++)
  {
    var JsonObject = locallite_json.result[i];
    if(!JsonObject)
      continue;
    fillhtml += '<div onclick="ChangeLocalliteInActiveDivClass(this, '+JsonObject.bizid+', null, '+JsonObject.oid+', 6);DisplayLocalliteSelectedTagInformation('+x+', null, \'\', \''+JsonObject.lat+'\', \''+JsonObject.lon+'\', 1, \''+JsonObject.name+'\');" class="user_block not_selected" id="wallObject'+i+'">';
    
    var categoryimg = (JsonObject.categoryimgurl!='') ? 'local/images/category/'+JsonObject.categoryimgurl : 'local/images/category/default.png';
    
    var stars = '';
    var rating = (JsonObject.rating) ? JsonObject.rating : 0;
    for(var s=1; s<=5; s++)
      stars += (s<=rating) ? '<img src="local/images/stars_small.png">' : '<img src="local/images/stars_small-02.png">';

    fillhtml += '<div><div id="user_stars" style="float:right;"><div id="stars">'+stars+'</div>';
    fillhtml += '<div id="more"><img height="21" width="13" alt="" src="local/images/user_arrow.png" title="Click to see description"/></div></div>';
    fillhtml += '<div id="user_thumb" style="margin-top:2px;"><img height="54" width="57" alt="" src="'+categoryimg+'" title="Business Category"/></div>';
    var userimg = (JsonObject.writerimgurl!='') ? JsonObject.writerimgurl : 'local/images/user_pic.gif';
    fillhtml += '<div id="user_pic" style="margin-top:2px;"><img height="51" width="51" alt="" src="'+userimg+'" title="User Image"/></div>';
    fillhtml += '<div id="user_description" style="width:68%; position:relative; overflow-x:none; border:0px solid #FF0000;"><div style="width:223px;">'+JsonObject.writeralias+'&nbsp;-&nbsp;'+JsonObject.timeupdated;
    fillhtml += '</div>';
	var lenJsonWriterandTim = parseInt(JsonObject.writeralias.length) + parseInt(JsonObject.timeupdated.length);
	if(lenJsonWriterandTim < 35)
	  var titwidth = '223px';	
	else
	  var titwidth = 'auto';	
		//fillhtml += '<br/>';
	fillhtml += '<div style="width:'+titwidth+'"><strong>'+JsonObject.name+'&nbsp;</strong></div>';
    fillhtml += '<div style="width:auto;position:absolute;"><span>'+JsonObject.address+'&nbsp;</span></div></div></div>';
    fillhtml += '<div id="icons" style="padding-top:20px;"><div id="icons_right">';

	var img1 = 'user_icons.png';
	var img2 = 'user_icons-02.png';
	var img3 = 'user_icons-03.png';		
	var commentscount = parseInt(JsonObject.comments);
	if(commentscount>0)
		img1 = 'user_icons_active.png';
	var voicenotescount = parseInt(JsonObject.voicenotes);
	if(voicenotescount>0)
		img2 = 'user_icons-02_active.png';
	var picscount = parseInt(JsonObject.pics);
	if(picscount>0)
		img3 = 'user_icons-03_active.png';
    fillhtml += '<ul><li><img height="25" width="25" align="absmiddle" alt="" title="Reviews" src="local/images/'+img1+'"/>'+JsonObject.comments+'</li>';
    fillhtml += '<li><img height="26" width="30" align="absmiddle" title="Voice Notes" alt="" src="local/images/'+img2+'"/> '+JsonObject.voicenotes+'</li>';
    fillhtml += '<li><img height="21" width="27" align="absmiddle" title="Images" alt="" src="local/images/'+img3+'"/> '+JsonObject.pics+'</li>';
    fillhtml += '<li style="text-align: right; width: 100px;" title="Distance">&nbsp;</li></ul></div>';
    var FavoriteFollow = '';
    if(JsonObject.favorite==1)
      FavoriteFollow += '<img src="local/images/user_icos_colored.png" title="User Favorite" width="21" height="19" alt="" />';
    else
      FavoriteFollow += '<img src="local/images/user_icons-04.png" title="Not User Favorite" width="20" height="19" alt="" />';
    if(JsonObject.followee==1)
      FavoriteFollow += '<img src="local/images/user_icos_colored-02.png" title="User Followee" width="21" height="19" alt="" />';
    else
      FavoriteFollow += '<img src="local/images/user_icons-05.png" title="Not User Followee" width="21" height="19" alt="" />';
    fillhtml += '<div id="icons_left">'+FavoriteFollow+'</div></div>';
    if((JsonObject.bizad) && (JsonObject.bizad)!='')
      fillhtml += '<div class="marquee"><marquee title="Business Ad" behavior="scroll" direction="left" scrollamount="2"><font color="#ff0066"><b>'+ JsonObject.bizad +'</b></font></marquee></div></div>';
    fillhtml += '</div>';
    x++;
  }
  fillhtml += '<div id="NextPrevDiv" style="background:#FFFFFF url(local/images/user_bg.gif) repeat-y scroll right center; width:365px; margin-left:3px; height:60px; margin-top:3px; padding-left:110px; padding-top:15px;"><span style="cursor:pointer;" id="PreviousSpan"><img src="local/images/previous_n.png" title="Previous" onclick="Fill_Locallite_Left_Content_Page(0)" /></span><span style="cursor:pointer; padding-left:180px" id="NextSpan"><img src="local/images/next_n.png" title="Next" onclick="Fill_Locallite_Left_Content_Page(1)" /></span><br /></div>';
  SetDOMElementInnerHtml('mastersummary', fillhtml);
  
  GetDOMElement('content_left').scrollTop = parseInt(1);
  GetDOMElement('mastersummary').scrollTop = parseInt(1);

  if(locallite_index==1)
  {	HideElement("PreviousSpan"); }
  else
  {	ShowElement("PreviousSpan", "inline"); }
  if(locallite_index==eval(Math.ceil(parseInt(locallite_json.result.length)/10)))
  {	HideElement("NextSpan"); }
  else
  {	ShowElement("NextSpan", "inline"); }
	
}

function DisplayLocalliteMyBusinessDetails(adid)
{
  HideElement('mastersummary');
  HideElement('askquestion');
  ShowElement('detailsummary');
  SetDOMElementInnerHtml('detailsummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
  url = MAIN_URL_BASE+'ad_dropdown.php?req=1';
  url += (adid) ? "&adid="+adid : "";
  url += (main_map['lat']) ? "&hdnlat="+main_map['lat'] : "";
  url += (main_map['lon']) ? "&hdnlon="+main_map['lon'] : "";
  
  var ggai = new AJAXInteraction(url, FillLocalliteSummaryWithResponseHtml);
  ggai.Get();		
}

function DisplayLocalliteMyWallDetails(id)
{
  HideElement('lists');
  ShowElement('detailsummary');
  SetDOMElementInnerHtml('detailsummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
  url = MAIN_URL_BASE+'wall_dropdown.php?req=1';
  url += (id) ? "&id="+id : "";
  
  var ggai = new AJAXInteraction(url, FillLocalliteSummaryWithResponseHtml);
  ggai.Get();		
}

function GetWallInfo(gid, domainid)
{
  var d = GetDistanceFromTop();	
  GetDOMElement('rcol').style.paddingTop = parseInt(d/3)+'px';
  SetDOMElementInnerHtml('detaildiv', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:50px; margin-left:60px;"></div>');
  url = simple_request_url_base+'getgroupdescription&req=1';
  url += "&i=" + uid + "&c=" + upw+"&dtype="+dtype;
  url += (gid) ? "&gid="+gid : "";
  url += (domainid) ? "&domainid="+domainid : "";

  var ggai = new AJAXInteraction(url, FillRCOLResponseHtml);
  ggai.Get();
}

function FillRCOLResponseHtml(rstr)
{
  SetDOMElementInnerHtml('detaildiv', rstr);
}

function LogOutUser(onwinclose)
{
  if(!onwinclose)
	  if (DO_PERIODIC_LOGOUT <= 0)
		return;
  
  url = MAIN_URL_BASE + 'logoutuser.php';//simple_request_url_base+'logout&req=1';
  var ggai = new AJAXInteraction(url);
  ggai.Get();	
}

function GetUserInfo(userid, domainid)
{
  var d = GetDistanceFromTop();	
  GetDOMElement('rcol').style.paddingTop = parseInt(d/3)+'px';
  SetDOMElementInnerHtml('detaildiv', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:50px; margin-left:60px;"></div>');
  url = simple_request_url_base+'getuserinformation&req=1';
  url += "&i=" + uid + "&c=" + upw+"&dtype="+dtype+"&userid="+userid+"&domainid="+domainid+"&rand="+Math.random();
  
  var ggai = new AJAXInteraction(url, FillRCOLResponseHtml);
  ggai.Get();
}

function GetSearchConfigData(entryid, domainid, searchsort)
{
  var d = GetDistanceFromTop();	
  GetDOMElement('rcol').style.paddingTop = parseInt(d/3)+'px';
  SetDOMElementInnerHtml('detaildiv', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:50px; margin-left:60px;"></div>');
  url = simple_request_url_base+'getsearchconfigdata&req=1&dtype='+dtype;
  url += (entryid) ? "&entryid="+entryid : "";
  url += (domainid) ? "&domainid="+domainid : "";
  url += (searchsort) ? "&searchsort="+searchsort : "";
  
  var ggai = new AJAXInteraction(url, FillRCOLResponseHtml);
  ggai.Get();
}

function SubmitChangePasswordForm()
{
  var cpassw = Trim(GetDOMElementValue('cpassw'));
  var passw = Trim(GetDOMElementValue('passw'));
  var confirmpassw = Trim(GetDOMElementValue('confirm'));
  if(cpassw=='' || passw=='' || confirmpassw==''){
    ShowError("Fill All Fields Without Spaces!");
  }
  else{
    if(String(passw) != String(confirmpassw)){
      ShowError("Password and Confirm password does not match!'"+passw+"' != '"+confirmpassw+"'");
    }
    else{
      document.mainForm.submit();
    }
  }
}

function ValidateImageUpload(obj, type)
{
  if(!obj)
    return null;
  
  type = (type)?type:"image";
  
  var fileName=/[\\/][0-9a-z._-]+$/i;
    
  var sContVal = obj.value;
   
  if (sContVal.length != 0)
  {    
    var res="no";
       
    var gfile=sContVal.toLowerCase();
    var str= new String();
    str= gfile;
       
    var finddot=str.lastIndexOf('.',str.length);
    var contain=new String();
    var contain=str.substring(finddot+1,str.length);
       
    var findslash=str.lastIndexOf('\\',str.length); // checks the occurance of '.' in photoname [creates problem in uplaoding]
    var contain2=new String();
    var contain2=str.substring(findslash+1,finddot);
       
    var sSpace = sContVal.indexOf(' ')
      var str=new String();
    str=contain2;
    var span=new RegExp("[#]","g");
    var rep=str.replace(span,"~");
       
       
    var spans1=new RegExp("[.]","g");
    var rep=rep.replace(spans1,"~");
           
                   
    var chkindex = rep.indexOf('~')
                           
      if(type == 'image'){
	var arr=new Array('jpeg','jpg','gif','png','pjpeg','pjpg'); //add file extensions here
      }
      else if(type == 'audio'){
	var arr=new Array('mp3','mov','wav','caf','wma'); //add file extensions here
      }
      else if(type == 'video'){
	var arr=new Array('flv','mp4','3gp','avi'); //add file extensions here
      }
    var msgString = "";
    for(i=0;i<=arr.length-1;i++)
    {
      if(arr[i]==contain)
	var res="yes";
      msgString += "."+arr[i]+", ";	
    }
           
       
    if(res != "yes" || (sContVal=="") || (chkindex != -1) )
    {
      ShowError("Your " + type + " must have one of the following file extension types: " + msgString + " Please try again.");
      obj.value = '';
      subvalue = false;
    }
    else
    {
      subvalue = true;
    }
  }
  if (subvalue==true)
  {
    return true;
  }
  else {
    return false;
  }
}

function SignInFormSubmit()
{
  var login = Trim(GetDOMElementValue("userlogin"));
  var password = Trim(GetDOMElementValue("userpassword"));
  if(login=='' || password=='')
  {
    ShowError("Enter USERNAME/PASSWORD to login!");
    return null;
  }
  else
  {
    //document.loginform.submit();
    var url = simple_request_url_base+"login&l=" + login + "&c=" + password +"&dtype="+dtype+"&ismd5=0";
    var ggai = new AJAXInteraction(url, SignInFormSubmitResponse);
    ggai.Post();
  }
}

function SignInFormSubmitResponse(response)
{
  var resArr = response.split(";");
  if(parseInt(resArr[0])>0)
    window.parent.location = resArr[2];
  else
    window.parent.ShowError(resArr[1]);
}

function GetMyBusinessList()
{
  var url = simple_request_url_base+"getmybusiness&i=" + uid + "&c=" + upw ;
  var ggai = new AJAXInteraction(url, SetMyBusinessList);
  ggai.Post();
}

function SetMyBusinessList(response)
{
  SetDOMElementInnerHtml('mastersummary', '');
  ShowElement('mastersummary');
  SetDOMElementInnerHtml('mastersummary', response);
}

function ValidateEmailAddress(elem_id, address)
{

  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  var address = (address) ? address : GetDOMElementValue(elem_id);
  if(reg.test(address) == false) {
    ShowError('Enter Valid Email Address Like john@gmail.com ');
    return false;
  }
  return true;
}
//
function checkCapsLock( e, id, obj, zindex )
{
  var myKeyCode=0;
  var myMsg = "CAPS LOCK";
  // Internet Explorer 4+
  if ( document.all ) {
    myKeyCode=e.keyCode;
    // Netscape 4
  } else if ( document.layers ) {
    myKeyCode=e.which;
    // Netscape 6
  } else if ( document.getElementById ) {
    myKeyCode=e.which;
  }

  // Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
  if ( ( myKeyCode >= 65 && myKeyCode <= 90 )) {
    document.getElementById(id).style.border = '1px solid #FF0000';
    //SetDOMElementInnerHtml('errorbox','Caps Lock on');
	  left = obj.offsetLeft;
	  left = eval(parseInt(left)-450);
	  top = obj.offsetTop;
	  var disTop = typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;
	  //alert("disTop="+disTop);
	  //alert("top="+top);
	  if(parseInt(top)>parseInt(116))
		top = eval(parseInt(top)+parseInt(disTop)+40);
	  var div = GetDOMElement("capslockmsg");
	  div.style.left = left+'px';
	  div.style.top = top+'px';
	  div.style.zIndex = (zindex) ? zindex : 1;
	
    ShowElement("capslockmsg");
    SetDOMElementInnerHtml('capslockmsg','Caps Lock on');
  }else{
    document.getElementById(id).style.border = '0px solid #FFFFFF';
    //SetDOMElementInnerHtml('errorbox','');
    HideElement("capslockmsg");
    SetDOMElementInnerHtml('capslockmsg','');
  }
}

function DisplayWrongInputError( show, obj, msg, zindex, left)
{
  if(show)
  {
	  //left = obj.offsetLeft;
	  top = 180;
	  var disTop = typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;
	  var div = GetDOMElement("capslockmsg");
	  div.style.left = left+'px';
	  div.style.top = top+'px';
	  div.style.zIndex = (zindex) ? zindex : 1;
	
	  ShowElement("capslockmsg");
      SetDOMElementInnerHtml('capslockmsg',msg);
  }
  else
  {
    HideElement("capslockmsg");
    SetDOMElementInnerHtml('capslockmsg','');
  }
}

function ShowHint(value, elem, type, e)
{
  if(Trim(value)=="")
  {
    SetDOMElementInnerHtml('hint','');
    HideElement('hint');	  
    return null;
  }
  var key = (window.event) ? event.keyCode : e.which;
  if((key>=65 && key<=90) || (key>=48 && key<=57) || key==8 || key==46)
  {
    value = Trim(value);
    var url = simple_request_url_base+""+type+"&i=" + uid + "&c=" + upw +"&word="+value+"&dtype="+dtype;
    var ggai = new AJAXInteraction(url, SetShowHint);
    ggai.Get();	
  }
  else
    return null;
}

function SetShowHint(res)
{
  if(res && res!="")
  {
    SetDOMElementInnerHtml('hint',res);
    ShowElement('hint');
  }
  else
  {
    SetDOMElementInnerHtml('hint','');
    HideElement('hint');		
  }
}

function GetUserOwnBizReview(userid, useraliasid)
{
  business_category_html = GetDOMElementInnerHtml('mastersummary');
  //alert(userid+', '+useraliasid);
  clearInterval(interval);
  SetDOMElementInnerHtml('mastersummary', '<div id="loading_gif" style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div><div style="display:none" id="controls"></div><div style="display:none" id="Listing"></div><div style="display:none" id="User"></div><div style="display:none" id="Review"></div>');	
  ShowElement('mastersummary');
  HideElement('detailsummary');
  var url = simple_request_url_base+"getuserownbizreview&i=" + uid + "&c=" + upw +"&userid="+userid+"&useraliasid="+useraliasid+"&dtype="+dtype;
  var ggai = new AJAXInteraction(url, SetUserOwnBizReview);
  ggai.Get();
}

function SetUserOwnBizReview(response)
{
  //alert(response)
  SetDOMElementInnerHtml('mastersummary', response);
}

function GetBizReview(bizid, oid, sindex)
{
	SetDOMElementInnerHtml('bizreviews', '<div id="loading_gif" style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div><div style="display:none" id="controls"></div><div style="display:none" id="Listing"></div><div style="display:none" id="User"></div><div style="display:none" id="Review"></div>');
	url = MAIN_URL_BASE+'graffiti_dropdown.php?req=1';
//	url += (graffitiid) ? "&graffitiid="+graffitiid : "";
	url += (oid) ? "&oid="+oid : "";
//	url += (alisid) ? "&writeraliasid="+alisid : "";
	url += (bizid) ? "&bizid="+bizid : "";
	url += (main_map['lat']) ? "&hdnlat="+main_map['lat'] : "";
	url += (main_map['lon']) ? "&hdnlon="+main_map['lon'] : "";
	url += (sindex) ? "&sindex="+sindex : 0;
	var ggai = new AJAXInteraction(url, FillLocalliteSummaryWithResponseHtml);
	ggai.Get();
}

function KMLLoader(kmzfile)
{
	try{
		if(!kmzfile)
			kmzfile = GOOGLE_MAP_KMZ_FILE;
  if(kmzfile)
  	if(kmzfile!="")
	{
	  if(geoxml)
	     main_map['map'].removeOverlay(geoxml);
	  geoxml = new GGeoXml(kmzfile);
	  geoxml.hidden = false;
	  main_map['map'].addOverlay(geoxml);
	  MallSpecificOnly();
	}
	CreateMallLevelButton();
	}
	catch(e)
	{}
}

function GetRSSFeed()
{
	var url = simple_request_url_base+'getrssfeed&req=1';
	var ggai = new AJAXInteraction(url, FillRSSFeedResponseHtml);
	ggai.Get();
}

function FillRSSFeedResponseHtml(response)
{
  if(response)
    SetDOMElementInnerHtml('rssfeed', response);
  else
    SetDOMElementInnerHtml('rssfeed', '');
  if(GetDOMElement('tab3'))	
	 GetDOMElement('tab3').setAttribute('onClick', 'LivePageTabs(3);');
}
function removeElement(parent, child)
{
  var d = document.getElementById(parent);
  var olddiv = document.getElementById(child);
  d.removeChild(olddiv);
}
