// 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;

// 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 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 = 14;

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;
//
// 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 get group names
var get_group_names_url_base = MAIN_URL_BASE + "getgroupnames_x.php";

// Variables needed to delete a particular group object (tag)
var delete_tag_group_url_base = simple_request_url_base + "deletegrouptag&oid=";

// Variables associated with location history search
var NUM_HISTORY_LOCATIONS = 25;
var loc_hist_data= new Array();

// Variables needed to get moving object location
var get_obj_loc_url_base = MAIN_URL_BASE + "getlatestlocation_x.php?";
var moving_objects = new Array();

var view_tmp_loc_url_base = MAIN_URL_BASE + "viewtmplocation_x.php?";

// 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 for getting device group display status
var get_gdisp_status_url_base = simple_request_url_base + "displayedgroups&";

// Variables for getting instant messages
var get_instant_messages_url_base = MAIN_URL_BASE + "getinstantmessages_x.php?";

// Variables related to updating tags;
var tag_update_url_base = MAIN_URL_BASE + "updatetag_x.php?";

// Variables related to updating tags;
var ad_update_url_base = MAIN_URL_BASE + "updatead_x.php?";

// The default html for updating ad content
var get_customized_tag_form_url_base = MAIN_URL_BASE + "tagpopuptemplate.php?";
var customized_tag_form_html = null;

// The default html for updating generic tag content
var get_customized_ad_form_url_base = MAIN_URL_BASE + "adpopuptemplate.php?";
var customized_ad_form_html = null;

// Variables needed to get moving object location
var get_loc_hist_url_base = simple_request_url_base + "locationhistory&";

// Variables needed to get moving object location
var get_hist_at_loc_url_base = MAIN_URL_BASE + "gethistoryatlocation_x.php?";

// 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 ParseNearestBizResponse(rstr)
{
  if(GetDOMElement("tagbizlistDiv") && rstr)
  {
    var string = nth_xml_tag(rstr, "string", 0);
    if(string)
    {
      SetDOMElementInnerHtml('tagbizlistDiv', 'Business:<select style="width:165px;margin-bottom:2px;" class="tagselect" name="tagbizlist" id="tagbizlist" >'+string+'</select>');
    }
  }
}

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 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 AddTagModalDialog(lat, lon, alt, oid, bizresultid, adpin)
{
  availW = GetWindowWidth();

  var alt = (alt) ? alt : 0;
  var adpin = (adpin) ? adpin : false;

  CreateGrayOverlay();

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

  if(main_map['type']==SIMPLE_MAP && parseInt(availW)<1000) mbox.style.left = '110px';

  // XXXX: Do not use SetDOMElementInnerHtml function here as it will clear PopupDismissTimer;
  mbox.innerHTML = '<div style="float:left; margin-left:100px;">'+GetProgressBarObject()+'</div>';

  customized_tag_form_html = null;
  if(main_map['type']!=MOBIKU_MAP)
  {
    if(adpin)
    {
      var ct_url = get_customized_ad_form_url_base + "i="+uid+"&c="+upw+"&lat="+lat+"&lon="+lon;
      if(oid > 0)
	ct_url += "&oid="+oid;
      ct_url += (main_map['type']==SIMPLE_MAP && selected_groups) ? "&gid="+selected_groups : "";
      if (bizresultid > 0)
	ct_url += "&bizresultid="+bizresultid;
	
      ct_url += (main_map['type']==SIMPLE_MAP) ? "&isSimpleMap=1" : "";
    }
    else
    {
      var ct_url = get_customized_tag_form_url_base + "i="+uid+"&c="+upw+"&lat="+lat+"&lon="+lon;
      if(oid > 0)
	ct_url += "&oid="+oid;
      ct_url += (main_map['type']==SIMPLE_MAP && selected_groups) ? "&gid="+selected_groups : "";
      if (bizresultid > 0)
	ct_url += "&bizresultid="+bizresultid;
	
      ct_url += (main_map['type']==SIMPLE_MAP) ? "&isSimpleMap=1" : "";
    }
    var gaddress = GetDOMElement('gaddress');
    if(gaddress)
    {
      gaddress = CleanTagString(gaddress.value);
      // XXXX: Do not include code below in function 'CleanTagString' as this will disturb data representation on home.php and view_graffiti.php
      gaddress = (gaddress) ? gaddress.replace(/<b>/g, "") : "";
      gaddress = gaddress.replace(/<\/b>/g, "");
      ct_url += "&address="+encodeURI(gaddress);
    }
	
    var gbizid = GetDOMElement('gbizid');
    if(gbizid)
    {
      gbizid = CleanTagString(gbizid.value);
      gbizid = gbizid.replace(/ /g, "");
      ct_url += "&gbizid="+encodeURI(gbizid);
    }
	
    //XXXX: Call to this function is correct as it correct as it would only
    //display output - we would still do this if adpin
    var ctai = new AJAXInteraction(ct_url, ParsePopupTagResults);
    if (ctai)
      ctai.Get();
  }
  else
  {
    var m = GetPopupHTML('<input type=hidden id=txtlat value="'+(lat)+'" /><input type=hidden id=txtlon value="'+(lon)+'" />', 'MobikuPopup');
    var html = '<div class="post"><div class="ct"><div class="l"><div class="r"/></div></div><h3 class="title">Add Graffiti<div style="width: 10px; float: right;"><img title="Close Popup" src="'+IMAGE_URL_BASE+'help_close.gif" onClick="CancelTagUpdate();"></h3><p class="byline"/><div class="entry">'+m+'</div><div class="cb"><div class="l"><div class="r"/></div></div></div>';
    SetDOMElementInnerHtml('mbox', html);
  }
  var td = GetDOMElement("tagthislocation");
  if (td)
  {
    var la = document.createElement("input");
    if (la)
    {
      la.setAttribute('type', 'hidden');
      la.setAttribute('id', 'taglatname');
      la.setAttribute('value', lat);
      td.appendChild(la);
    }

    var lo = document.createElement("input");
    if (lo)
    {
      lo.setAttribute('type', 'hidden');
      lo.setAttribute('id', 'taglonname');
      lo.setAttribute('value', lon);
      td.appendChild(lo);
    }

    var al = document.createElement("input");
    if (al)
    {
      al.setAttribute('type', 'hidden');
      al.setAttribute('id', 'tagaltname');
      al.setAttribute('value', alt);
      td.appendChild(al);
    }
    if (oid > 0)
    {
      var al = document.createElement("input");
      if (al)
      {
	al.setAttribute('type', 'hidden');
	al.setAttribute('id', 'oid');
	al.setAttribute('value', oid);
	td.appendChild(al);
      }
    }
  }

  tdg_oid = oid;
}

function ParsePopupTagResults(rstr)
{
  customized_tag_form_html = rstr;
  SetDOMElementInnerHtml('mbox', customized_tag_form_html);
}

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')!="")
      OneSearch();
  }
}

function OneSearch(what)
{
  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>');
  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 = '';

  // Simultaneously issue a search for businesses
  FindBusinesses(searchstring);

  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)
{
  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)
  {
    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);
}

function SendBusinessSearchRequest(what, search_index, our_db)
{
  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 + "&sindex="+search_index + "&dtype="+dtype;
  //gg_url += "&miles=20";
  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);
  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;
  SetMarqueeTimeout();
}

// 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+"&dtype=web&lat="+main_map['lat']+"&lon="+main_map['lon'];
  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');
  SetDOMElementInnerHtml('Listing', rstr);
  ShowElement('ready');
  HideElement('notready');
  ShowElement('businessResults');
  ShowElement('businessResultsdiv');
  ShowElement('businessResultsclrbtn');
  DisplayNoSearchResultsMessage(1);
  SetMarqueeTimeout();
  var script = GetDOMElementValue('script');
  if(script)
    eval(script);
  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)
{
  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)
{
  if (displayed_groups["'"+gid+"'"] != null)
  {
    GeoAlert(12, "Being asked to clear group " + gid);
    if (displayed_groups["'"+gid+"'"]['gid'] != null)
      displayed_groups["'"+gid+"'"]['gid'] = null;

    // Only clear the moving_objects array if the group is actually being
    // unchecked. Otherwise, just nuke the pins because this function is
    // just being called to nuke the old pins
    if (displayed_groups["'"+gid+"'"]['moving'] == 1)
    {
      // This group is for a moving object(s).
      if (displayed_groups["'"+gid+"'"]['oid'] != null)
      {
   	for (var obj in displayed_groups["'"+gid+"'"]['oid'])
   	{
   	  var oid = displayed_groups["'"+gid+"'"]['oid'][obj];
   	  if (moving_objects["'"+oid+"'"] != null)
   	  {
 	    GeoAlert(12, "[DGP] Value of moving_objects["+oid+"] is: " + moving_objects["'"+oid+"'"]['get_loc_timer']);
  	    if (moving_objects["'"+oid+"'"]['get_loc_timer'] != null)
   	    {
	      //  	      cancelTimeout(moving_objects["'"+oid+"'"]['get_loc_timer']);
   	      clearTimeout(moving_objects["'"+oid+"'"]['get_loc_timer']);
  	      GeoAlert(12, "Cleared timer: "+moving_objects["'"+oid+"'"]['get_loc_timer']);
   	      moving_objects["'"+oid+"'"]['get_loc_timer'] = null;
  	    }
 	    else
 	      GeoAlert(12, "but this ("+oid+") objects moving objects timer is null. why?");
	
   	    moving_objects["'"+oid+"'"]['last_lat'] = null;
   	    moving_objects["'"+oid+"'"]['last_lon'] = null;
   	    moving_objects["'"+oid+"'"]['last_time'] = null;
   	    moving_objects["'"+oid+"'"] = null;
   	  }
   	}
   	displayed_groups["'"+gid+"'"]['oid'] = null;
      }
    }
    // Now delete all the pushpins associated with this group
    ClearGroupPushPins(gid);
    displayed_groups["'"+gid+"'"] = null;
  }
  else
  {
    GeoAlert(12, "Being asked to clear group " + gid + " but group is null already");
    // ClearGroupPushPins(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);
    }
}

function DisplayAllDeviceCheckedGroups()
{
  if (uid == null || dtype == null)
    return;

  // First send a request to get all the checked groups for this device
  // Then, for each such group call ToggleTagGroupDisplay with uncheck=false if
  // the group is still to be displayed or called UnDisplayTagGroup if the
  // group is to no longer be displayed.
  //
  // It might be prudent to run this above sequence periodically (through a
  // timer).
  var gg_url = get_gdisp_status_url_base + "i=" + uid + "&c=" + upw + "&dtype=" + dtype;
  var ggai = new AJAXInteraction(gg_url, ParseGetGroupDisplayResponse);
  if (ggai)
    ggai.Get();
}

function ParseGetGroupDisplayResponse(rstr)
{
  var btn = GetDOMElement('btnrefresh');
  if(!rstr || rstr=="")
  {
    SetDOMElementInnerHtml('grpList', '');
    return null;
  }

  var json = GetJson(rstr);
  var gnum = (json && json.groups) ? json.groups.length : 0;
  var html = "";

  for (var i=0; i<gnum; i++)
  {
    var elem = json.groups[i];
    var gid = (elem && elem.gid) ? elem.gid : null;
    var gtype = (elem && elem.gtype) ? elem.gtype : null;
    var gtitle = (elem && elem.title) ? elem.title : null;
    checked_groups["'"+gid+"'"] = gid;

    var gtypestyle = "";
    if(gtype && gtype=='biz')
      gtypestyle = "color:ForestGreen; font-weight:bold;";
	

    if(btn && btn.name==2)
    {
      html += '<div style="text-align:left; height:20px;'+gtypestyle+'"><input id="chk'+i+'" name="" type="checkbox" value="'+ gid +'" onclick="ToggleTagGroupDisplay('+ gid +')" checked /><label style="margin-left:25px; float:none;" for="inp1">'+gtitle+'</label></div>';
    }
  }

  if(btn && btn.name==2)
  {
    btn.name=1;
    SetDOMElementInnerHtml('grpList', "");
    html = (html=="") ? '<div style="text-align:left; height:20px;"><label style="margin-left:25px; float:none;" for="inp1">No List Selected To Display!</label></div>' : html;
    SetDOMElementInnerHtml('grpList', html);
    SetDOMElementValue('maxWallDisp', gnum);
  }
  else
    UpdateDisplayOfAllGroupTags();
}

function ToggleTagGroupDisplay(g, check)
{
  RemoveInfoWindow();

  // By default, set to true. Used to determine whether to undisplay group
  // or not
  var check = (check == null) ? true : check;

  // XXXX: the value in checked_groups must always match the checkbox on
  // the web page. In other words, if the value of checked_groups[group id]
  // is not null, the checkbox corresponding to that group must be checked
  // on the webpage. If the checkbox is not checked, the value in the array
  // should be null. So this assumes that there is consistency between the
  // display and the array in the Javascript. That is dangerous. Eventually
  // we should use the explicit value of the checkbox (which should be
  // passed in) to actually determine and set the display of the tag group.
  if (IsGroupBeingDisplayed(g) == false)
  {
    GeoAlert(12, "Group("+g+") is not being displayed - displaying");
    checked_groups["'"+g+"'"] = g;

    SendGroupDisplayUpdateRequest(g, 'set');
    try
    {
      GetMapView();
    }
    catch(e)
    {
      GeoAlert(0, "[ToggleTagGroupDisplay] Exception. Message= " + e.message);
    }

    try
    {
      GetGroupTags(g);
    }
    catch (e)
    {
      // Nothing
    }
  }
  else
  {
    if (check == true || check == "true")
    {
      GeoAlert(12, "Group("+g+") is being displayed - undisplaying");
      // Only undisplay this group if the bool is set to true - meaning that
      // this function is being called as a result of the user unchecking
      // the display of this group from the appropriate groupname display
      // page. Since such a call will not have the check parameter set,
      // this function will set the value to true (default).
      // The value of the bool will be false if this function is

      // being called through a function that gets the current devicegroup
      // status from the server - indicating that the group should be
      // continued to display.

      // If the server indicates that this group should no longer be
      // displayed on this device, the appropriate response handling
      // function will call UnDisplayTagGroup directly.
      UnDisplayTagGroup(g);
    }
    else
    {
      GeoAlert(12, "Group("+g+") is being displayed - not being asked to do any. So, not doing anything");
      // Nothing to do - group is already being displayed and we are not
      // being asked to stop displaying it.
    }
  }
}

function UnDisplayTagGroup(g, updatedb)
{
  var updatedb = (updatedb == null) ? true : updatedb;

  checked_groups["'"+g+"'"] = null;
  if (updatedb == true)
    SendGroupDisplayUpdateRequest(g, 'unset');

  DeleteGroupPins(g);
}

function UnDisplayAllTagGroups()
{
  try
  {
    for (var gid in checked_groups)
    {
      var gnum = checked_groups[gid];
      if (gnum != null)
  	UnDisplayTagGroup(gnum, false);

    }
  }
  catch (exception) {
    GeoAlert(0, "UnDisplayAllTagGroups: exception.");
  }
}

// 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 GetGroupTags(g)
{
  UpdateDisplayOfAllGroupTags();	
  return null;

  var dg_url = disp_tag_group_url_base + "i=" + uid + "&c=" + upw + "&gid=" + g + "&dtype=" + dtype;
  dg_url += "&tllat=" + GetLatitudeFromPoint(main_map['topleft']);
  dg_url += "&tllon=" + GetLongitudeFromPoint(main_map['topleft']);
  dg_url += "&brlat=" + GetLatitudeFromPoint(main_map['bottomright']);
  dg_url += "&brlon=" + GetLongitudeFromPoint(main_map['bottomright']);

  GeoAlert(14, "[GetGroupTags] Getting tags for group " + g);

  var dgai = new AJAXInteraction(dg_url, ParseGetGroupTagsResults);
  if (dgai)
    dgai.Get();
}

function ParseGetGroupTagsResults(rstr)
{
  if(!rstr || rstr=="")
    return null;

  disp_tag_group_html = rstr;

  var json = GetJson(rstr);
  var ggid = (json && json.gid) ? json.gid : null;
  var ggtype = (json && json.gtype) ? json.gtype : null;
  var gicon = (json && json.grpicon) ? json.grpicon : null;
  var gnum = (json && json.tag) ? json.tag.length : 0;
  // TODO: if the group is a "moving group" and there are no
  // tags, then the timer will not start ...
  GeoAlert(14, "Displaying " + gnum + " tags for group " + ggid + "full response: " + rstr);

  var html = "";
  html += GetDOMElementInnerHtml('dispWallGrftidiv');
  for (var i=0; i<gnum; i++)
  {
    var tagdata = json.tag[i];//nth_xml_tag(rstr, "Tag", i);
    var info = ExtractTagInformation(tagdata, 0);

    if (info)
    {
      var goid = info['oid'];
      var gmp = info['moving'];
      var glat = info['lat'];
      var glon = info['lon'];
      var str = CleanTagString(info['tagdesc']);

      var tdesc = "<div style='font-size:8pt; font-family:Arial;'>"+str+"<input type='hidden' id='gaddress' value='"+info['address']+"' /></div>";
      var seldata = (info['name'] && info['name']!="") ? "<b>"+info['name']+"</b><br/>" : str.substr(0, str.indexOf("<hr>"))+"<br/>";
      seldata += (info['address'] && info['address']!="") ? info['address']+"<br/>" : "";
      if (main_map['type']==MOBIKU_MAP)
	html += "<li>";
      html += "<div id='wallObject"+tagIndex+"' style='font-size:8pt; font-family:Arial; text-align:left; padding-top:5px; padding-bottom:5px;'  onmouseover='OpenInfoWindowForList("+tagIndex+")'><input type='hidden' value='"+info['timeupdate']+"' id='updatetime"+tagIndex+"'>";

      var time = (info['timeupdate']) ? info['timeupdate'] : "";
      time = time.substr(0, time.indexOf(" "));

      html += (main_map['type']!=MOBIKU_MAP) ? '<table><tr><td><div style="float:left; width:45px; text-align:center;">'+tagIndex+'</div><div style="float:left; width:150px; text-align:left;">'+seldata+'</div><div style="float:left; width:100px; text-align:left;">'+time+'</div></td></tr></table>' : '<table><tr><td><div style="float:left; width:150px; text-align:left;">'+seldata+'</div></td></tr></table>';
      html += "</div>";
      if (main_map['type']==MOBIKU_MAP)
	html += "</li>";

      gicon = (info['alert']) ? NewIcon("purple") : nth_xml_tag(rstr, "grpicon", 0);
      if(ggtype=='biz')
	gicon = NewIcon("pink");
      AddGroupPin(glat, glon, tdesc, gicon, gmp, ggid, goid);
    }
    else
      GeoAlert(14, "Did not extract any information for tag " + i);
  }

  SetDOMElementInnerHtml('dispWallGrftidiv', html);
  ShowElement('dispWallGrfti');
  ShowElement('dispWallGrftidiv');
  ShowElement('dispWallGrfticlrbtn');
}

function GetAllDisplayedGroupsTags()
{
  var dg_url = disp_all_groups_tags_url_base + "i=" + uid + "&c=" + upw + "&dtype=" + dtype;
  dg_url += "&tllat=" + GetLatitudeFromPoint(main_map['topleft']);
  dg_url += "&tllon=" + GetLongitudeFromPoint(main_map['topleft']);
  dg_url += "&brlat=" + GetLatitudeFromPoint(main_map['bottomright']);
  dg_url += "&brlon=" + GetLongitudeFromPoint(main_map['bottomright']);

  GeoAlert(14, "[GetGroupTags] Getting tags for all displayed groups");

  var dgai = new AJAXInteraction(dg_url, ParseGetAllDisplayedGroupsTagsResults);
  if (dgai)
    dgai.Get();
}

function ParseGetAllDisplayedGroupsTagsResults(rstr)
{
  if(!rstr || rstr=="")
    return null;

  disp_all_groups_tags_html = rstr;

  var temp = rstr.split('{"gid":');
  for(var g=1; g<temp.length; g++)
  {
    var string = '{"gid":'+temp[g];
    string = (string.lastIndexOf(',')==((string.length)-1)) ? string.substring(0, (string.length)-1): string;
    ParseGetGroupTagsResults(string);
  }
}

function ExtractTagInformation(rstr, index)
{
  if (!rstr || index < 0)
    return null;

  var info = new Array();

  var moving = rstr.moving;
  var oid = rstr.oid;
  var bizid = rstr.bizid;

  var name = rstr.name;
  name = CleanTagString(name);

  if(name && name.indexOf("&")>0)
  {
    var str = name.substr(0, name.indexOf("&"));
    str += " and "+name.substr(eval(name.indexOf("&")+1), name.length);
    name = str;
  }
  if (!name || name=="")
    name = rstr.Name;
  if (name)
    name = CleanTagString(name);

  var address = rstr.businessaddress;
  if (address)
  {
    address = CleanTagString(address);
  }
  else
  {
    var address = rstr.address;
    if (address)
      address = CleanTagString(address);
  }

  var description = rstr.description;
  if (description)
    description = CleanTagString(description);
  var graffities = rstr.graffities;
  var rating = 0;
  if(graffities)
  {
    description = (description) ? description+"<hr>" : "";
    // XXXX: In graffities variable we have data excluding graffities tags there fore I am adding graffities tags to form a
    //       validate xml to load and parse
    var graffitinum = graffities.length;
    for(var g=0; g<graffitinum; g++)
    {
      var add = "";
      var elem = (graffities[g] && graffities[g].graffiti) ? graffities[g].graffiti : null;
      var timeupdate = (graffities[0] && graffities[0].timeupdated) ? graffities[0].timeupdated : null;
      var nl = (elem) ? elem.length : 0;
      for(var h=0; h<nl; h++)
      {
	var subelem = elem[h];
	if(subelem)
	{  	
	  switch(subelem.name)
	  {
	      case "alerttype":
		info['alert'] = "1";
		break;
	      case "hyperlink":
		var hyperlink = decodeURI(subelem.value);
		if(hyperlink && !(hyperlink.indexOf("<a")>=0))
		{
		  var strlink = hyperlink.substr(0, hyperlink.indexOf("|==|"));
		  strlink = "<a href='"+strlink+"' target='_blank'>"+ hyperlink.substr(hyperlink.indexOf("|==|")+4, hyperlink.length) +"</a>";
		  add += (strlink)+"<br>";
		}
		else
		  add += (hyperlink)+"<br>";
			
		break;
	      case "icon":
		var icont = decodeURI(subelem.value);
		add += CleanTagString(icont)+"<br>";
		break;	
	      case "mobiku":
		var mobikut = decodeURI(subelem.value);
		add += CleanTagString(mobikut)+"<br>";
		break;
	      case "multimedia":
		var mmlda = decodeURI(subelem.value);
		add += "<img src='"+CleanTagString(mmlda)+"' width='200' height='80' /><br>";
		break;
	      case "rating":
		var rrvwt = decodeURI(subelem.value);
		add += "<div title='Graffiti Ratings' style='height:15px; padding-top:1px; padding-bottom:1px;'>";
		var rclass = (rrvwt>=1) ? 'ratingstarselected' : 'ratingstar';
		add += "<div id='ratingstar1' class='"+rclass+"'></div>";
		var rclass = (rrvwt>=2) ? 'ratingstarselected' : 'ratingstar';
		add += "<div id='ratingstar2' class='"+rclass+"'></div>";
		var rclass = (rrvwt>=3) ? 'ratingstarselected' : 'ratingstar';
		add += "<div id='ratingstar3' class='"+rclass+"'></div>";
		var rclass = (rrvwt>=4) ? 'ratingstarselected' : 'ratingstar';
		add += "<div id='ratingstar4' class='"+rclass+"'></div>";
		var rclass = (rrvwt>=5) ? 'ratingstarselected' : 'ratingstar';
		add += "<div id='ratingstar5' class='"+rclass+"'></div>";		
		add += "</div><br>";
		break;
	      case "review":
		var rrvwt = decodeURI(subelem.value);
		add += "<div title='User Review' style='float:left; width:45px;'></div><div title='User Review' style='min-height:25px;'>"+CleanTagString(rrvwt)+"</div><br>";
		break;
	      case "text":
		var txtt = decodeURI(subelem.value);
		add += CleanTagString(txtt)+"<br>";
		break;
	      default:
		break;
	  }//
	}//
      }//
      description += (add) ? (add+"<hr>") : "";
    }//
  }

  var phone = rstr.phonenumber;
  if (phone)
    phone = CleanTagString(phone);
  else
  {
    var phone = rstr.phone;
    if (phone)
      phone = CleanTagString(phone);
  }

  var adtext = rstr.adtext;
  if (adtext)
    adtext = CleanTagString(adtext);

  var adid = rstr.adid;
  if (adid)
    adid = adid;

  var bizadtext = rstr.bizad;
  if(bizadtext)
    bizadtext = bizadtext;

  var numreviews = rstr.NumReviews;
  if(numreviews)
    numreviews = numreviews;

  var numpics = rstr.NumPics;
  if(numpics)
    numpics = numpics;

  var numsvnotes = rstr.NumVoiceNotes;
  if(numsvnotes)
    numsvnotes = numsvnotes;

  var thumb = rstr.thumbnailurl;
  if (thumb)
    thumb = CleanTagString(thumb);

  var img = rstr.imageurl;
  if (!img)
    img = rstr.image;
  if (img)
    img = CleanTagString(img);

  var vid = rstr.videourl;
  if (vid)
    vid = CleanTagString(vid);

  var favorite = rstr.favorite;
  if(favorite)
    favorite = favorite;
  else
    favorite = 0;
  
  var rating = rstr.rating;
  if (rating)
    rating = rating;
  else
  {
    rating = rstr.Rating;
    if(rating)
      rating = rating;
    else
      rating = null;
  }
  
  //var is_this_an_ad = rstr.advertisement;
  var is_this_an_ad = adtext ? 1 : 0;

  var lat = rstr.lat;
  var lon = rstr.lon;
  if (!lat || !lat)
  {
    var coordinates = rstr.coordinates;
    if (coordinates)
    {
      var str1 = coordinates.indexOf(",");
      lat = coordinates.substr(0, str1);
      coordinates = coordinates.substr(eval(str1+1), coordinates.length);
      if (coordinates)
      {
 	var str2 = coordinates.indexOf(",");
 	lon = coordinates.substr(0, str2);
      }
    }
  }

  info['moving'] = moving;
  info['oid'] = oid;
  info['phone'] = phone;
  info['ad'] = adtext;
  info['bizad'] = bizadtext;
  info['thumb'] = thumb;
  info['img'] = img;
  info['vid'] = vid;
  info['is_ad'] = is_this_an_ad;
  info['lat'] = lat;
  info['lon'] = lon;
  info['name'] = (name) ? name : "&nbsp;";
  info['address'] = (address) ? address : "&nbsp;";
  info['bizid'] = (bizid) ? bizid : null;
  info['adid'] = (adid) ? adid : null;
  info['timeupdate'] = (timeupdate) ? timeupdate : '';
  info['rating'] = (rating) ? rating : 0;
  info['favorite'] = (favorite) ? favorite : 0;

  info['numreview'] = (numreviews) ? numreviews : 0;
  info['numpics'] = (numpics) ? numpics : 0;
  info['numsvnotes'] = (numsvnotes) ? numsvnotes : 0;

  info['tagdesc'] = "";
  if (name)
  { info['tagdesc'] += "<b>"+name+"</b><hr>"; }
  if (description)
  { info['tagdesc'] += '<br>' + description + '';}
//  else   {info['tagdesc'] += '<hr>';}
  if (address) info['tagdesc'] += '<br>' + address;
  if (phone) info['tagdesc'] += '<br>' + phone;
  if (adtext)
  {
    if (vid)
      info['tagdesc'] += '<hr><a href="' + vid + '">' + adtext + '</a>';
    else
    {
      if (img)
 	info['tagdesc'] += '<hr><a href="' + img + '">' + adtext + '</a>';
      else
	info['tagdesc'] += '<hr>' + adtext;
    }
  }
  else
  {
    if (thumb)
    {
      if (vid)
      {
	info['tagdesc'] += '<hr><a href="' + vid + '"><img src="' + thumb + '" /></a>';
      }
      else
      {
 	if (img)
 	  info['tagdesc'] += '<hr><a href="' + img + '"><img src="' + thumb + '" /></a>';
 	else
 	  info['tadesc'] += '<hr><img src="' + thumb + '" />';
      }
    }
    else
    {
      if (img)
      {
	info['tagdesc'] += '<hr><img src="' + img + '" />';
      }
    }
  }

  if(graffitinum && graffitinum>0)
    info['graffiti'] = 'true';

  return info;
}

function GetNodeInnerText(node)
{
  if((!(node)))
    return "";

  var innerText = (node.textContent) ? (node.textContent) : (node.text);	
  return innerText;
}

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 ExtractReviewInformation(rstr, index)
{
  if (!rstr || index < 0)
    return null;

  var desc="";
  var reviews = "<R>" + nth_xml_tag(rstr, "Reviews", index) + "</R>";
  if (reviews)
  {
    desc = "<table><tr>";
    var noOfReviews = str_num_occurrences(reviews, "<Review>");
    for (var j=0; j<noOfReviews; j++)
    {
      var reviewerName = nth_xml_tag(reviews, "ReviewerName", j);
      if (reviewerName)
	reviewerName = CleanTagString(reviewerName);

      var reviewerIcon = nth_xml_tag(reviews, "ReviewerIcon", j);
      if (reviewerIcon)
	reviewerIcon = CleanTagString(reviewerIcon);

      var reviewURL = nth_xml_tag(reviews, "ReviewURL", j);
      if (reviewURL)
	reviewURL = CleanTagString(reviewURL);

      var numReviews = nth_xml_tag(reviews, "NumReviews", j);
      if (numReviews)
	numReviews = CleanTagString(numReviews);

      var ratings = nth_xml_tag(reviews, "Rating", j);
      if (ratings)
	ratings = CleanTagString(ratings);

      var info = nth_xml_tag(reviews, "Info", j);
      if (info)
	info = CleanTagString(info);

      desc += "<td><table>" +
 	"<tr><td><a href=\""+reviewURL+"\"><img src=\"."+reviewerIcon+"\" width=\"42\" height=\"24\" border=\"0\"></a></td></tr>";
      if (ratings || numReviews)
 	desc += "<tr><td>";
      if (ratings)
 	desc += ratings;
      if (numReviews)
 	desc += "("+numReviews+")";
      if (ratings || numReviews)
 	desc += "</td></tr>";
      if (info)
 	desc += "<tr><td>"+info+"</td></tr>";
      desc += "</table></td>";

      if(! (j == eval(noOfReviews-1)))
      {
 	desc += "<hr>";
      }
    }
    desc += "</tr></table>";
  }
	
  return desc;
}

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 StartGetObjectLocationTimer(g, o)
{
  // If timer already exists - do not add another one.
  if (moving_objects["'"+o+"'"] != null && moving_objects["'"+o+"'"]['get_loc_timer'] != null)
    return;

  var t = setTimeout("GetObjectLocation('"+g+"','"+o+"',1)", 30000);
  if (moving_objects["'"+o+"'"] == null)
    moving_objects["'"+o+"'"] = new Array();

  moving_objects["'"+o+"'"]['get_loc_timer'] = t;
  GeoAlert(12,"[SGOLT] Value of moving_objects["+o+"] is: " + moving_objects["'"+o+"'"]['get_loc_timer']);
}

function GetObjectLocation(gid, oid, timer_call)
{
  var timer_call = (timer_call) ? timer_call : null;
  if (timer_call)
  {
    // Since this function was called by the timer itself, clear the
    // old entry for the timer.
    if (moving_objects["'"+oid+"'"])
      moving_objects["'"+oid+"'"]['get_loc_timer'] = null;
  }

  // Now build the request to send out
  var go_url = get_obj_loc_url_base + "i=" + uid + "&c=" + upw + "&gid=" + gid + "&oid=" + oid;

  var goai = new AJAXInteraction(go_url, ParseGetObjectLocationResults);
  if (goai)
    goai.Get();
}

function ParseGetObjectLocationResults(rstr)
{
  var acode = nth_xml_tag(rstr, "acode", 0);
  var expired = nth_xml_tag(rstr, "expired", 0);
  var tgid = nth_xml_tag(rstr, "gid", 0);
  var toid = nth_xml_tag(rstr, "oid", 0);
  var tnum = str_num_occurrences(rstr, "<Location>");

  GeoAlert(16, "[ParseGetObjectLocationResults]: " + tnum + " results. Expired is: " + expired);

  var tnow = GMTDate();
  if (tnum > 0)
  {
    var t = nth_xml_tag(rstr, "Time", 0);
    var tdiff_str = DateDifference(t, tnow);
    GeoAlert(16, "t: "+t+" now:"+tnow.toGMTString() + " diff:" + tdiff_str);

    ClearGroupPushPins(tgid);
    var lat = nth_xml_tag(rstr, "Latitude", 0);
    var lon = nth_xml_tag(rstr, "Longitude", 0);
    var alt = nth_xml_tag(rstr, "Altitude", 0);
    var vll = NewLatLongPoint(lat, lon);

    // XXXX: typically we set the map center after adding the pin but in
    // this case for some reason that ends up nuking the pin
    SetMapCenter(main_map['map'], vll);
    AddLatLonPin(tgid, toid, vll, tdiff_str, null, 1);

    if (moving_objects["'"+toid+"'"] == null)
      moving_objects["'"+toid+"'"] = new Array();
    moving_objects["'"+toid+"'"]['last_time'] = t;
    moving_objects["'"+toid+"'"]['last_lat'] = lat;
    moving_objects["'"+toid+"'"]['last_lon'] = lon;
  }
  else
  {
    if (!acode)
      GeoAlert(16, 'Object has not moved.');
  }

  if (acode)
  {
    ClearErrorBox();
    if (!expired)
    {
      StartViewUserLocationTemporarilyTimer(acode);
    }
    else
    {
      DisplayBoxError("Access to user's location has expired.");
//       // XXXX: should we redirect the user to this? Seems like we
//       // should not redirect the user to any page - just leave them be.
//       window.location = view_tmp_loc_url_base+"acode="+acode;
    }
  }
  else
  {
    StartGetObjectLocationTimer(tgid, toid);
  }
}

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

function CheckForTagsInProximityToMovingObjects()
{
  try
  {
    for (var oid in moving_objects)
    {
      // Call settimer routine to fetch locations of all tags near object's
      // current location. Set pointer to timer in moving_objects array and
      // both clear the timer and remove the entry in the deletegrouppins
      // function
      var last_lat = moving_objects[oid]['last_lat'];
      var last_lon = moving_objects[oid]['last_lon'];
      GetProximityTags(oid, last_lat, last_lon);
    }
  }catch (e)
  {
    GeoAlert(0,"Exception Occured in CheckForTagsInProximityToMovingObjects");
  }
}

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);
  }
}

function SendGroupDisplayUpdateRequest(gid, val)
{
  var ug_url = update_gdisp_status_url_base + "i=" + uid + "&c=" + upw;
  ug_url += "&gid=" + gid + "&dtype=" + dtype + "&dispval=" + val;

  var ugai = new AJAXInteraction(ug_url, ParseGroupDisplayUpdateResponse);
  if (ugai)
    ugai.Get();
}

function ParseGroupDisplayUpdateResponse(rstr)
{
  var rcode = nth_xml_tag(rstr, "rcode", 0);
}

function ConfirmGroupDelete()
{
  var delete_grp = false;
  delete_grp = confirm("Are you sure you want to delete this group? Deleting the group will also delete all objects associated with the group.");
  if (delete_grp == true)
  {
    var e = GetDOMElement('grpdeleteform');
    if (e)
      e.submit();
  }
}

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

function SendRequestToGetInstantMessages()
{
  var gim_url = get_instant_messages_url_base + "i=" + uid + "&c=" + upw;

  var gimai = new AJAXInteraction(gim_url, ParseGetInstantMessagesResponse);
  if (gimai)
    gimai.Get();
}

function ParseGetInstantMessagesResponse(rstr)
{
  if (! rstr)
    return;

  if (! ymessenger)
    return;

  var imnum = str_num_occurrences(rstr, "<IM>");
  GeoAlert(12, "You got " + imnum + " IMs");
  for (var i=0; i<imnum; i++)
  {
    var sender = nth_xml_tag(rstr, "Sendername", i);
    var im_msg = nth_xml_tag(rstr, "Msg", i);
    var senderlivelocgid = nth_xml_tag(rstr, "SenderLiveLocGid", i);
    var senderqueryrespgid = nth_xml_tag(rstr, "SenderQueryRespGid", i);
    var sendergids = senderlivelocgid + ":" + senderqueryrespgid;

    var message = "<font face='tahoma' size='1' color='darkorange'><b> " + sender + "</b> asks: " + im_msg +"</font>";
    ymessenger.toastShow(sendergids, 10, "<a href='void(0)'>" + message + "</a>");

    ymessenger.SetEventHandler("ToastLinkClicked", On_ToastLinkClicked);
    function On_ToastLinkClicked(msg)
    {
      // XXXX: note msg here is actually the 2 gids separated by a ":"
      if (!msg)
 	return;

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

      ToggleTagGroupDisplay(s[0], false);
      ToggleTagGroupDisplay(s[1], false);
    }
  }
}

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()
{
  setTimeout("$('.marquee marquee').marquee();", MARQUEE_TIMEOUT);
}

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;
}

// time is an integer representing seconds
// returns a formatted string
function SecondsToString(time)
{
  if(time == null)
    return("");

  if(time > 60)
  {                                 // if time == 100
    var seconds = time % 60;       // seconds == 40
    var minutes = time - seconds;  // minutes == 60
    minutes     = minutes / 60;    // minutes == 1

    if(minutes > 60)
    {                                     // if minutes == 100
      var minLeft = minutes % 60;        // minLeft    == 40
      var hours   = minutes - minLeft;   // hours      == 60
      hours       = hours / 60;          // hours      == 1

      return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
    }
    else
    {
      return(minutes + " minutes, " + seconds + " seconds");
    }
  }
  else
  {
    return(time + " seconds");
  }
}

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 nth_xml_tag(base, str, nth, exact)
{
  if (base == "" || str == "" || base == null || str == null || nth < 0)
    return null;

  var exact = (exact == null) ? true : exact;
  if (str[0] == "<")
    return null;

  var n = 0;
  var s = 0;
  var ts = (exact == true) ? "<"+str+">" : "<"+str+" ";
  var te = "</"+str+">";
  while (s != -1 && n < nth+1)
  {
    s = base.indexOf(ts, s+1);
    n++;
  }
  if (s == -1)
    return null;

  var l = ts.length;
  var e = base.indexOf(te, s + ts.length);
  var tag = base.substring(s+l, e);

  return tag;
}

// TODO: only works for first attribute.
function nth_xml_tag_attribute(base, tag, attr, nth)
{
  if (base=="" || tag=="" || base==null || tag==null || attr ==null || attr=="" || nth<0)
    return null;

  if (tag[0] == "<")
    return null;

  var n = 0;
  var s = 0;
  var ts = "<"+tag+" "+attr+"=\"";
  var te = "\"";
  while (s != -1 && n < nth+1)
  {
    s = base.indexOf(ts, s+1);
    n++;
  }
  if (s == -1)
    return null;

  var l = ts.length;
  var e = base.indexOf(te, s + ts.length);
  var value = base.substring(s+l, e);

  return value;
}

function quoted_str_2_num(str)
{
  if (str == null || str == "")
    return -237;

  var e = str.lastIndexOf("\"") - 1;
  return Number(str.substr(1, e));
}

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)
    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);
}

///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////// YIM Stuf ////////////////////////////////////////


///////////////////////////-------------------------//////////////////////////////
/////////////////////////// YIM Primary Window Code //////////////////////////////
// Called by yimprimarywindow.php once the user has logged into the plugin
// to open the primary window


function LoadYahooMessengerPlugin(mapcontainer, u, p)
{
  uid = u;
  upw = p;
  dtype = 'ym';

  // Pointer to primary window object
  ymessenger = window.external;

  // The handler that is called when the secondary window sends a message
  ymessenger.SetEventHandler("SecondaryWindowMessage", SecondaryWindowMessageHandler);
  function SecondaryWindowMessageHandler(msg)
  {
    if (! msg)
      return;

    if (msg.indexOf(":") < 0)
      return;

    var msgtype = msg.split(":")[0];
    switch (msgtype)
    {
  	case "GDU":
  	  // XXX: ck_value currently unused
  	  var ck_value = msg.split(":")[1];
  	  ToggleTagGroupDisplay(msg.split(":")[2]);
  	  break;
  	default:
  	  GeoAlert(0, "[YIMSWMH] Unimplemented msgtype("+msgtype+")");
    }
  }

  // OK, primary window is ready to start receiving events (means all event
  // handlers have been registered)
  ymessenger.LocalReady();

  // Initialize the map
  InitializeMainPage(mapcontainer, uid, upw, dtype, true);

  // Now start getting IMs
  GetInstantMessages();
}

// Generic function called when "Tag Groups" clicked in
// yimprimarywindow.php to open secondary window. All this function does is
// open the secondary window and display the contents of
// yimsecondarywindow.php.
function OpenYahooMessengerSecondaryWindow()
{
  // Now actually open the secondary window and get the following URL
  var yim_sw_url = yahooimsecondarywin_file;

  if (ymessenger)
    ymessenger.SecondaryWindowOpenWithDimensions(yim_sw_url, 327, 428, "Powered by "+COMPANY_NAME+".");
}
/////////////////////////// YIM Primary Window Code //////////////////////////////
///////////////////////////-------------------------//////////////////////////////

///////////////////////////---------------------------////////////////////////////
/////////////////////////// YIM Secondary Window Code ////////////////////////////
//
// Called by yimsecondarywindow.php when it loads. Use this function to
// register secondary window event handlers and do whatever the secondary
// window needs to do on startup
function LoadYahooMessengerSecondaryWindow(u)
{
  uid = u;
  dtype = 'ym';

  // Pointer to secondary window object
  ymessenger = window.external;

  // The secondary window is ready to start receiving events
  ymessenger.LocalReady();
}

function YIMUpdateTagGroupDisplay(gid, chk_val)
{
  if (chk_val)
    YIMSendMessageToPrimaryWindow("GDU:Y:"+gid);
  else
    YIMSendMessageToPrimaryWindow("GDU:N:"+gid);
}

function YIMSendMessageToPrimaryWindow(msg)
{
  if (ymessenger)
    ymessenger.SendMessageToMainPluginWindow(msg);
}

/////////////////////////// YIM Secondary Window Code ////////////////////////////
///////////////////////////---------------------------////////////////////////////

//////////////////////////////// YIM Stuf ////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
// TODO: these function names need to be more descriptive
function startLoading()
{
  Element.show('mainAreaLoading');
  Element.hide('mainAreaInternal');
}
	
function finishLoading() {
		
  Element.show('mainAreaInternal');
  setTimeout("Effect.toggle('mainAreaLoading');", 100);
}

function loadContent(id)
{
  startLoading();
  new Ajax.Updater('mainAreaInternal', 'rpc.php', {method: 'post'});
  finishLoading();
}
//////////////////////////////////////////////////////////////////////////////
function DisplayLocationHistory(mdevice)
{
  var doid = (mdevice) ? mdevice.value : -1;
  if (doid < 0)
  {
    GeoAlert(3, "No device to show location history for.");
    return;
  }

  var e = null;

  e = GetDOMElement("startyear");
  var syear = (e) ? e.value : null;
  e = GetDOMElement("startmonth");
  var smonth = (e) ? e.value : null;
  e = GetDOMElement("startday");
  var sday = (e) ? e.value : null;
  e = GetDOMElement("starthour");
  var stime = (e) ? e.value : null;
  var shour = (stime) ? stime.substr(0, 2) : null;
  var sminute = (stime) ? stime.substr(3, 2) : null;
  var ssecond=0;

  e = GetDOMElement("endyear");
  var eyear = (e) ? e.value : null;
  e = GetDOMElement("endmonth");
  var emonth = (e) ? e.value : null;
  e = GetDOMElement("endday");
  var eday = (e) ? e.value : null;
  e = GetDOMElement("endhour");
  var etime = (e) ? e.value : null;
  var ehour = (etime) ? etime.substr(0, 2) : null;
  var eminute = (etime) ? etime.substr(3, 2) : null;
  var esecond = 0;

  //   var eetime = etime.toUTCString();
  //   var eyear = etime.getUTCFullYear();
  //   var emonth = eval(etime.getUTCMonth()+1);	//as getMonth return month from 0 to 11
  //   var edate = etime.getUTCDate();
  //   var ehour = etime.getUTCHours();
  //   var eminute = etime.getUTCMinutes();

  var st_db = syear+"-"+smonth+"-"+sday+" "+shour+":"+sminute+":"+ssecond;
  var et_db = eyear+"-"+emonth+"-"+eday+" "+ehour+":"+eminute+":"+esecond;

  GeoAlert(12, "Show history from " + st_db + " to " + et_db + " for device " + doid);
  GetLocationHistory(doid, st_db, et_db, false);
}

// If this is an "incremental" location history search and the results have
// already been prefetched, this function will not call GetLocationHistory
// to get the results again - it will just display them. Otherwise it will
// call GetLocationHistory.
function ShowLocationHistory(direction)
{
  ClearErrorBox();
  RemoveInfoWindow();

  // "direction" has one of three values (-1, 0, 1). -1 means previous
  // results, 0 means same results and 1 means next results.

  var ci=loc_hist_data['current_start'];
  switch(direction)
  {
      case -1:
 	// Show the previous N results
 	if (ci == 0)
 	{
 	  GeoAlert(12, "Weird - the previous button should not have been displayed");
 	  return;
 	}
 	ci -= NUM_HISTORY_LOCATIONS;
 	if (ci < 0)
 	  ci = 0;
	
 	loc_hist_data['current_start'] = ci;
 	var mi = ci+NUM_HISTORY_LOCATIONS;
	
 	GeoAlert(12, "Drawing polyline for results " + ci + " to " + mi);
 	DrawPolylinesOrPins(loc_hist_data['points'], loc_hist_data['pointname'], ci, mi);
 	DrawHistoryControls(ci+1, ci+NUM_HISTORY_LOCATIONS, loc_hist_data['total_results']);
 	break;

      case 0:
 	// Show the same N results
 	var mi = ci+NUM_HISTORY_LOCATIONS;
 	if (mi > loc_hist_data['max_index'])
 	  mi = loc_hist_data['max_index'];
	
 	GeoAlert(12, "Drawing polyline for results " + ci + " to " + mi);
 	DrawPolylinesOrPins(loc_hist_data['points'], loc_hist_data['pointname'], ci, mi);
 	DrawHistoryControls(ci+1, ci+NUM_HISTORY_LOCATIONS, loc_hist_data['total_results']);
 	break;

      case 1:
 	// Show the next N results
 	ci = ci + NUM_HISTORY_LOCATIONS;
 	loc_hist_data['current_start'] = ci;
	
 	if (ci >= loc_hist_data['max_index'])
 	{
 	  // Being asked to get next set of results and this is the latest
 	  // we have, so get them from the server.
 	  GetLocationHistory(loc_hist_data['doid'], loc_hist_data['end_time'], loc_hist_data['qet'], true);
 	}
 	else
 	{
 	  // Coolio, Julio. We are being asked to get next set of results
 	  // and we should already have them. So just display them.
 	  var mi = ci + NUM_HISTORY_LOCATIONS;
 	  if (mi > loc_hist_data['max_index'])
 	    mi = loc_hist_data['max_index'];
	
 	  GeoAlert(12, "Drawing polyline for results " + ci + " to " + mi);
 	  DrawPolylinesOrPins(loc_hist_data['points'], loc_hist_data['pointname'], ci, mi);
 	  DrawHistoryControls(ci+1, mi, loc_hist_data['total_results']);
 	}
 	break;
      default:
 	GeoAlert(0, "Invalid value.");
 	break;
  }
}

function GetLocationHistory(doid, stime, etime, incr)
{
  ClearErrorBox();
  loc_hist_data['incr'] = incr;
  if (! incr)
  {
    loc_hist_data['doid'] = doid;
    loc_hist_data['qst'] = stime;
    loc_hist_data['qet'] = etime;
  }

  var gh_url = get_loc_hist_url_base + "i=" + uid + "&c=" + upw + "&did=" + doid + "&st=" + stime + "&et=" + etime;
  GeoAlert(12, "[GLH] Sending request: " + gh_url);

  var ghai = new AJAXInteraction(gh_url, ParseGetLocationHistoryResults);
  if (ghai)
    ghai.Get();
}

function ParseGetLocationHistoryResults(rstr)
{
  var json = GetJson(rstr);
  var totallocs = (json) ? json.totallocations : 0;
  var tnum = (json && json.location) ? json.location.length : 0;
  GeoAlert(12, "[PGLHR] Got back " + tnum + " responses");
  DeleteAllMapShapes(main_map['map']);

  if (tnum <= 0)
  {
    DisplayBoxError("No record of your locations in that time frame!");
    return;
  }

  if (loc_hist_data['incr'] == false)
  {
    GeoAlert(12, totallocs+" locations in that time frame. Will display only "+tnum);

    // Since this is a new search, create a new array of
    // points. The old will be (hopefully) garbage collected
    // when the reference to it is dropped.
    loc_hist_data['points'] = null;
    loc_hist_data['points'] = new Array(totallocs);
    loc_hist_data['pointname'] = null;
    loc_hist_data['pointname'] = new Array(totallocs);
    loc_hist_data['total_results'] = totallocs;
    loc_hist_data['current_start'] = 0;
    loc_hist_data['max_index'] = 0;

    loc_hist_data['gid'] = json.gid;
    loc_hist_data['icon'] = json.grpicon;
    loc_hist_data['did'] = json.did;
  }

  var index = loc_hist_data['max_index'];
  var ci = index;
  var tnow = GMTDate();

  for (var i=0; i<tnum; i++)
  {
    var t = json.location[i].time;
    var lat = json.location[i].latitude;
    var lon = json.location[i].longitude;
    var alt = json.location[i].altitude;
    var tdiff_str = DateDifference(t, tnow);

    loc_hist_data['points'][index] = NewMarker(lat, lon, null, null, "yellow");
    loc_hist_data['pointname'][index] = "<b>My Location</b><br>" + tdiff_str;

    if (i == (tnum-1))
    {
      loc_hist_data['end_time'] = t;
    }

    index++;
  }
  if (loc_hist_data['max_index'] < index)
    loc_hist_data['max_index'] = index;

  GeoAlert(12, "Going to draw points/polyline for indices " + ci + " to " + index);
  DrawPolylinesOrPins(loc_hist_data['points'], loc_hist_data['pointname'], ci, index);
  DrawHistoryControls(index-tnum+1, index, loc_hist_data['total_results']);
}

function DrawPolylinesOrPins(lpoints, lnames, si, ei)
{
  var points = new Array(ei-si);
  var index=0;
  for (var i=si; i<ei; i++)
  {
    points[index] = lpoints[i];
    index++;
  }

  var shape_type = null;
  var s = (document) ? (document.mapshapeselector)?document.mapshapeselector.mapshapetype:null : null;

  if (s)
  {
    for (var i=0; i<s.length; i++)
      if (s[i].checked)
 	shape_type = s[i].value;
  }

  // Clear existing shapes
  DeleteAllMapShapes(main_map['map']);
  //DeleteAllPolylines(main_map['map']);

  if (shape_type == "polyline")
  {
    var color = NewMapColor(255,0,0,1);
    var width=5;
    var id='171';

    GeoAlert(12, "[DPoP] Drawing polyline");
    var poly = NewMapPolyline(id, points, color, width);
    // XXXX: have to delete old polylines before new one can be added
    AddMapPolyline(main_map['map'], poly);
    SetMapView(main_map['map'], points);
  }
  else
  {
    //DeleteAllShapes(main_map['map']);
    GeoAlert(12, "[DPoP] Drawing " + index + " points (" + si + " to " + ei + ")");
    var ni = 0;
    for (var ii=0; ii<index; ii++)
    {
      ni = si+ii;
      if(MSFT==1)
	AddLatLonPin(loc_hist_data['gid'], loc_hist_data['did'], points[ii], lnames[ni], loc_hist_data['icon'], 0);
      else
	AddLatLonPin(loc_hist_data['gid'], loc_hist_data['did'], points[ii].getPoint(), lnames[ni], loc_hist_data['icon'], 0, null, null, 1);
    }
    // Since results are returned in order (latest location is
    // last), center map on last location
    if(MSFT==1)
      SetMapCenter(main_map['map'], loc_hist_data['points'][index-1]);
    else
    {
      // For Google we have to get the point because the array actually
      // contains marker objects, not just the point object
      SetMapCenter(main_map['map'], loc_hist_data['points'][index-1].getPoint());
    }
  }
}

function DrawHistoryControls(start, end, total)
{
  var html="";

  if (start > 1)
  {
    // Show "previous" arrows
    html += '<a class="lochistmoreresults" href="javascript:ShowLocationHistory(-1);"> << </a>';
  }

  html += '<span class="lochistmoreresults">Showing '+start+'-'+end+' of '+total+' results.</span>';

  if (end+1 < total)
  {
    // Show "next" arrows
    html += '<a class="lochistmoreresults" href="javascript:ShowLocationHistory(1);"> >> </a>';
  }

  var histCtrl = GetDOMElement("historyControl");
  if(!(histCtrl))
    histCtrl = CreateHistoryControlBox();

  if (histCtrl)
    histCtrl.innerHTML = html;

  //histCtrl.style.top = "325px";	
}

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

  div.setAttribute('id','historyControl');
  div.setAttribute('name','historyControl');
  div.style.position='absolute';
  div.style.width='260px';
  div.style.left = "110px";
  div.style.border = "solid";
  div.style.borderWidth = "thin";
  div.style.fontFamily = "Arial";
  div.style.fontSize = "11px";
  div.style.backgroundColor = "white";
  div.style.height = "20px";
  div.style.textAlign = "center";
  div.style.marginTop = "285px";	
  if(GetDOMElement('mapcontainer'))
    GetDOMElement('mapcontainer').appendChild(div);

  return div;
}

function DisplayHistoryAtLocation(mdevice)
{
  RemoveInfoWindow();

  var doid = (mdevice) ? mdevice.value : -1;
  if (doid < 0)
  {
    GeoAlert(3, "No device to show location history for.");
    return;
  }

  GetMapView();
  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 gh_url = get_hist_at_loc_url_base + "i=" + uid + "&c=" + upw + "&dtype=" + dtype + "&did=" + doid;
  gh_url += "&tla=" + tllat + "&tlo=" + tllon + "&bra=" + brlat + "&bro=" + brlon;

  GeoAlert(12, "[DHAL] Sending request: " + gh_url);

  var ghai = new AJAXInteraction(gh_url, ParseGetHistoryAtLocationResults);
  if (ghai)
    ghai.Get();
}

function ParseGetHistoryAtLocationResults(rstr)
{
  var tnum = str_num_occurrences(rstr, "<Location>");
  GeoAlert(10, "[PGHALR] Got back " + tnum + " responses");
  DeleteAllMapShapes(main_map['map']);

  if (tnum <= 0)
  {
    DisplayBoxError("No record of your locations in that area. Zoomout map and try again.");
    return;
  }

  var gid = nth_xml_tag(rstr, "gid", 0);
  var icon = nth_xml_tag(rstr, "grpicon", 0);
  var did = nth_xml_tag(rstr, "did", 0);
  var tnow = GMTDate();

  for (var i=0; i<tnum; i++)
  {
    var t = nth_xml_tag(rstr, "Time", i);
    var lat = nth_xml_tag(rstr, "Latitude", i);
    var lon = nth_xml_tag(rstr, "Longitude", i);
    var alt = nth_xml_tag(rstr, "Altitude", i);
    var tdiff_str = DateDifference(t, tnow);

    var ll = NewLatLongPoint(lat, lon);
    AddLatLonPin(gid, did, ll, tdiff_str, icon, 0, null, null, 1);
  }
}

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

function UpdateAd()
{
  var lat = GetDOMElementValue('taglatname');
  var lon = GetDOMElementValue('taglonname');
  var alt = GetDOMElement('tagaltname');
  alt = (alt) ? alt.value : 0;
  var adTxt = GetDOMElementValue('adTxt');
  var adThumb = GetDOMElementValue('adThumb');
  var adImg = GetDOMElementValue('adImg');
  var adVid = GetDOMElementValue('adVid');

  if (!adTxt && !adThumb && !adImg && !adVid)
  {
    CancelTagUpdate();
    DisplayBoxError("You need to specify either text or a thumbnail or an image for a video for the ad.");
    return;
  }

  var au_url = ad_update_url_base + "i=" + uid + "&c=" + upw + "&lat="+lat+ "&lon="+lon+ "&alt="+alt;
  if (adTxt)
    au_url += "&adtxt="+encodeURI(adTxt);
  if (adThumb)

    au_url += "&adthumb="+encodeURI(adThumb);
  if (adImg)
    au_url += "&adimg="+encodeURI(adImg);
  if (adVid)
    au_url += "&advid="+encodeURI(adVid);

  var auai = new AJAXInteraction(au_url, ParseUpdatedAdInformationResponse);
  if (auai)
    auai.Get();

  // Call cancel to dismiss the tag update box
  CancelTagUpdate();
}

function ParseUpdatedAdInformationResponse(rstr)
{
  if (rstr)
    DisplayBoxError(nth_xml_tag(rstr, "status", 0));
}

function PrepareTagUpdateUrlString(includeNoBasis, forupdatetag)
{
  var lat = GetDOMElementValue('taglatname');
  var lon = GetDOMElementValue('taglonname');
  var alt = GetDOMElement('tagaltname');
  alt = (alt) ? alt.value : 0;

  var GraffitiText = GetDOMElementValue('txtTagDesc');
  var GraffitiImg = GetDOMElementValue('txtTagImg');
  var GraffitiLink = GetDOMElementValue('txtTagLinkUrl');
  var GraffitiAlert = (GetDOMElement('alerttypetag')) ? GetDOMElement('alerttypetag').checked : null;
  var GraffitiAddress = GetDOMElementValue('GraffitiAddress');
  var GraffitiStar = GetDOMElementValue('ratingstar');

  var gId = GetDOMElementValue('tagwallslist');
  if (!gId) gId = GetDOMElementValue('tagwallslist2');
  if (!gId) gId = GetDOMElementValue('grpid');

  var gName = GetDOMElementValue('newgrpname');
  var gDesc = GetDOMElementValue('newgrpdesc');
  var nBizId = GetDOMElementValue('tagbizlist');
  var fileName = (GraffitiImg) ? (GraffitiImg.substr(eval(GraffitiImg.lastIndexOf("\\")+1), GraffitiImg.length)) : "";
  var rand = GetDOMElementValue('hdnrand');
  if (!rand) rand = 0;
  nBizId = (nBizId) ? nBizId+"_" : null;

  if (!GraffitiText && fileName=="" && GraffitiLink=="" && GraffitiStar<0)
  {
    CancelTagUpdate();
    DisplayBoxError("You need to enter some kind of graffiti.");
    return null;
  }

  if (gId <= 0 && !gName)
  {
    CancelTagUpdate();
    DisplayBoxError("You need to specify a name for the new wall.");
    return;
  }

  var tu_url = (!(includeNoBasis)) ? tag_update_url_base + "i=" + uid + "&c=" + upw : "";
//  tu_url += (main_map['type']==SIMPLE_MAP) ? "&isSimpleMap=1" : "";
  tu_url += "&lat="+lat+ "&lon="+lon+ "&alt="+alt + "&rand="+rand;
  if (tdg_oid && tdg_oid > 0)
    tu_url += "&oid="+tdg_oid;

  tu_url += "&gid="+gId;
  if(nBizId && nBizId != "")
    tu_url += "&tagbizlist="+nBizId;
  if (gName && gName != "")
    tu_url += "&gname="+encodeURI(gName);
  if (gDesc && gDesc != "")
    tu_url += "&gdesc="+encodeURI(gDesc);
  if(GraffitiText && GraffitiText != "")
    tu_url += "&GraffitiText="+encodeURI(GraffitiText);
  if(fileName && fileName != "")
    tu_url += "&fileName="+fileName;
  if(GraffitiLink && GraffitiLink != "")
    tu_url += "&GraffitiLink="+encodeURI(GraffitiLink);
  if(forupdatetag && GetDOMElement('alerttypetag'))
  {
    if(GraffitiAlert)
      tu_url += "&GraffitiAlert=enabled";
    else
      tu_url += "&GraffitiAlert=disabled";
  }
  else
  {
    if(GraffitiAlert && GraffitiAlert != "")
      tu_url += "&GraffitiAlert=enabled";
  }
  	
  if(GraffitiAddress && GraffitiAddress!="")
    tu_url += "&GraffitiAddress="+encodeURI(GraffitiAddress);
  if(GraffitiStar || GraffitiStar==0)
    tu_url += "&GraffitiStar="+GraffitiStar;

  return tu_url;
}

function UpdateTag()
{
  // TODO: the information that is updated needs to be displayed in the tag
  // popup!!

  var tu_url = PrepareTagUpdateUrlString();
  if (!tu_url)
    return false;

  var tuai = new AJAXInteraction(tu_url, ParseUpdatedTagInformationResponse);
  if (tuai)
    tuai.Get();

  // Call cancel to dismiss the tag update box
  CancelTagUpdate();
}

function ParseUpdatedTagInformationResponse(rstr)
{
  if (rstr)
    DisplayBoxError(nth_xml_tag(rstr, "status", 0));

  UpdateDisplayOfAllGroupTags();
}

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 ShowWallCreationDialog(step, existingwall)
{
  CreateGrayOverlay();

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

  var html = "";	
  html = (existingwall) ? GetPopupHTML(null, 'existingwallquestion') : GetPopupHTML(null, 'createwall');

  if(step && step==1)
  {
    mbox.style.top = '200px';
    html += "Use your Facebook network to help add graffiti to this wall?<br>";
    html += "<br><a href='javascript:void(0)' onClick='CancelTagUpdate(); ";
    html += (existingwall) ? "'>" : "if(GetDOMElement(\"groupsearchcreateform\"))  {GetDOMElement(\"groupsearchcreateform\").submit();}'>";
    html += "<img src='"+IMAGE_URL_BASE+"button_no_small.png' /></a><a href='javascript:void(0)' onClick='ShowWallCreationDialog(2, "+existingwall+");'><img src='"+IMAGE_URL_BASE+"button_yes_small.png'/>";
  }
  if(step && step==2)
  {
    mbox.style.top = '180px';
    html += "Enter the question that you want your social network to see:<br><textarea id='Question' name='Question' rows=3 cols=65></textarea>";
    html += "<br><a href='javascript:void(0)' onClick='CancelTagUpdate(); ";
    html += (existingwall) ? "'>" : " if(GetDOMElement(\"groupsearchcreateform\"))  {GetDOMElement(\"groupsearchcreateform\").submit();}'> ";
    html += "<img src='"+IMAGE_URL_BASE+"button_cancel.png' /></a><a href='javascript:void(0)' onClick='Question=GetDOMElementValue(\"Question\");";
    html += (existingwall) ? " SetDOMElementValue(\"postedQuestion\", Question); if(GetDOMElement(\"frmPostWallQuestion\"))  {GetDOMElement(\"frmPostWallQuestion\").submit();} '>": "ShowWallCreationDialog(3);'> ";
    html += (existingwall) ? "<img src='"+IMAGE_URL_BASE+"button_submit.png'/> " : "<img  src='"+IMAGE_URL_BASE+"button_continue.png'/> ";
  }
  if(step && step==3)
  {
    var form = GetDOMElement("groupsearchcreateform");
    if(form)
    {
      form.txtQuestion.value = Question;
    }
    mbox.style.top = '160px';	
    html += "Make the wall publicly accessible?<br>";
    html += "<br><a href='javascript:void(0)' onClick='document.getElementById(\"txtQuestion\").value=\"\";CancelTagUpdate(); if(GetDOMElement(\"groupsearchcreateform\")) {GetDOMElement(\"groupsearchcreateform\").submit();}'>";
    html += "<img src='"+IMAGE_URL_BASE+"button_cancel.png' /></a><a href='javascript:void(0)' onClick='CancelTagUpdate();Question=null;GetDOMElement(\"groupsearchcreateform\").submit();'><img  src='"+IMAGE_URL_BASE+"button_submit.png'/>";
  }

  html += "</a></div></div></div></div></div></div></div></div></div>";
  SetDOMElementInnerHtml('mbox', html);
}

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 ViewUserLocationTemporarily(access_code)
{
  if (!access_code)
  {
    DisplayBoxError("Internal error. Unable to display location. Sorry.");
    return;
  }

  // Now build the request to send out - use the same functions to read the
  // response as the functions used on the search.php page to display
  // moving object location. The only difference is that the outgoing
  // request is to a different url on the server - one that accepts an
  // access code in lieu of a uid and password.
  var vl_url = view_tmp_loc_url_base + "acode=" + access_code;
  GeoAlert(16, "[ViewUserLocationTemporarily] Sending request: " + vl_url);

  var vlai = new AJAXInteraction(vl_url, ParseGetObjectLocationResults);
  if (vlai)
    vlai.Get();
}

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 AddNewQueryAd(nkeyid, nadid, clatid, clonid, tllatid, tllonid, brlatid, brlonid, zoomid)
{
  var nkey = GetDOMElement(nkeyid);
  var nad = GetDOMElement(nadid);
  if (!nkey || !nad)
    return false;

  if (!nkey.value || nkey.value=="" || !nad.value || nad.value=="")
  {
    ShowError("Please enter ad keywords and/or ad");
    return false;
  }

  SetMapDisplayedArea(clatid, clonid, tllatid, tllonid, brlatid, brlonid, zoomid);
  GetDOMElement('biznewad').submit();
}

function ShowRecentBizQueries(keyword_field)
{
  if (! keyword_field)
    return null;

  var kf = GetDOMElement(keyword_field);
  if (!kf)
    return null;

  var keywords = kf.value;
  if (! keywords)
  {
    GeoAlert(0, "Please enter new keywords to show searches for.");
    return null;
  }

  // TODO: send request to server to get locations of moving users
  // who did recent searches for the keywords the biz user has specified

  return null;
}

function ReloadPageWithParams(category, group_id, nextcolumn)
{
  var gg_url = get_wall_cat_url_base + "i=" + uid + "&c=" + upw;
  if (category && category != '')
  {
    gg_url += "&cat="+category;
    SetDOMElementValue("selCat", category);
    SetDOMElementValue("prvcyStng", "a");
    SetDOMElementValue("gid", "");
    SetDOMElementValue("req_grp_id", "");
  }
  if (group_id && group_id != '')
  {
    var cat = GetDOMElementValue("selCat");
    SetDOMElementValue("gid", group_id);
    SetDOMElementValue("req_grp_id", group_id);
    gg_url += "&cat="+cat+"&gid="+group_id;
  }
  if(nextcolumn)
    gg_url += "&nextcolumn="+nextcolumn;

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

function ParseGetWallTagResponse(rstr)
{
  var prvcyStng = GetDOMElementValue("prvcyStng");
  if(!prvcyStng)
    return;

  if (prvcyStng=="a")
  {
    SetDOMElementValue("prvcyStng", "1");
    SetDOMElementInnerHtml("prvcyStngDiv", "");
    // XXXX: IE does not support simple SetDOMElementInnerHtml("grpGroups", rstr); for select  box therefore adding a new function
    //       to work for IE and FF both
    FillComboInnerHTML("grpGroups", rstr);
  }
  else if(GetDOMElementValue('req_grp_id')!="")
  {
    SetDOMElementValue("prvcyStng", "1");
    SetDOMElementInnerHtml("prvcyStngDiv", rstr);

    // XXXX: This one is to auto select the wall from select list if user is coming from home.php for viewing wall settings
    var sel = GetDOMElement('grpGroups');
    for(i=0; i<sel.options.length; i++)
      if(parseInt(GetDOMElementValue("req_grp_id"))==parseInt(sel.options[i].value))
      {sel.options[i].selected = true; i=sel.options.length;}
  }
}

function FillComboInnerHTML(selcomboid, string)
{
  var selcombo = GetDOMElement(selcomboid);
  if (!selcombo)
    return;

  selcombo.innerHTML = "";
  string = "<sel>"+string+"</sel>";

  var xmlDoc = CreateDomDocumentObject(string);
  var optnum = xmlDoc.documentElement.getElementsByTagName("option").length;
  for(p=0; p<optnum; p++)
  {
    var node = xmlDoc.documentElement.getElementsByTagName("option")[p];
    var text = GetNodeInnerText(node);
    text = (text) ? text : "";
    var val = node.getAttribute("value");
    var option = document.createElement('option');
    option.appendChild(document.createTextNode(text));
    option.setAttribute('value', val);
    selcombo.appendChild(option);
  }
}

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

  var gn = GetDOMElement("createGroupName");
  var gd = GetDOMElement("createGroupDesc");
  var clat = GetDOMElement("clat");
  var clon = GetDOMElement("clon");

  if (!gn || gn.value=="")
  {
    ShowError("Enter name for wall");
    return null;
  }

  if(!main_map['lat'] && !main_map['lon']) ExtractMapViewFromCookie();
  if(clat && main_map['lat']) clat.value = main_map['lat'];
  if(clon && main_map['lon']) clon.value = main_map['lon'];

  ShowWallCreationDialog(1);
}

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 EditGroupTag(oid, graffitiid)
{
  if(!oid || !graffitiid)
    return null;

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

  var OwnerId = GetDOMElementValue('OwnerId'+graffitiid);
  var graffitigid = GetDOMElementValue('graffitigid'+graffitiid);
  var text = GetDOMElementValue('text'+graffitiid);
  var media = GetDOMElementValue('media'+graffitiid);
  media = (media) ? media.substr(0, media.indexOf("height"))+" height='100px'"+media.substr(media.indexOf("width"), media.len) : media;

  var hlnk = GetDOMElementValue('hlnk'+graffitiid);
  var alerttag = GetDOMElementValue('alert'+graffitiid);
//alert(OwnerId +", "+ graffitigid +", "+ text +", "+ media +", "+ hlnk +", "+ alerttag);
  var chkd = (alerttag=="enabled") ? "checked" : "";
  var desc = '<div style="height:20px;width:390px;background-color:#DEEA9B;color:#336600;text-align:center;padding-top:3px;">Update Graffiti</div><br/><br/><form style="height:180px;" name="frmPopUpGraffiti" method="post" action="'+tag_update_url_base+'i='+uid+'&c='+upw+'&forcenew=0" enctype="multipart/form-data" target="uploadResponseHandler"><table width="100%"><tr style="height:22px;"><td style="font-weight:normal; color:#bed63a;">Text</td><td><textarea type="text" name="txtTagDesc" id="txtTagDesc" cols="40" rows="1" style="height: 34px; width:350px;">'+text+'</textarea></td></tr><tr  style="height:22px;"><td style="font-weight:normal; color:#bed63a;">Image</td><td>'+media+'</td></tr><tr style="height:22px;"><td style="font-weight:normal; color:#bed63a;">URL</td><td><input type="text" name="txtTagLinkUrl" id="txtTagLinkUrl" style="width: 350px;" value="'+hlnk+'"/></td></tr><tr style="height:22px;"><td style="font-weight:normal; color:#bed63a;">Alert</td><td><input style="width:15px; margin-left:50px;" type="checkbox" name="alerttypetag"  id="alerttypetag" value="'+alerttag+'" onClick="if(this.checked) {this.value=\'enabled\'} else {this.value=\'disabled\'};" '+chkd+'/></td></tr></table><input type="hidden" name="tagwallslist2" id="tagwallslist2" value="'+graffitigid+'"><input type="hidden" name="oid" id="oid" value="'+oid+'" /><input type="hidden" id="graffitiid" name="graffitiid" value="'+graffitiid+'" /></form><div><a onclick="CancelTagUpdate();" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_cancel.png"/></a><a onclick="SubmitPopupTemplateForm(null, -1, 1)" href="javascript:void(0)"><img src="'+IMAGE_URL_BASE+'button_update.png"/></a></div><iframe id="uploadResponseHandler" name="uploadResponseHandler" style="height:0px; width:0px; display:none;"></iframe>';

  var html = GetPopupHTML(desc, 'edittag');
  if(mbox)
  {mbox.style.left = '350px';mbox.style.width = '420px';}

  SetDOMElementInnerHtml('mbox', html);
}

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 SortWallObjects(title)
{
  if(title=='rank')
  {
    SortWallObjectsRankWise();
    SetDOMElementInnerHtml('rankarrow', 'Rank <a href="Javascript:void(0)" title="Order By Rank" onclick="SortWallObjects(\'rank\');" style="text-decoration:none;"><img src="'+IMAGE_URL_BASE+'filled_arrow.png" /></a>');
    SetDOMElementInnerHtml('timearraow', 'Last Updated <a href="Javascript:void(0)" title="Order By Time Updated" onclick="SortWallObjects(\'time\');" style="text-decoration:none;"><img src="'+IMAGE_URL_BASE+'arrow.png" /></a>');
  }
  else if(title=='time')
  {
    SortWallObjectsTimeWise();
    SetDOMElementInnerHtml('rankarrow', 'Rank <a href="Javascript:void(0)" title="Order By Rank" onclick="SortWallObjects(\'rank\');" style="text-decoration:none;"><img src="'+IMAGE_URL_BASE+'arrow.png" /></a>');
    SetDOMElementInnerHtml('timearraow', 'Last Updated <a href="Javascript:void(0)" title="Order By Time Updated" onclick="SortWallObjects(\'time\');" style="text-decoration:none;"><img src="'+IMAGE_URL_BASE+'filled_arrow.png" /></a>');		
  }
}

function SortWallObjectsRankWise()
{
  var html = "";	
  for(var j=1; j<tagIndex; j++)
  {
    var innerhtml = GetDOMElementInnerHtml("wallObject"+j);
    var indx = j;
    if(GetDOMElement('wallObject'+indx))
    {
      var display = GetDOMElement('wallObject'+indx).style.display;
      display = (display) ? 'display:'+display+';' : "";
      html += "<div id='wallObject"+indx+"' style='font-size:8pt; font-family:Arial; text-align:left; padding-top:5px; padding-bottom:5px;"+display+"'  onmouseover='OpenInfoWindowForList("+indx+")'>"+ innerhtml +"</label></div>";
    }
  }
  SetDOMElementInnerHtml('dispWallGrftidiv', '');
  SetDOMElementInnerHtml('dispWallGrftidiv', html);
}

function SortWallObjectsTimeWise()
{
  //disp_tag_group_html;
  var html = "";
  var array = new Array();
  var ai = 0;
  for (var i=1; i<=tagIndex; i++)
  {
    var time = GetDOMElementValue('updatetime'+i);
    if(!time)
      continue;

    year = time.substr(0, time.indexOf('-'));
    time = time.substr(time.indexOf('-')+1, time.length);
    month = time.substr(0, time.indexOf('-'));
    time = time.substr(time.indexOf('-')+1, time.length);
    day = time.substr(0, time.indexOf(' '));
    time = time.substr(time.indexOf(' ')+1, time.length);
    h = time.substr(0, time.indexOf(':'));
    time = time.substr(time.indexOf(':')+1, time.length);
    m = time.substr(0, time.indexOf(':'));
    time = time.substr(time.indexOf(':')+1, time.length);
    s = time.substr(0, time.length);
    var date = new Date(year,month,day,h,m,s);
    if(GetDOMElement('wallObject'+i))
    {
      array[ai] = new Array(i, date);
      ai++;
    }
  }

  if(array && array.length>0)
  {
    for(var j=0; j<array.length; j++)
    {
      for(var k=j+1; k<array.length; k++)
      {
	if(array[j][1]<array[k][1])
	{
	  var indx = array[j][0];
	  array[j][0] = array[k][0];
	  array[k][0] = indx;
	  var maxT = array[j][1];
	  array[j][1] = array[k][1];
	  array[k][1] = maxT;
	}
      }
    }
    for(var j=0; j<array.length; j++)
    {
      var innerhtml = GetDOMElementInnerHtml("wallObject"+array[j][0]);
      var indx = array[j][0];
      html += "<div id='wallObject"+indx+"' style='font-size:8pt; font-family:Arial; text-align:left; padding-top:5px; padding-bottom:5px;'  onmouseover='OpenInfoWindowForList("+indx+")'>"+ innerhtml +"</div>";
    }
  }

  SetDOMElementInnerHtml('dispWallGrftidiv', '');
  SetDOMElementInnerHtml('dispWallGrftidiv', html);
}

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'))
  {
    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)
    {
      SetDOMElementInnerHtml('detailsummary', '<div style="background-image:url('+LOADING_GIF+'); width:220px; height:19px; margin-top:200px; margin-left:150px;"></div>');
      if(isreview)
	url = MAIN_URL_BASE+'review_dropdown.php?req=1';
      else
      	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";
      var ggai = new AJAXInteraction(url, FillLocalliteSummaryWithResponseHtml);
      ggai.Get();
    }
  }
  SetMarqueeTimeout();  
}

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

function LocalliteBusinessSearch()
{
  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();
    }
    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)
{
  SetMarqueeTimeout();
  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'));
  SetMarqueeTimeout();
}

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);
  SetMarqueeTimeout();

  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)
{
  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 : "";

  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);
  SetMarqueeTimeout();
}

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(1);
	}
	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);');
}