/*
 * Production javascript
 *
 * Copyright (c) 2008 Vidteq India Pvt Ltd
 * and GPL (GPL-LICENSE.txt) licenses.MSI
 *
 * $Rev: $
 */

function addOnLayer(layerObj,tabObj,legendObj) {
  this.layerRef = layerObj;
  this.tab = tabObj;
  if (legendObj) this.legendTab = legendObj;
  //this.tab.panel_div.title=this.layerRef.tabTitle;
}

addOnLayer.prototype.toggleTab = function () {
  if(this.tab.active==null || ! this.tab.active){
    this.tab.activate();
    this.addLayer();
    if (this.legendTab) this.addLegend();
  } else if(this.tab.active) {
    this.tab.deactivate();
    this.removeLayer();
    if (this.legendTab) this.removeLegend();
  }
  //this.updateClearButton();  // TBD need a mechanism to claer
}

addOnLayer.prototype.addLayer = function() {
  this.layer = new OpenLayers.Layer.WMS(this.layerRef.name,
    this.layerRef.url,
    this.layerRef.layerDetails,
    this.layerRef.layerConfig
  );
  if (this.layerRef.loadstart && this.layer)
    this.layer.events.register("loadstart",mboxObj,this.layerRef.loadstart);
  if (this.layerRef.loadend)
    this.layer.events.register("loadend",mboxObj,this.layerRef.loadend);
  //else 
  //  this.layer.events.register("loadend",ioAreaObj,function () { ioAreaObj.displayMessage(this.layerRef.statusName+" is loaded"); });
  //this.map.setCenter(new OpenLayers.LonLat(globalLon, globalLat), globalZoom);
  // TBD loaded 
  mboxObj.map.addLayer(this.layer);
  if (this.layerRef.wfsLoader) this.layerRef.wfsLoader();
  ioAreaObj.displayMessage(this.layerRef.statusName+" is loaded");
}

addOnLayer.prototype.addLegend = function() {
  if (this.legendTab.panel_div) this.legendTab.panel_div.style.display='block';
  if (! mboxObj.legendPanel.active) {
    mboxObj.legendPanel.addControls(this.legendTab);
    mboxObj.map.addControl(mboxObj.legendPanel);
    mboxObj.legendPanel.div.style.top = '30px';
    if (this.layerRef.legendTitle) this.legendTab.panel_div.title=this.layerRef.legendTitle;
    // TBD not finding symmetric removal, is there a memory leak
  }
  this.legendTab.activate();
}

addOnLayer.prototype.removeLegend = function() {
  if (this.legendTab.panel_div) this.legendTab.panel_div.style.display='none';
  if (this.legendTab.active) this.legendTab.deactivate();
}

addOnLayer.prototype.removeLayer = function() {
  mboxObj.map.removeLayer(this.layer);
  this.layer=null;
  if (this.layerRef.wfsUnloader) this.layerRef.wfsUnloader();
  ioAreaObj.displayMessage(this.layerRef.statusName+" is cleared");
}

addOnLayer.prototype.clearLayer = function () {
  if(this.tab.active) {
    this.tab.deactivate();
    this.removeLayer();
    if (this.legendTab) this.removeLegend();
  }
}

//var carImageUrl = 'images/car.png';
//var imageDoiIconUrl = imagePathsObj.doi;
//var imagePoiIconUrl = imagePathsObj.poi;
//var imageBusStopIconUrl = imagePathsObj.biasstops;
var globalLon = 77.6;
var globalLat = 12.96;
var globalZoom = 10;

function mbox(mapDom,viewPort,goVidClickAttach) {
  this.mapDom = mapDom;
  this.viewPort = viewPort;
  this.goVidClickAttach = goVidClickAttach;
  this.routeActive = false;
  this.srfActive = false;
  this.srfZoomExt = [];
  this.placeViaBallFlag=false;
  this.enableCarDisplay = false;
  this.startIcon = {
    //mapUrl : startIconUrl,
    //fvtUrl : startIconUrl,
    mapUrl : imagePathsObj.startIconUrl,
    fvtUrl : imagePathsObj.startIconUrl,
    mapStyle : "cursor:pointer;",
    fvtStyle : "cursor:pointer;",
    size : 32,
    title : 'Start Place'
  };
  this.endIcon = {
    //mapUrl : endIconUrl,
    //fvtUrl : endIconUrl,
    mapUrl : imagePathsObj.endIconUrl,
    fvtUrl : imagePathsObj.endIconUrl,
    mapStyle : "cursor:pointer;",
    fvtStyle : "cursor:pointer;",
    size : 32,
    title : 'End Place'
  };

  this.routeStyle = OpenLayers.Util.applyDefaults({
    strokeWidth: 8,
    cursor:'hand',
    strokeColor: "#9900CC",
    fillOpacity: 0,
    strokeOpacity: .6
    }, OpenLayers.Feature.Vector.style['default']);
  this.routeNoVidStyle = OpenLayers.Util.applyDefaults({
        strokeWidth: 5,
        strokeColor: "red",
        fillOpacity: 0,
        strokeOpacity: .6
    }, OpenLayers.Feature.Vector.style['default']);
  this.routeNoVbStyle = OpenLayers.Util.applyDefaults({
        strokeWidth: 5,
        strokeColor: "orange",
        fillOpacity: 0,
        strokeOpacity: .6
    }, OpenLayers.Feature.Vector.style['default']);
  this.routeNoDpStyle = OpenLayers.Util.applyDefaults({
        strokeWidth: 5,
        strokeColor: "blue",
        fillOpacity: 0,
        strokeOpacity: .6
    }, OpenLayers.Feature.Vector.style['default']);
  this.clickPointStyle = OpenLayers.Util.applyDefaults({
        strokeWidth: 5,
        strokeColor: mainColor,
        fillOpacity: 0,
        pointRadius:1,
        strokeOpacity: .9
    }, OpenLayers.Feature.Vector.style['default']);
  this.viaBallStyle = OpenLayers.Util.applyDefaults({
        strokeWidth: 8,
        strokeColor: 'black',
        fillOpacity: 0,
        pointRadius:1,
        strokeOpacity: .9
    }, OpenLayers.Feature.Vector.style['default']);
  //this.routeEnds = new routeEnds();
  this.init();
}

mbox.prototype.overrideOLClasses=function () {
  OpenLayers.Handler.Marker = OpenLayers.Class(OpenLayers.Handler.Feature, {
    handle: function(evt) {
      var type = evt.type;
      var node = OpenLayers.Event.element(evt);
      var feature = null;
      for (var i=0; i<this.layer.markers.length; i++) {
        if (this.layer.markers[i].icon.imageDiv.firstChild == node) {
          feature = this.layer.markers[i];
          break;
        }
      }
      var selected = false;
      if (feature) {
        if (this.geometryTypes == null) {
          // over a new, out of the last
          // over a new of still on the last
          if (!this.feature) {
            // over a nwe feature
            this.callback('over', [feature]);
          } else {
            // out of the last and over a new
            this.callback('out', [this.feature]);
            this.callback('over', [feature]);
          }
          this.feature = feature;
          this.callback(type, [feature]);
          selected = true;
        } else {
          if (this.feature && (this.feature != feature)) {
            // out of the last and over a new
            this.callback('out', [this.feature]);
            this.feature = null;
          }
          selected = false;
        }
      } else {
        if (this.feature) {
          // out of the last
          this.callback('out', [this.feature]);
          this.feature = null;
        }
        selected = false;
      }
      return selected;
    },
    CLASS_NAME: "OpenLayers.Handler.Marker"
  });
  OpenLayers.Control.DragMarker = OpenLayers.Class(OpenLayers.Control.DragFeature, {
      initialize: function(layer, options) {
      OpenLayers.Control.prototype.initialize.apply( this, [options] );
      this.layer = layer;
      this.handlers = {
        drag: new OpenLayers.Handler.Drag(
          this, OpenLayers.Util.extend({
            down: this.downFeature,
            move: this.moveFeature,
            up:   this.upFeature,
            out:  this.outCancel,
            done: this.doneDragging
          }, this.dragCallbacks
          )
        ),
        feature: new OpenLayers.Handler.Marker(
          this, this.layer, OpenLayers.Util.extend({
            over: this.overFeature,
            out:  this.outFeature
          }, this.featureCallbacks
          ), {
            geometryTypes: this.geometryTypes
          }
        )
      };
    } ,
    moveFeature: function(pixel) {
      var px = this.feature.icon.px.add(pixel.x - this.lastPixel.x, pixel.y - this.lastPixel.y);
      this.feature.moveTo(px);
      this.lastPixel = pixel;
      this.onDrag(this.feature.pixel);
    },
    CLASS_NAME: "OpenLayers.Control.DragMarker"
  });
  OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
       'single': true,
       'double': false,
       'pixelTolerance': 0,
       'stopSingle': false,
       'stopDouble': false
    },
    initialize: function(options) {
      this.handlerOptions = OpenLayers.Util.extend(
        {}, this.defaultHandlerOptions
      );
      OpenLayers.Control.prototype.initialize.apply(
        this, arguments
      );
      this.handler = new OpenLayers.Handler.Click(
        this, {
          'click': this.trigger
        }, this.handlerOptions
      );
    },
    trigger: function(e) {
      mboxObj.killRcmPopup.apply(mboxObj,[]);
      if (mboxObj.imagetab.active) { mboxObj.popupWfsLayer.apply(mboxObj,[e]) }
      if(__experimentalUI) closeAnyDropDowns();
      return true;
    }
  });
  OpenLayers.Control.DblClick = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
       'single': false,
       'double': true,
       'pixelTolerance': 0,
       'stopSingle': false,
       'stopDouble': false
    },
    initialize: function(options) {
      this.handlerOptions = OpenLayers.Util.extend(
        {}, this.defaultHandlerOptions
      );
      OpenLayers.Control.prototype.initialize.apply(
        this, arguments
      );
      this.handler = new OpenLayers.Handler.Click(
        this, {
          'dblclick': this.trigger
        }, this.handlerOptions
      );
    },
    trigger: function(evt) {
       mboxObj.killRcmPopup.apply(mboxObj,[]);
       if(typeof(__experimentalUI)!='undefined' && __experimentalUI) closeAnyDropDowns();
        return false;
   }
  });
}   
var myZoomis;
mbox.prototype.init = function () {
  try {
    if(ioAreaObj.embed) { } else {
    	if (self.navigator.userAgent.match(/MSIE\s[68]/)){//switch for disabling the Cat Scroll Panel in case of MSIE
    	 $("#scrolltabv").css('display','none');
    	 $("#scrolltabv_title").css('display','none');
    	}else{
    	 attachClicksToCatagory();
         attachClicksToUpDown();
    	}
    }
  } catch(e) {};
  this.overrideOLClasses();     
  this.locatorPoint = new Array();
  this.allMarkers = new Array();
  this.carImageSize = new OpenLayers.Size(24,24);
  this.viaBallSize = new OpenLayers.Size(24,24);
  this.carOffset = function(size) {
     return new OpenLayers.Pixel(-(size.w/2),-(size.h/2));
  };
  this.imageIconSize= new OpenLayers.Size(12,12);
  this.imageIconOffset= function(imageIconSize) {
     return new OpenLayers.Pixel(-(imageIconSize.w/2),-(imageIconSize.h/2));
  };
  this.viaBallIconUrl = imagePathsObj.viaBall;
  this.carImageUrl = imagePathsObj.car;
  this.imageDoiIconUrl = imagePathsObj.doi;
  this.imagePoiIconUrl = imagePathsObj.poi;
  this.imageBusStopIconUrl = imagePathsObj.biasstops;
  this.carIcon = new OpenLayers.Icon(this.carImageUrl,this.carImageSize,null,this.carOffset);
  this.imageDoiIcon = new OpenLayers.Icon(this.imageDoiIconUrl,this.imageIconSize,null,this.imageIconOffset);
  this.imagePoiIcon = new OpenLayers.Icon(this.imagePoiIconUrl,this.imageIconSize,null,this.imageIconOffset);
  this.imageBusStopIcon = new OpenLayers.Icon(this.imageBusStopIconUrl,this.imageIconSize,null,this.imageIconOffset);
  this.viaBallIcon = new OpenLayers.Icon(this.viaBallIconUrl,this.viaBallSize,null,this.imageIconOffset);
  OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
  // first map creation
  var mapOptions = {
    resolutions: [0.000686646,0.000343323, 0.000171661, 0.000085831, 0.000042915, 0.000021458, 0.00001072883606],
    maxExtent:new OpenLayers.Bounds (77.16796875,12.12890625,78.22265625,13.4478),
    fallThrough:true,
 //maxExtent:new OpenLayers.Bounds (77.43164063,12.74414063,77.78320313,13.18359375),
    controls: []
  }
  //console.log("one ...");
  this.map = new OpenLayers.Map( this.mapDom , mapOptions );
  //console.log("two ...");
  
  // now layer creation
  // layer index 1 - RCM click layer
  this.clickPointMark = new OpenLayers.Layer.Vector("Point Clicked",
    {style: this.clickPointStyle}
  );
  //console.log("three ...");
  this.map.addLayer(this.clickPointMark);
  //console.log("four ...");

    
  // layer index 2 - base layer
  this.baseLayer = new OpenLayers.Layer.WMS( "BANGALORE_ALL",
       tilecacheBaseUrl,
    { layers: tilecacheBaseLayer,
      format: 'image/png' },
    //{  attribution: '<div><a style=text-decoration:none;height:40px;width:80px;border:0px solid black; title="Visit www.VidTeq.com for detailed video maps." target=_blank style=cursor:pointer href="http://www.vidteq.com" ><img src="images/vidteq_map.png"; class=pngfixclass; height=40px; width=80px; style=border:0px solid black;text-decoration:none;height:40px;width:80px;background-color:transparent; /></a></div>',
    {  attribution: '<div><a style=text-decoration:none;height:40px;width:80px;border:0px solid black; title="Visit www.VidTeq.com for detailed video maps." target=_blank style=cursor:pointer href="http://www.vidteq.com" ><img src="'+imagePathsObj.vidteqMapLogo+'"; class=pngfixclass; height=40px; width=80px; style=border:0px solid black;text-decoration:none;height:40px;width:80px;background-color:transparent; /></a></div>',
       transitionEffect: 'resize',
       buffer: 0
    }
  );
  this.map.addLayer(this.baseLayer);
 
  //indexed at last
  myZoomis = this.map.getZoom();
  

  // layer index 3 - route layer
  this.route = new OpenLayers.Layer.Vector( "One route",
    {style: this.routeStyle}
  );
  //this.route.events.register('featureadded',this.route,function () {  });
  this.map.addLayer(this.route);
  // layer index 4 
  this.routeNoVid = new OpenLayers.Layer.Vector( "No Vid",
    {style: this.routeNoVidStyle}
  );
  this.map.addLayer(this.routeNoVid);

  // layer index 5 
  this.routeNoVb = new OpenLayers.Layer.Vector( "No VB",
    {style: this.routeNoVbStyle}
  );
  this.map.addLayer(this.routeNoVb);

  // layer index 6
  this.routeNoDp = new OpenLayers.Layer.Vector( "No VD",
    {style: this.routeNoDpStyle}
  );
  this.map.addLayer(this.routeNoDp);

  this.viaBallLayer = new OpenLayers.Layer.Vector("Via Ball",
    {style: this.viaBallStyle}
  );
  this.map.addLayer(this.viaBallLayer);
  
  this.carMarkLayer = new OpenLayers.Layer.Markers("Car Marker");
  this.carMarkLayer.div.style.zIndex='4000';
  this.map.addLayer(this.carMarkLayer);

  this.locationMarkLayer = new OpenLayers.Layer.Markers("Location Markers");
  this.map.addLayer(this.locationMarkLayer);

  this.viaBallMarkerLayer = new OpenLayers.Layer.Markers("Via Ball Markers");
  this.map.addLayer(this.viaBallMarkerLayer);

  this.textDirLayer=new OpenLayers.Layer.Markers("textdir");
  this.map.addLayer(this.textDirLayer);

  this.imageMarkers = new OpenLayers.Layer.Markers("images");
  this.map.addLayer(this.imageMarkers);
  
  this.busStopsLayer=new OpenLayers.Layer.Markers("Bus Stops Layer");
  this.map.addLayer(this.busStopsLayer);
  
  this.pfLayerMarkers= new OpenLayers.Layer.Markers("pfLayer Marker");
  this.map.addLayer(this.pfLayerMarkers);
  
  this.startEndMarkLayer = new OpenLayers.Layer.Markers("Start end markers");
  this.map.addLayer(this.startEndMarkLayer);    

  this.dragSE = new OpenLayers.Control.DragMarker(this.startEndMarkLayer,{
    'onComplete': function () {
    var markerIconType = this.feature.icon.url;
      if (markerIconType == "images/start.gif") {
        ioAreaObj.getRoadName(this.startMarker.lonlat,'start');
      } else if(markerIconType == "images/end.gif") {
        ioAreaObj.getRoadName(this.endMarker.lonlat,'end');
      }
    },
    'onStart': function () {
     //document.getElementById('loadname').style.display='block';
    }
  });
  this.dragCar = new OpenLayers.Control.DragMarker(this.carMarkLayer,{
    'onComplete': function (e) {
      if(e) {
        mboxObj.releaseCarAfterDrag.apply(mboxObj,[parseFloat(e.lonlat.lon),parseFloat(e.lonlat.lat)]);
      }
    },
    'onStart': function () {
      if(this.feature.icon.url == "images/car.png") {
        mboxObj.enableCarDisplay = false;
      }
    }
  });
  this.map.addControl(this.dragCar);
  this.dragCar.activate();
  this.parser = new OpenLayers.Format.WKT();
  this.tabPanel = new OpenLayers.Control.Panel();
  this.legendPanel = new OpenLayers.Control.Panel();
  this.addOnTabs = new Array();
  var videoLayer = {
    name : "BANGALORE_VIDEO",
    statusName : "Video Layer",
    url  : tilecacheVideoUrl, 
    layerDetails : { layers: tilecacheVideoLayer, format: 'image' },
    layerConfig : { visibility: true,
        isBaseLayer:false,
        transitionEffect: 'resize',
        opacity: .6,
        buffer: 0
    },
    tabTitle:"Highlights roads having the video coverage till date"
  }  
  var imageLayer = {
    name : "BANGALORE_POI_IMAGE",
    statusName : "Image Layer",
    url  : tilecacheImageUrl, 
    layerDetails : { layers: tilecacheImageLayer, format: 'image' },
    layerConfig : { visibility: true,
        isBaseLayer:false,
        transitionEffect: 'resize',
        buffer: 0
    },
    tabTitle:"Explore places of interest in Bengaluru",
    wfsLoader : function () { mboxObj.loadImageWfsLayer.apply(mboxObj,[]); }
  }  
  var biasLayer = {
    name : "BANGALORE_BIAS",
    statusName : "BIAS Layer",
    url  : tilecacheBiasUrl, 
    layerDetails : { layers: tilecacheBiasLayer, format: 'image' },
    layerConfig : { visibility: true,
        isBaseLayer:false,
        transitionEffect: 'resize',
        buffer: 0
    },
    tabTitle:"Explore the BIAS Routes in Bengaluru",
    legendTitle:"Legend for BIAS Routes",
    wfsLoader : function () { mboxObj.loadBiasWfsLayer.apply(mboxObj,[]); },
    wfsUnloader : function () { mboxObj.unloadBiasWfsLayer.apply(mboxObj,[]); },
    loadstart : function () { mboxObj.changeBaseLayerZoom.apply(mboxObj,[]); }
   }  
  ////ward Layer
  // var wardLayer = {
  //  name : "BANGALORE_WARDS",
  //  statusName : "WARD Layer",
  // // url  : 'http://10.4.71.100:8080/geoserver/wms?transparent=true',
  //  url  : 'http://10.4.71.200/cgi-bin/tilecache.cgi?', 
  //  
  // // url  : 'http://10.4.71.104/cgi-bin/mapserv1?map=/home/mapdata/siba/software/Map/bangalore_wards.map',
  //  layerDetails : { layers: 'BANGALORE_WARDS', format: 'image/png' },
  //  //    layerDetails : { layers: 'sde:bangalore_ward_zones', format: 'image/png' },

  //  //layerDetails : { layers: 'BANGALORE_WARDS', format: 'image/png' },
  //  layerConfig : { visibility: true,
  //      isBaseLayer:false,
  //      transitionEffect: 'resize',
  //      buffer: 0
  //  },
  //  tabTitle:"Explore the Wards of  Bengaluru",
  //  
  // // wfsLoader : function () { mboxObj.loadWardWfsLayer.apply(mboxObj,[]); },
  //  wfsUnloader : function () { mboxObj.unloadWardWfsLayer.apply(mboxObj,[]); },
  //  loadstart : function () { mboxObj.wardWfsLayerZoomChange.apply(mboxObj,[]); }
  //}  
  //this.videotab=new OpenLayers.Control.Button({displayClass: "videotab", trigger: function () { mboxObj.toggleVideotab.apply(mboxObj,[]); } });
  this.videotab=new OpenLayers.Control.Button({displayClass: "videotab", trigger: function () { mboxObj.toggleTab.apply(mboxObj,[mboxObj.videotab]); } });
  this.videotab.tabLayer = new addOnLayer(videoLayer,this.videotab);
  this.addOnTabs.push(this.videotab);
  
  //  this.wardtab=new OpenLayers.Control.Button({displayClass: "wardtab", trigger: function () { mboxObj.toggleTab.apply(mboxObj,[mboxObj.wardtab]); } });
  //  this.wardtab.tabLayer= new addOnLayer(wardLayer,this.wardtab);
 
  //  this.addOnTabs.push(this.wardtab);
  
  //this.imagetab=new OpenLayers.Control.Button({displayClass: "imagetab", trigger: function () { mboxObj.toggleImagetab.apply(mboxObj,[]); } });
  this.imagetab=new OpenLayers.Control.Button({displayClass: "imagetab", trigger: function () { mboxObj.toggleTab.apply(mboxObj,[mboxObj.imagetab]); } });
  this.imagetab.tabLayer = new addOnLayer(imageLayer,this.imagetab);
  this.addOnTabs.push(this.imagetab);
  //this.biastab=new OpenLayers.Control.Button({displayClass: "biastab", trigger: function () { mboxObj.toggleBiastab.apply(mboxObj,[]); } });
  this.biastab=new OpenLayers.Control.Button({displayClass: "biastab", trigger: function () { mboxObj.toggleTab.apply(mboxObj,[mboxObj.biastab]); } });
  //this.biasLegend=new OpenLayers.Control.Button({displayClass: "biasleg", trigger: function () { mboxObj.toggleBiastab.apply(mboxObj,[]); } });
  this.biasLegend=new OpenLayers.Control.Button({displayClass: "biasleg", trigger: function () { mboxObj.toggleTab.apply(mboxObj,[mboxObj.biastab]); } });
  this.biastab.tabLayer = new addOnLayer(biasLayer,this.biastab,this.biasLegend);
  this.addOnTabs.push(this.biastab);
  this.tabPanel.addControls(this.addOnTabs);
  this.map.addControl(this.tabPanel);
  for (var i in this.addOnTabs) {   
    this.addOnTabs[i].panel_div.title=this.addOnTabs[i].tabLayer.layerRef.tabTitle;
  }
  //"Explore the Bias Routes in Bengaluru";
  //this.videotab.panel_div.title="Highlights roads having the video coverage till date";
  //this.imagetab.panel_div.title="Explore places of interest in Bengaluru";
  if(MSIE6) { 
    this.imagetab.panel_div.style.display='none'  
  }  
  this.map.addControl( new OpenLayers.Control.PanZoomBar());
  this.map.addControl( new OpenLayers.Control.Attribution());
  this.map.addControl( new OpenLayers.Control.Navigation());
  this.map.addControl( new OpenLayers.Control.MousePosition() );
  var ab=this.map.getControlsByClass("OpenLayers.Control.Attribution");
  ab[0].div.style.bottom="2px";
  try {
    if(ioAreaObj.embed) {
    ab[0].div.style.position="fixed";
  }
  } catch(e) {}
  ab[0].div.style.fontFamily="'Trebuchet MS', Arial";
  ab[0].div.style.fontSize="12px";
  ab=this.map.getControlsByClass('OpenLayers.Control.MousePosition');
  ab[0].activate();
  if(!vidteq.debug) ab[0].div.style.display='none';
  ab[0].div.style.bottom="2px";
  ab[0].div.style.fontFamily="'Trebuchet MS', Arial";
  ab[0].div.style.left="10px";
  if(ioAreaObj.embed) this.tweakMapControls();
  var click = new OpenLayers.Control.Click();
  this.map.addControl(click);
  click.activate();
  var dblclick = new OpenLayers.Control.DblClick();
  this.map.addControl(dblclick);
  dblclick.activate();
  if (typeof(z_category) != 'undefined'){
    //$("#button_zcat").click();
    //try { $("#button_zcat").click(); } catch(e) { };
  }
  //this.addControlsForVia();
  if(ioAreaObj.embed && ioAreaObj.embed.place && ioAreaObj.embed.place.lonlat) {
    var a;a={}; a.point=[]; a.point.push(ioAreaObj.embed.place.lonlat); this.zoomToFit(a);
  } else {
    this.map.setCenter(new OpenLayers.LonLat(globalLon, globalLat), globalZoom);
  }
  if(ioAreaObj.embed && ioAreaObj.embed.minimap) {  
    if(parseInt(ioAreaObj.embed.height) < 240 ||  parseInt(ioAreaObj.embed.width) < 320) {
      $('#map')[0].style.cursor='pointer';
      $('#map')[0].title='Click to get more detailed features';
      $('#map')[0].onclick=this.popoutTheMinimap;
    }
  } else if(ioAreaObj.embed && ioAreaObj.embed.firstTimeRule && ioAreaObj.embed.firstTimeRule.busId) {
  } else {
    document.getElementById(this.viewPort).oncontextmenu = function (e) { mboxObj.attachRcmToMap.apply( mboxObj,[e]);return false; };
    $('#map')[0].title='Right Click on Map for more options'
  } 
  // if (typeof(z_category) != 'undefined'){
   	// $("#button_zcat")[0].onclick();
   	//}
}

mbox.prototype.getViaString = function () {
  var viaString='';
  for(var i in this.viaBallMarkerAdded) {
    viaString+=this.viaBallMarkerAdded[i].lonlat.lon+' '+this.viaBallMarkerAdded[i].lonlat.lat;
    if(i!=(this.viaBallMarkerAdded.length-1)) viaString+=',';
  }
  if (viaString == '') return null;
  return viaString;
}

mbox.prototype.addControlsForVia = function () {
  var newControl=new OpenLayers.Control.SelectFeature(this.route,{'hover':true,'onSelect':this.placeViaBall,'onUnselect':this.removeViaBall});
  this.map.addControl(newControl);
  this.map.controls[11].activate();
  this.dragViaBall = new OpenLayers.Control.DragMarker(this.viaBallMarkerLayer,{
    'onComplete': function (markerObj) {
      if(markerObj) {
        mboxObj.map.controls[11].activate();
        var whichViaBallIndex=0;
        var viaBallLoc = new OpenLayers.LonLat(markerObj.lonlat.lon,markerObj.lonlat.lat);
        if(!mboxObj.viaBallMarkerAdded) {
          mboxObj.viaBallMarkerAdded=[];
        } else {
          mboxObj.placeViaBallMarker(viaBallLoc);
        }
        //   mboxObj.releaseCarAfterDrag.apply(mboxObj,[parseFloat(e.lonlat.lon),parseFloat(e.lonlat.lat)]);
      }
    },
    'onStart': function (markerObj) {
      mboxObj.map.controls[11].deactivate();    
      mboxObj.placeViaBallFlag=false;   
    }
  });
  this.map.addControl(this.dragViaBall);
  this.dragViaBall.activate();
}

mbox.prototype.placeViaBallMarker = function (viaBallLoc) {
  ioAreaObj.changeBackOpacity(0.2);
  ioAreaObj.displayMessage(ioAreaObj.loadingDivMessage);
  if(!mboxObj.viaBallMarkerAdded) mboxObj.viaBallMarkerAdded=[];
  whichViaBallIndex=mboxObj.viaBallMarkerAdded.length;
  viaBallIconUrl=imagePathsObj.viaBallMarkers+"v"+(whichViaBallIndex+1)+".png";
  viaBallIcon=new OpenLayers.Icon(viaBallIconUrl,mboxObj.viaBallSize,null,mboxObj.imageIconOffset); 
  mboxObj.viaBallMarkerAdded[whichViaBallIndex] = new OpenLayers.Marker(viaBallLoc,viaBallIcon);
  mboxObj.placeViaBallFlag=true;
  mboxObj.removeViaBall();
  mboxObj.addViaMarkerToLayer(whichViaBallIndex);
  mboxObj.viaBallMarkerAdded[whichViaBallIndex].icon.imageDiv.style.zIndex="9500";
  ioAreaObj.placeViaRequest();
  mboxObj.killRcmPopup();
  return 0;
}

mbox.prototype.addViaMarkerToLayer = function(whichViaBallIndex) {
//If marker is already added, remove and reattach, to get the z-Index feeler for the user ! 
    if(mboxObj.viaBallMarkerAdded[whichViaBallIndex]) {
    mboxObj.startEndMarkLayer.removeMarker(mboxObj.viaBallMarkerAdded[whichViaBallIndex]);  
    }
    mboxObj.startEndMarkLayer.addMarker(mboxObj.viaBallMarkerAdded[whichViaBallIndex]);
    return 0;
}

mbox.prototype.placeViaBall = function () {
  var viaBallLonLat=mboxObj.map.getLonLatFromPixel(mboxObj.map.controls[8].lastXy);
  var pointWkt='POINT('+viaBallLonLat.lon+' '+viaBallLonLat.lat+')';
  mboxObj.viaBallMarkerLayer.removeMarker(mboxObj.viaBallMarker);
  var viaBallLoc = new OpenLayers.LonLat(viaBallLonLat.lon,viaBallLonLat.lat);
  mboxObj.viaBallMarker = new OpenLayers.Marker(viaBallLoc,mboxObj.viaBallIcon);
  mboxObj.viaBallMarkerLayer.addMarker(mboxObj.viaBallMarker);
  mboxObj.viaBallMarker.icon.imageDiv.style.zIndex='12000';
  mboxObj.viaBallMarker.icon.imageDiv.style.cursor='pointer';
  mboxObj.viaBallMarker.icon.imageDiv.title='Drage me and release to alter the  route';
  /*mboxObj.removeFeatures('viaBallLayer');
  mboxObj.pushFeatures('viaBallLayer',mboxObj.parser.read(pointWkt));*/
  mboxObj.placeViaBallFlag=true;
  if(mboxObj.placeViaBallFlag) $('#'+mboxObj.mapDom)[0].onmousemove=mboxObj.placeViaBall;
}

mbox.prototype.removeViaBall = function () {
  /*mboxObj.removeFeatures('viaBallLayer');
  mboxObj.placeViaBallFlag=false;*/
  if(mboxObj.placeViaBallFlag) {
    mboxObj.viaBallMarkerLayer.removeMarker(mboxObj.viaBallMarker);
    $('#'+mboxObj.mapDom)[0].onmousemove=null;
  }
}

mbox.prototype.tweakMapControls = function () {
  this.imagetab.panel_div.style.display="none";
  this.videotab.panel_div.style.display="none";
  if(parseInt(ioAreaObj.embed.height)<=250 || parseInt(ioAreaObj.embed.width)   <=250) {
     var ab=this.map.getControlsByClass('OpenLayers.Control.PanZoomBar');
    if(parseInt(ioAreaObj.embed.height)<=60 || parseInt(ioAreaObj.embed.width)  <=60) {
      ab[0].div.style.display='none';
    } else { 
      ab[0].buttons[0].style.display="none";
      ab[0].buttons[1].style.display="none";
      ab[0].buttons[2].style.display="none";
      ab[0].buttons[3].style.display="none";
      ab[0].buttons[4].style.top="4px";
      ab[0].buttons[5].style.top="20px";
      ab[0].div.childNodes[6].style.display="none";
      ab[0].div.childNodes[5].style.display="none";
    }
    ab=this.map.getControlsByClass("OpenLayers.Control.Attribution");
    //map.controls[4].buttons[7].style.display="none";
    //map.controls[4].buttons[6].style.display="none";
    ab[0].div.style.fontSize="9px";
    if(parseInt(ioAreaObj.embed.height)<200 || parseInt(ioAreaObj.embed.width)  <200)
      ab[0].div.style.display="none";
  } else {
    var dc=this.map.getControlsByClass("OpenLayers.Control.Attribution");
    dc[0].div.style.fontSize="12px";
  } 
}

mbox.prototype.toggleTab = function (tabObj) {
  for (var i in this.addOnTabs) {   
    if (this.addOnTabs[i] == tabObj) continue;
    if (this.addOnTabs[i].tabLayer) this.addOnTabs[i].tabLayer.clearLayer();
  }
  tabObj.tabLayer.toggleTab();
  this.updateClearButton();  // needa mechanism to clear
}

mbox.prototype.updateClearButton = function () {
  var isTabActive = false;
  for (var i in this.addOnTabs) { 
    if (this.addOnTabs[i].active) isTabActive = true;
  }
  if ( this.routeActive || this.srfActive || isTabActive ) {
    ioAreaObj.toggleButtons({"clearroutetab":true}); 
  } else { 
    ioAreaObj.toggleButtons({"clearroutetab":false}); 
  }
}

mbox.prototype.loadImageWfsLayer = function () {
  ioAreaObj.displayMessage("Loading Images .. please be patient");
  if(this.imagetab.active==true) {
    var zoomLevel=this.map.getZoom();
    zoomLevel+=10;
  }
  //bounds=this.imageLayer.getTilesBounds();
  bounds=this.imagetab.tabLayer.layer.getTilesBounds();
  var reqData= {
    z:zoomLevel,
    b:bounds.left+" "+bounds.bottom+","+bounds.right+" "+bounds.top,
    maptile:"requestgml"
  }
  $.getJSON(imgTileUrl,reqData,function (response) {  
    mboxObj.imgTile=response;  // TBD not sure about the context
    mboxObj.imgTile.boxes=new Array();
    for(i=0;i<mboxObj.imgTile.points.length;i++) {
      var ll=mboxObj.imgTile.points[i].split(",");
      ll[0]=parseFloat(ll[0]);
      ll[1]=parseFloat(ll[1]);
      var factor=8*mboxObj.map.getResolutionForZoom(mboxObj.map.getZoom());
      var minlon=ll[0]-factor;  
      var minlat=ll[1]-factor;
      var maxlon=ll[0]+factor;
      var maxlat=ll[1]+factor;
      mboxObj.imgTile.boxes[i]=new OpenLayers.Bounds(maxlon,maxlat,minlon,minlat);
      // TBD why extend ?
      mboxObj.imgTile.boxes[i].extend(new OpenLayers.LonLat(minlon,minlat));
      mboxObj.imgTile.boxes[i].extend(new OpenLayers.LonLat(maxlon,maxlat));
    }
    ioAreaObj.displayMessage("Images at this zoom level loaded");
  });
}

// TBD context not sure 
mbox.prototype.popupWfsLayer = function(e) {
  var lonlat=this.map.getLonLatFromPixel(this.map.events.getMousePosition(e));
  var didISearch = false;
  for(i=0;i<this.imgTile.boxes.length;i++) {
    if(this.imgTile.boxes[i] && this.imgTile.boxes[i].containsLonLat(lonlat,'inclusive')) {
      this.imageTilePopup(lonlat,this.imgTile.names[i],this.imgTile.poiname[i]);
      didISearch=true;
      break;
    }
  }
  if (didISearch) return 0;
}

mbox.prototype.imageTilePopup = function(lonlat,imageName,imagePOIName) {
  //ioAreaObj.displayMessage(''); Has been in the system since incpetion of mbox.js 
  this.killRcmPopup();
  this.removeOpenPopup();
  var imageSource=cloneImageUrl+imageName;
  imagePOIName=(imagePOIName==undefined)?(" "):(imagePOIName);
  var imagePopupContent="<div oncontextmenu='return false;'><div style='padding:4px'><div style='text-align:center'><a onfocus='this.blur();' class='simple' style='color:white;'>"+imagePOIName+"</a></div><div style='position:absolute'><div style='padding-left:310px; padding-bottom:235px;'><img style='cursor:pointer' src='"+imagePathsObj.close+"' onclick='javascript:mboxObj.removeOpenPopup.apply(mboxObj,[]);' href='javascript:void(0);'/></div>";
  imagePopupContent+="</div><img class='imagepop' style='border:2px solid white;' alt='Image' height=240 width=320 src='"+imageSource+"' /></div></div>";
  this.openPopup=new OpenLayers.Popup.FramedCloud("imagepopupdiv",
               new OpenLayers.LonLat(lonlat.lon,lonlat.lat),
               new OpenLayers.Size(330,270),imagePopupContent,
               null,false,this.removeOpenPopup);
  this.openPopup.setBackgroundColor("white");
  this.openPopup.setBorder("0px");
  this.openPopup.div.style.zIndex=18000;
  this.openPopup.autoSize=false;
  this.map.addPopup(this.openPopup);
  document.getElementById('imagepopupdiv').setClassName='imagepop';
  document.getElementById('imagepopupdiv_contentDiv').setClassName='imagepop';
  //OpenLayers.Event.stop(e);
}

mbox.prototype.removeOpenPopup = function() {
  if(typeof(this.openPopup) != 'undefined' && this.openPopup != null) {
    this.map.removePopup(this.openPopup);
    this.openPopup.destroy();
    this.openPopup=null;
  }
}
mbox.prototype.getCurrentZoom = function (){ return this.map.getZoom(); }

mbox.prototype.changeBaseLayerZoom = function() {
  var opacityBaseLayer=parseInt(this.map.getZoom())/10+0.3;
  this.map.layers[1].setOpacity(1)
}
//mbox.prototype.loadWardWfsLayer = function() {
//  myZoomis = this.map.getZoom();
//  OpenLayers.Console.log(myZoomis);
//  //var myBoundis =this.wardtab.tabLayer.layer.getTilesBounds();
//  //alert(myResolutionis);
//  //return; 
//  if (myZoomis <2){
//         $('#map')[0].title='Click on the area for more infor';
//
//      $.getJSON(imgTileUrl,{action:"requestZones"},function (response) {
//      this.wardWfsStyle=OpenLayers.Util.applyDefaults({
//        strokeWidth: 3,
//      //  strokeColor: yellow,
//        fillOpacity: 0,
//        //pointRadius:1,
//        strokeOpacity: 1
//    }, OpenLayers.Feature.Vector.style['default']);
//    this.wardWfsSelectStyle=OpenLayers.Util.applyDefaults({
//        strokeWidth: 3,
//        //strokeColor: "#D298F0",
//        fillColor: "#E6CBF3",
//        fillOpacity: .4,
//        //pointRadius:1,
//        strokeOpacity: 1
//    }, OpenLayers.Feature.Vector.style['default']);
//    mboxObj.wardWfsLayer=new OpenLayers.Layer.Vector("Wards", {style : this.wardWfsStyle});
//   // for(var i=0;i< response.results.length;i++) {
//    for(var i=0;i<response.results.length;i++) {
//   
//      var polygon=response.results[i].polygon
//      
//      var m=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.fromWKT(polygon))
//      m.name= response.results[i].name
//      m.noofwards=response.results[i].noofwards
//      m.zone=response.results[i].zone
//      m.population=response.results[i].population
//      m.male=response.results[i].male
//      m.female=response.results[i].female
//      mboxObj.wardWfsLayer.addFeatures([m]);
//     // m.events.register("mouseover",justAlert);
//        //alert (polygon); 
//  }
//        var report = function(e) {
//                OpenLayers.Console.log(e.type, e.feature.id);
//            };
//            
//
// mboxObj.wardWfsLayer.highlightCtrl = new OpenLayers.Control.SelectFeature(mboxObj.wardWfsLayer, {
//               // hover: true,
//                highlightOnly: true,
//                //renderIntent: "temporary",
//                clickout: true,
//                selectStyle: this.wardWfsSelectStyle,
//                onSelect :  mboxObj.wardWfsPopup,
//                onUnselect: mboxObj.wardWfsRemovePopup
//               //  onHover : wardWfsPopup,
//                //eventListeners: {
//                  //  beforefeaturehighlighted: report,
//                   // featurehighlighted: alert("highlight"),
//                    //featureunhighlighted: alert("unhighlight")
//                //}
//            });
//            mboxObj.map.addControl(mboxObj.wardWfsLayer.highlightCtrl);
//            mboxObj.wardWfsLayer.highlightCtrl.activate();
//          //  mboxObj.wardWfsLayer.highlightCtrl.events.register("mouseover",justAlert);
//  
//    mboxObj.map.addLayer(mboxObj.wardWfsLayer);
//  });
//  }else if (myZoomis >1 && myZoomis<4){
//       $('#map')[0].title='Zoom Out to get Zone Lvl Data';
//
//       var bounds=this.wardtab.tabLayer.layer.getTilesBounds();
//
//      var reqData= {
//    b:bounds.left+" "+bounds.bottom+","+bounds.right+" "+bounds.top,
//    action :"requestWards"
//  }
//  $.getJSON(imgTileUrl,reqData,function (response) {
//  this.wardWfsStyle=OpenLayers.Util.applyDefaults({
//        strokeWidth: 3,
//      //  strokeColor: yellow,
//        fillOpacity: 0,
//        //pointRadius:1,
//        strokeOpacity: 1
//    }, OpenLayers.Feature.Vector.style['default']);
//    this.wardWfsSelectStyle=OpenLayers.Util.applyDefaults({
//        strokeWidth: 3,
//        //strokeColor: "#D298F0",
//        fillColor: "#E6CBF3",
//        fillOpacity: .4,
//        //pointRadius:1,
//        strokeOpacity: 1
//    }, OpenLayers.Feature.Vector.style['default']);
//    mboxObj.wardWfsLayer=new OpenLayers.Layer.Vector("Wards", {style : this.wardWfsStyle});
//   // for(var i=0;i< response.results.length;i++) {
//    for(var i=0;i<response.results.length;i++) {
//   
//      var polygon=response.results[i].polygon
//      
//      var m=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.fromWKT(polygon))
//      m.name= response.results[i].name
//      m.wardno=response.results[i].wardno
//      m.zone=response.results[i].zone
//      m.population=response.results[i].population
//      m.male=response.results[i].male
//      m.female=response.results[i].female
//      m.category=response.results[i].category
//      mboxObj.wardWfsLayer.addFeatures([m]);
//     // m.events.register("mouseover",justAlert);
//        //alert (polygon); 
//  }
//        var report = function(e) {
//                OpenLayers.Console.log(e.type, e.feature.id);
//            };
//            
//
// mboxObj.wardWfsLayer.highlightCtrl = new OpenLayers.Control.SelectFeature(mboxObj.wardWfsLayer, {
//                // hover: true,
//                highlightOnly: true,
//                //renderIntent: "temporary",
//                clickout: true,
//                selectStyle: this.wardWfsSelectStyle,
//                onSelect :  mboxObj.wardWfsPopup,
//                onUnselect: mboxObj.wardWfsRemovePopup
//               //  onHover : wardWfsPopup,
//                //eventListeners: {
//                  //  beforefeaturehighlighted: report,
//                   // featurehighlighted: alert("highlight"),
//                    //featureunhighlighted: alert("unhighlight")
//                //}
//            });
//            mboxObj.map.addControl(mboxObj.wardWfsLayer.highlightCtrl);
//            mboxObj.wardWfsLayer.highlightCtrl.activate();
//          //  mboxObj.wardWfsLayer.highlightCtrl.events.register("mouseover",justAlert);
//  
//    mboxObj.map.addLayer(mboxObj.wardWfsLayer);
//  });
//}
//} 
//mbox.prototype.wardWfsLayerZoomChange = function() {
//  var layername 
//  var curZoom =this.map.getZoom();
//  var yo=this.wardtab.active;
//
//  //alert ("am in a load start  and my curZoois "+curZoom+"and old zoom is "+myZoomis +"and the layer is "+layername);
//  if(this.wardtab.active==true){
//       if ( ((curZoom) > 1 && curZoom<=3)  ){
//          //alert ("am in case 1")
//       mboxObj.unloadWardWfsLayer.apply(mboxObj,[]);
//         mboxObj.loadWardWfsLayer.apply(mboxObj,[]);
//          $('#map')[0].title='Zoom Out to get Zone Lvl Data';
//   }
//         else if  ((curZoom<2))
//          {
//              
//           mboxObj.unloadWardWfsLayer.apply(mboxObj,[]);
//           mboxObj.loadWardWfsLayer.apply(mboxObj,[]);
//             $('#map')[0].title='Zoom Out to get Zone Lvl Data';
//
//          }
//          else if (curZoom==myZoomis && curZoom<=3){
//              //alert("am in case 3")
//              mboxObj.unloadWardWfsLayer.apply(mboxObj,[]);
//              mboxObj.loadWardWfsLayer.apply(mboxObj,[]);
//              }
//          else if (curZoom>3){
//              //alert("am in case 4")
//              mboxObj.unloadWardWfsLayer.apply(mboxObj,[]);
//             $('#map')[0].title='Zoom Out to get Ward Info';
//
//              }
//              myZoomis = this.map.getZoom();
//      }
//  
//}
//mbox.prototype.unloadWardWfsLayer = function () {
//  //this.wardWfsLayer.clearMarkers();
//  if(mboxObj.wardWfsLayer) { this.map.removeLayer( mboxObj.wardWfsLayer); mboxObj.wardWfsLayer=null}
//  if (mboxObj.wardPopup){this.map.removePopup(mboxObj.wardPopup);} 
//  if(mboxObj.wardPopup){mboxObj.wardPopup=null ;}
//  $('#map')[0].title='Right Click on Map for more options';
//}
//mbox.prototype.wardWfsPopup = function (feature){
//               var  selectedFeature = feature ;
//                var popupdata
//              if(feature.name){
//                popupdata= "<div style='font-size:.8em'><b>Zone: </b> "+feature.zone+" <br />Name: " + feature.name+ "<br> Population : "+feature.population+"<br>No of Male : " +feature.male+ "<br> No of Female : " +feature.female+"<br>Category : " +feature.category+" <br><b><i>Zoom out to get Zone Details</i><b/></div>";
//            }
//             else {
//                popupdata= "<div style='font-size:.8em'><b>Zone: </b> "+feature.zone+" <br />No Of Wards: " + feature.noofwards+ "<br> Population : "+feature.population+"<br>No of Male : " +feature.male+ "<br>No of Female : " +feature.female+"<br><b><i>Zoom further in To get WARD Details</i><b/></div>";
//            }
//             
//                mboxObj.wardPopup = new OpenLayers.Popup.FramedCloud("wardinfo", 
//                                   selectedFeature.geometry.getBounds().getCenterLonLat(),
//                                   
//                                     null,
//                                   
//                                     popupdata,null, true, mboxObj.wardWfsRemovePopup);
//                                   
//                                   this.map.addPopup(mboxObj.wardPopup);
//            
//        }
//mbox.prototype.wardWfsRemovePopup = function () {
//  if (mboxObj.wardPopup)this.map.removePopup(mboxObj.wardPopup);
//  }
//
mbox.prototype.loadBiasWfsLayer = function() {
  $.getJSON(imgTileUrl,{action:"requestBias"},function (response) {
    mboxObj.biasWfsLayer=new OpenLayers.Layer.Markers("BIAS")
    for(var i=0;i< response.results.length;i++) {
      var ll=response.results[i].points.split(" ")
      var m=new OpenLayers.Marker(new OpenLayers.LonLat(ll[0],ll[1]),mboxObj.imageBusStopIcon.clone())
      //var r=vidteq.bias.response.results[i].busno.split(",");
      //var height=((r.length/4)+1)*13+14;
      var r=response.results[i].timings.split(" ");
      var s=response.results[i].busno.split(",");
                        //height=200;
      var height=parseInt((parseInt(r.length/7)+1)*16+15+13);
      //var height=((parseInt(r.length/7)+1)*15+(s.length/7+1)*15+13);
      if (MSIE6){height=height+2}
      if (r.length%7>0){height=height+12;}
      m.timings=response.results[i].timings;
      m.content="<div style='border:6px solid #21598c;'><a class=simple><b>"+response.results[i].name+"</b> <br/><u>Timings</u><br/>";
      for(j=0;j<r.length;j++){
        //if (m.content== null)//{//alert ("no timing for"+response.results[i].busno )}
        m.content+=r[j];
        m.content+=" "; 
      }
      m.content+="</a></div>";
      m.size=new OpenLayers.Size(250,height);
      //m.events.register("mouseover",m,function () {mboxObj.popupBiasWfsLayer.apply(mboxObj,[]);})
      m.events.register("mouseover",m,mboxObj.popupBiasWfsLayer);
      m.events.register("mouseout",m,function () { mboxObj.map.removePopup(mboxObj.biasPopup)});
      mboxObj.biasWfsLayer.addMarker(m);
    }
    mboxObj.map.addLayer(mboxObj.biasWfsLayer);
  });
}
mbox.prototype.unloadBiasWfsLayer = function () {
  this.biasWfsLayer.clearMarkers();
  this.map.removeLayer(this.biasWfsLayer);
}

mbox.prototype.popupBiasWfsLayer = function() {
  if(MSIE6){  this.size.h=this.size.h-10;}
  //if(MSIE7){  this.size.h=this.size.h-10;}
  mboxObj.biasPopup = new OpenLayers.Popup.Anchored("businfo",new
    OpenLayers.LonLat(this.lonlat.lon,this.lonlat.lat),
    this.size,this.content,mboxObj.imageBusStopIcon.clone(),false);
    //vidteq.bias.popup.setBackgroundColor("white");
    //vidteq.bias.popup.setBorder("0px");
  mboxObj.biasPopup.div.style.zIndex=18000;
  mboxObj.biasPopup.updateSize;
  mboxObj.map.addPopup(mboxObj.biasPopup);
  //document.getElementById('imagepopupdiv').setClassName='imagepop';
  //document.getElementById('imagepopupdiv_contentDiv').setClassName='imagepop';
  // TBD
  document.getElementById('businfo').className='optionsdiv';
  document.getElementById('businfo_GroupDiv').className='optionsdiv';
  document.getElementById('businfo_contentDiv').className='optionsdiv';
  document.getElementById('businfo_GroupDiv').style.height=document.getElementById('businfo_contentDiv').style.height=document.getElementById('businfo').style.height=this.size.h+6+"px";
  document.getElementById('businfo_GroupDiv').style.width=document.getElementById('businfo_contentDiv').style.width=document.getElementById('businfo').style.width=this.size.w+1+"px";
}

mbox.prototype.cleanSrf = function() {
  this.removeAllLocatorPoints();
  this.srfZoomExt = [];
  if(ioAreaObj.embed) { 
    this.removeStartEndPoint(ioAreaObj.embed.other); 
  } else {
    this.removeStartEndPoint('start');
    this.removeStartEndPoint('end');
  }  // TBD is it really needed ?
  this.removeOpenPopup();
}

mbox.prototype.writeSrfToTable = function(srf) {
  if (typeof(srf.showSets[srf.curShowSet]) == 'undefined') return;
  this.srfActive = true;
  for(var i=srf.showSets[srf.curShowSet].from-1;i<srf.showSets[srf.curShowSet].to;i++) {
    if(srf.results[i].geom) {
      var pObj=this.lonLatObjFrmPoint(srf.results[i].geom);
      this.srfZoomExt.push(pObj);
      this.putLocatorPointNew(srf.results[i]);
    }
    //if(srf.results[i].popup && srf.results[i].popup.type==1 && srf.results[i].popup.open==1) this.callPopupLocation(i)
    //TBD - do we really need this feature anymore ?
  }
  if(ioAreaObj.embed && ioAreaObj.embed.place && ioAreaObj.embed.place.lonlat) {
    var a;a={}; a.point=[]; a.point.push(ioAreaObj.embed.place.lonlat);
    this.srfZoomExt.push(ioAreaObj.embed.place.lonlat);
  }
  this.zoomToFit();
  try { 
    if(ioAreaObj.embed && ioAreaObj.embed.locateStores && srf.results[0].parentType=='locateStores') this.callPopupLocation(0);
  } catch(e) {}
  
}

mbox.prototype.refreshLocatorPoint = function(entity) {
  var lpIndex = entity.index;
  if (entity.lpIndex) lpIndex = entity.lpIndex;
  if (typeof(this.locatorPoint[lpIndex]) != 'undefined' &&
      this.locatorPoint[lpIndex] != null &&
      this.locatorPoint[lpIndex].entity == entity) {
    this.locationMarkLayer.removeMarker(this.locatorPoint[lpIndex]);
    this.putLocatorPointNew(entity);
  }
}

mbox.prototype.putLocatorPointNew = function(entity) {
  if (entity.type && entity.type == 'center') return;
  var icon = entity.markIcon;
  if (!entity.type || entity.type != 'center') {
    if (routeEndsObj.isEqual('start',entity))  icon = this.startIcon;
    if (routeEndsObj.isEqual('end',entity))  icon = this.endIcon;
  }
  var sz = new OpenLayers.Size(icon.size,icon.size);
  var calculateOffset = function(size) {
    return new OpenLayers.Pixel(-(size.w/2),-size.h);
  };
  var olIcon = new OpenLayers.Icon(icon.mapUrl,sz,null,calculateOffset);

  var pObj=this.lonLatObjFrmPoint(entity.geom);
  var location = new OpenLayers.LonLat(pObj.lon,pObj.lat);

  this.locatorPoint[entity.lpIndex]=new OpenLayers.Marker(location,olIcon);
  this.locatorPoint[entity.lpIndex].entity = entity;
  this.allMarkers[entity.lpIndex] = this.locatorPoint[entity.lpIndex];
  entity.markerIndex = entity.lpIndex;
  this.locationMarkLayer.addMarker(this.locatorPoint[entity.lpIndex]);
  this.locatorPoint[entity.lpIndex].events.register("click",null,this.popupLocationNew);
  this.locatorPoint[entity.lpIndex].icon.imageDiv.firstChild.style.cursor='pointer';
  this.locatorPoint[entity.lpIndex].icon.imageDiv.title=icon.title;
}

mbox.prototype.removeStartEndPoint = function(which) {
  var markerStr = which+'Marker';
  try { 
    this.startEndMarkLayer.removeMarker(this[markerStr]); 
   } catch (e) { }
  this[markerStr] = {};
}

mbox.prototype.putStartEndPoint = function(which,entity) {
  var markerStr = which+'Marker';
  var icon;
  //if (which == 'start') icon = startIcon;
  if (which == 'start') icon = this.startIcon;
  //if (which == 'end') icon = endIcon;
  if (which == 'end') icon = this.endIcon;
  if (entity.icon && entity.icon.name && entity.type && entity.type == 'center') icon = entity.icon;
  var sz = new OpenLayers.Size(icon.size,icon.size);
  var calculateOffset = function(size) {
    return new OpenLayers.Pixel(-(size.w/2),-size.h);
  };  
  var olIcon = new OpenLayers.Icon(icon.mapUrl,sz,null,calculateOffset);
  var pObj=this.lonLatObjFrmPoint(entity.geom);
  var location = new OpenLayers.LonLat(pObj.lon,pObj.lat);
  this[markerStr] = new OpenLayers.Marker(location,olIcon);
  this.startEndMarkLayer.addMarker(this[markerStr]);
  this[markerStr].icon.imageDiv.title=icon.title;
  this[markerStr].entity = entity;
  this.allMarkers[markerStr] = this[markerStr];
  entity.markerIndex = markerStr;
  this[markerStr].events.register("click",null,this.popupLocation);
  this[markerStr].icon.imageDiv.firstChild.style.cursor=icon.mapStyle;
}

mbox.prototype.isPopupActiveFor = function(entity) {
  if (typeof(this.openPopup) != 'undefined' && 
    this.openPopup != null &&
    entity == this.openPopup.entity) return true;
  return false;
}

mbox.prototype.callPopupLocation = function(i,e) {
 if(self.navigator.appName.match(/Microsoft/i)) {
    this.locatorPoint[i].events.listeners['click'][0].func.apply(this.locatorPoint[i],[window.event]);
  } else {
    evt={};
    window.event=evt;
    this.locatorPoint[i].events.listeners['click'][0].func.apply(this.locatorPoint[i],[evt]);
  }
}

mbox.prototype.popUpStartEndPlace= function(which) {
if(self.navigator.appName.match(/Microsoft/i)) {
    if(this[which] && this[which].events) this[which].events.listeners['click'][0].func.apply(this[which],[window.event]);
  } else {
    evt={};
    window.event=evt;
    if(this[which] && this[which].events)  this[which].events.listeners['click'][0].func.apply(this[which],[evt]);
  } 
}   

mbox.prototype.popupLocationNew = function(evt) {
  mboxObj.removeOpenPopup();
  var mapHtml = getEntityHtml('map',this.entity);
  var size=(mapHtml.popupWidth)?(new OpenLayers.Size(mapHtml.popupWidth,mapHtml.popupHeight)):(new OpenLayers.Size(320,240));   
 // var size=new OpenLayers.Size(10,10);    
  mboxObj.openPopup=new OpenLayers.Popup.FramedCloud("locpopupdiv",new OpenLayers.LonLat(this.lonlat.lon,this.lonlat.lat),size,mapHtml.contentHTML,null,false,mboxObj.removeOpenPopup);
  mboxObj.openPopup.setBackgroundColor("white");
  mboxObj.openPopup.index = this.entity.index;
  mboxObj.openPopup.entity = this.entity;
  mboxObj.openPopup.autoSize=false;
  mboxObj.map.addPopup(mboxObj.openPopup);
  document.getElementById('locpopupdiv').setClassName='locpop';
  document.getElementById('locpopupdiv_contentDiv').setClassName='locpop';
  OpenLayers.Event.stop(evt);
}

mbox.prototype.popupLocation = function(evt) {
  mboxObj.removeOpenPopup();
  var mapHtml = getEntityHtml('map',this.entity);
  var size=(mapHtml.popupWidth)?(new OpenLayers.Size(mapHtml.popupWidth,mapHtml.popupHeight)):(new OpenLayers.Size(320,240));   
  mboxObj.openPopup=new OpenLayers.Popup.FramedCloud("locpopupdiv",new OpenLayers.LonLat(this.lonlat.lon,this.lonlat.lat),size,mapHtml.contentHTML,null,false,mboxObj.removeOpenPopup);
  mboxObj.openPopup.setBackgroundColor("white");
  mboxObj.openPopup.index = this.entity.index;
  mboxObj.openPopup.entity = this.entity;
  mboxObj.openPopup.autoSize=false;
  mboxObj.map.addPopup(mboxObj.openPopup);
  document.getElementById('locpopupdiv').setClassName='locpop';
  document.getElementById('locpopupdiv_contentDiv').setClassName='locpop';
  OpenLayers.Event.stop(evt);
}

mbox.prototype.fitCurrentRoute = function() {
  if (!this.routeActive) return ;
  var zoomLonLat={};
  zoomLonLat.point=new Array();
  zoomLonLat.point[0]={};
  zoomLonLat.point[1]={};
  var temp1=this.carPathArray[0][0].split(" ");
  zoomLonLat.point[0].lon=temp1[0];
  zoomLonLat.point[0].lat=temp1[1];
  var totP=parseInt(this.carPathArray.length-1);
  var lastTotP=parseInt(this.carPathArray[totP].length-1);
  var temp2=this.carPathArray[totP][lastTotP].split(" ");
  zoomLonLat.point[1].lon=temp2[0];
  zoomLonLat.point[1].lat=temp2[1];
  for(var i=0;i<this.syncMapPoints.length;i++) {
    var ll=this.carPathArray[this.syncMapPoints[i]][0].split(" ");
    var thisPoint={};
    thisPoint.lon=ll[0];
    thisPoint.lat=ll[1];
    zoomLonLat.point.push(thisPoint);
  }
  this.zoomToFit(zoomLonLat);
}

mbox.prototype.zoomToFit = function(zoomLonLat) {
  if (typeof(zoomLonLat) == 'undefined') {
    var zoomLonLat = {}; zoomLonLat.point = this.srfZoomExt;
  }
  if(zoomLonLat.point.length==0) return false;
  //This API takes an Object which is has its members as array latlong . Cool, generic function.Condition:-There should be alteast 2 points
  if(zoomLonLat.point.length==1) {
    this.map.setCenter(new OpenLayers.LonLat(zoomLonLat.point[0].lon,zoomLonLat.point[0].lat), 5);
    return false;
  }
  // now length >= 2
  var minlon = Math.min(zoomLonLat.point[0].lon,zoomLonLat.point[1].lon);
  var minlat = Math.min(zoomLonLat.point[0].lat,zoomLonLat.point[1].lat)-0.00005;
  var maxlon = Math.max(zoomLonLat.point[0].lon,zoomLonLat.point[1].lon);
  var maxlat = Math.max(zoomLonLat.point[0].lat,zoomLonLat.point[1].lat)+0.00005;
  // TBD why is buffer not added in lon ?
  var startEndBound=new OpenLayers.Bounds(minlon,minlat,maxlon,maxlat);
  for(var i=0;i<zoomLonLat.point.length;i++) {
    var local=new OpenLayers.LonLat(zoomLonLat.point[i].lon,zoomLonLat.point[i].lat);
    if(!startEndBound.containsLonLat(local)) {
      startEndBound.extend(local);
    }
  }
  this.map.zoomToExtent(startEndBound);
  return false;
}

mbox.prototype.removeAllLocatorPoints = function() {
  if(this.locationMarkLayer.markers && this.locationMarkLayer.markers.length>0) {
    this.locationMarkLayer.clearMarkers();
  }
  for (var i in this.locatorPoint) { this.locatorPoint[i] = {}; } 
  // I can optionally go down to entity and anul its marker TBD
}

mbox.prototype.removeImageMarkers = function() {
  if(typeof(this.oneImageMarker) != 'undefined' && 
     this.oneImageMarker.length>0) { this.oneImageMarker=[]; }
  if(typeof(this.imageMarkers) != 'undefined' && 
     this.imageMarkers != null &&
     this.imageMarkers.markers.length>0) {
    this.imageMarkers.clearMarkers();
   // this.map.removeLayer(this.imageMarkers);
 //   this.imageMarkers = null;
  }
}

// function to clear the route in mbox
mbox.prototype.clearAll = function () {
  for (var i in this.addOnTabs) {   
    if (this.addOnTabs[i].tabLayer) this.addOnTabs[i].tabLayer.clearLayer();
  }
  //this.clearBiasLayer();
  //this.clearImageLayer();
  //this.clearVideoLayer();
  this.clearViaBalls();
  this.clearRouteAndSrf();
}

mbox.prototype.clearViaBalls = function () {
  for (var i in this.viaBallMarkerAdded) {
    this.startEndMarkLayer.removeMarker(this.viaBallMarkerAdded[i]);
  }
  this.viaBallMarkerAdded=[]; 
}

mbox.prototype.clearRouteAndSrf = function () {
  this.killRcmPopup();
  this.carPathArray=[];     
  this.enableCarDisplay = false;
  this.syncMapPoints=[];    
  this.removeAllLocatorPoints();
  if(ioAreaObj.embed) { this.removeStartEndPoint(ioAreaObj.embed.other); }
  else {
    this.removeStartEndPoint('start');
    this.removeStartEndPoint('end');
  }
  this.removeOpenPopup();
  this.removeImageMarkers();
  this.route.removeFeatures(this.route.features);
  this.routeNoVid.removeFeatures(this.routeNoVid.features);
  this.routeNoVb.removeFeatures(this.routeNoVb.features);
  this.routeNoDp.removeFeatures(this.routeNoDp.features);
  if(this.textDirLayer) { this.textDirLayer.clearMarkers(); }
  if(this.busStopsLayer) { this.busStopsLayer.clearMarkers(); }
  if(this.carPoint) {
    this.carMarkLayer.removeMarker(this.carPoint);
    this.carMarkLayer.clearMarkers();
  }
  if(this.routeActive) {
  }
  this.routeActive=false;
  this.srfActive=false;
  return false;
}

mbox.prototype.pushFeatures = function(vectorLayer,pointWkt) {
  this[vectorLayer].addFeatures(pointWkt);
}

mbox.prototype.removeFeatures = function(vectorLayer) {
  if(this[vectorLayer].features) 
    this[vectorLayer].removeFeatures(this[vectorLayer].features);
}

mbox.prototype.setTitle = function (myStr) {
  document.getElementById(this.mapDom).title = myStr;
}

mbox.prototype.killRcmPopup = function() {
  this.removeFeatures('clickPointMark');
  if(typeof(this.rcmPopup) != 'undefined' && this.rcmPopup != null) {
    this.map.removePopup(this.rcmPopup);
    this.rcmPopup.destroy();
    this.rcmPopup=null;
  }
}

mbox.prototype.addRcmStartOrEndMarker = function(which,lonlat) {
  //if (this.routeActive) { this.clearRoute(); }
  if (this.routeActive) {
      this.clearViaBalls();
      clearRouteAndSrf();
  }
  // TBD above needs refinement
  this.killRcmPopup();
  routeEndsObj.replace.apply(routeEndsObj,[which,-1,lonlat])
}

mbox.prototype.returnMouseLonLats = function (e) {
  var check;
  if(self.navigator.appName.match(/Microsoft/i))  {
    e=window.event; 
    check=1;
  } else {
    check=e.target.id.match(/^OpenLayers.Layer.Vector/) || 
          e.target.id.match(/^OpenLayersDiv/);
  } 
  if(!check) return false;
  if(mboxObj.killOptionPopupVar){ clearTimeout(mboxObj.killOptionPopupVar); }
  mboxObj.killRcmPopup();
  e.xy=mboxObj.map.events.getMousePosition(e);
  return(e);
} 

mbox.prototype.attachRcmToMap = function(e) {
  var eventObj=mboxObj.returnMouseLonLats(e);
  if(!eventObj) return false;
  mboxObj.rcmLonlat=mboxObj.map.getLonLatFromPixel(eventObj.xy); 
  mboxObj.pointLonlat="POINT("+mboxObj.rcmLonlat.lon+" "+mboxObj.rcmLonlat.lat+")"; 
  mboxObj.pushFeatures('clickPointMark',mboxObj.parser.read(mboxObj.pointLonlat));
  eventObj.xy.x+=10;
  eventObj.xy.y-=10;
  var popuplonlat=mboxObj.map.getLonLatFromPixel(eventObj.xy);
  var mapOptionsHTML="<table height=88 width=100 style='border :2px solid "+mainColor+"; text-align:center; overflow:hidden;' cellborder='1' width=100% height=100%>";

    var optionsDecider = function (id,onclickFunc,text,disabled) {
        var ht=["<tr id='"+id+"'" ];
        ht.push("onclick=javascript:"+onclickFunc+";");
        ht.push("class=sugrow onmouseover=this.className='sugrowhighlight' onmouseout=this.className='sugrow'>");
        ht.push("<td><a onfocus='this.blur();' class='icondivtext'");
        if(disabled) {
        ht.push("style='cursor:text;color:#CDC8B1;' ");
        }
        ht.push("href='javascript:void(0)'>");
        ht.push(text+"</a></td></tr>");
        ht=ht.join(' ');
        return ht;
    }
  
    if(document.getElementById("clearroutetab") && (document.getElementById("clearroutetab").className!='maptabdisabled' || document.getElementById("clearroutetab").className!='maptabdisabled1')) {
    mapOptionsHTML+=optionsDecider("clearoption","clearAll()","Clear",false);
    }
    else {
    mapOptionsHTML+=optionsDecider("clearoption","void(0)","Clear",true);   
    }
    if(ioAreaObj.embed && ioAreaObj.embed.locateStores) {
        mapOptionsHTML+=optionsDecider("locateStores","ioAreaObj.locateNearByStoresByIndex(-1,'start');","Locate Nearest Store",false);
        if(mboxObj.routeActive) {
        mapOptionsHTML+=optionsDecider("viaoption","mboxObj.placeViaBallMarker.apply(mboxObj,[mboxObj.rcmLonlat])","Via",false);
        }
    }
    else {
    if(mboxObj.routeActive) 
    mapOptionsHTML+=optionsDecider("viaoption","mboxObj.placeViaBallMarker.apply(mboxObj,[mboxObj.rcmLonlat])","Via",false);
    
    var func="mboxObj.addRcmStartOrEndMarker.apply(mboxObj,['start',mboxObj.rcmLonlat]);";
    
    mapOptionsHTML+=optionsDecider("startoption",func,"Directions From",false);

    mapOptionsHTML+=optionsDecider("endoption","mboxObj.addRcmStartOrEndMarker.apply(mboxObj,['end',mboxObj.rcmLonlat])","Directions To",false);    
    }
    if(!mboxObj.routeActive)
    mapOptionsHTML+=optionsDecider("govidoption","void(0)","GO VID",false); 

    mapOptionsHTML+="</table>";
    mboxObj.rcmPopup=new OpenLayers.Popup("mapoptionsdiv",new OpenLayers.LonLat(popuplonlat.lon,popuplonlat.lat),new OpenLayers.Size(100,88),mapOptionsHTML,false);
    mboxObj.rcmPopup.setContentHTML(mapOptionsHTML);
    mboxObj.rcmPopup.panMapIfOutOfView=true;
    mboxObj.map.addPopup(mboxObj.rcmPopup);
    if(ioAreaObj.embed && !ioAreaObj.embed.locateStores) 
    mboxObj.disableInEmbed(ioAreaObj.embed.fix,mboxObj.rcmLonlat);      
    if($('#govidoption')[0]) {  
    $('#govidoption')[0].onclick=function () { ioAreaObj.invokeTheMode.apply(ioAreaObj,[]); return false; };
    }
  // TBD why not use trimpath - is it really useful explore
  document.getElementById('mapoptionsdiv').className='optionsdiv';
  document.getElementById('mapoptionsdiv_GroupDiv').className='optionsdiv';
  document.getElementById('mapoptionsdiv_contentDiv').className='optionsdiv';
  document.getElementById('mapoptionsdiv').style.height="88px";
  document.getElementById('mapoptionsdiv').style.width="100px";
  mboxObj.killOptionPopupVar=setTimeout('mboxObj.killRcmPopup()',30000);
  return false;
}

mbox.prototype.disableInEmbed = function (str,ll) {
  var whichOne=(str=='start')?($('#startoption')[0]):($('#endoption')[0]);
  var otherOne=(str=='start')?($('#endoption')[0]):($('#startoption')[0]);
  var passString=(str=='start')?('From'):('To');
  var otherString=(str=='start')?('end'):('start');
  whichOne.onclick=function () {};
  otherOne.onclick=function () {
    mboxObj.addRcmStartOrEndMarker.apply(mboxObj,[otherString,ll]);
    ioAreaObj.goVid();
  }
  try {     
    whichOne.innerHTML="<a class=simple style=color:#CDC8B1;>Directions "+passString+"</a>";
    whichOne.style.cursor='text';
  } catch(e) {} 
  whichOne.onmouseover=whichOne.onmouseout='';      
}   
 
mbox.prototype.writeWkt = function (layer,wktParent) {
  if (typeof(wktParent) == 'undefined' || typeof(wktParent.wkt) == 'undefined' || wktParent.wkt == null) return;
  var features = new Array;
  if (typeof(wktParent.wkt) == 'string') {
    features.push(this.parser.read(wktParent.wkt));
  } else {
    for (var i in wktParent.wkt) {
      var wkt = this.parser.read(wktParent.wkt[i]);
      if (wkt) features.push(wkt);
    }
  }  
  if ( features.length > 0 ) layer.addFeatures(features);
}

mbox.prototype.putImageData = function(imageData) {
  var imageLoc,oneMarker;
  this.oneImageMarker=new Array();
  for(var i=0;i<imageData.length;i++) {
    if(imageData[i].dpRoadName) {
      imageData[i].imageCaption= (imageData[i].dpRoadName=='' || imageData[i].dpRoadName==undefined )?('Name is not available'):(imageData[i].dpRoadName);
      imageLoc = new OpenLayers.LonLat(imageData[i].lonlat.lon,imageData[i].lonlat.lat);
      this.oneImageMarker[i] =new OpenLayers.Marker(imageLoc,this.imageDoiIcon.clone());
    }
    if(imageData[i].poiName) {
      var splitName=imageData[i].imgName.split("_");
      imageData[i].imageCaption=(imageData[i].poiName==undefined)?(" "):imageData[i].poiName;
      imageLoc = new OpenLayers.LonLat(imageData[i].lonlat.lon,imageData[i].lonlat.lat);
      this.oneImageMarker[i] =new OpenLayers.Marker(imageLoc,this.imagePoiIcon.clone());
    }
    if(this.oneImageMarker[i]) {
      this.oneImageMarker[i].icon.imageDiv.firstChild.style.cursor='pointer';
      this.imageMarkers.addMarker(this.oneImageMarker[i]);
      this.oneImageMarker[i].icon.imageDiv.title='Click to see image';
      this.oneImageMarker[i].data = imageData[i];
      this.oneImageMarker[i].events.register("click",imageData[i],this.popupOneImage);
    }
  }
}

mbox.prototype.popupOneImage = function(evt) {
  mboxObj.imageTilePopup(this.lonlat,this.imgName,this.imageCaption);
  // TBD arrow overlay 
  OpenLayers.Event.stop(evt);
}

// this function is already context neutral so ok
mbox.prototype.callPopupOneImage = function(i,evt) {  
  if(self.navigator.appName.match(/Microsoft/i)) {
    mboxObj.oneImageMarker[i].events.listeners['click'][0].func.apply(mboxObj.oneImageMarker[i].data,[window.event]);
  } else {  
    evt={};
    window.event=evt;
    mboxObj.oneImageMarker[i].events.listeners['click'][0].func.apply(mboxObj.oneImageMarker[i].data,[evt]);
  }
}

mbox.prototype.busStopPopup = function (lonlat,imagePath,busStopName) {
    mboxObj.imageTilePopup(this.lonlat,this.imagePath,this.busStopName);
    return 0;
} 

mbox.prototype.callBusStopPopup = function(i,evt) {
  if(self.navigator.appName.match(/Microsoft/i)) {
    mboxObj.busStopsMarkers[i].events.listeners['click'][0].func.apply(mboxObj.busStopsMarkers[i],[window.event]);
  } else {  
    evt={};
    window.event=evt;
    mboxObj.busStopsMarkers[i].events.listeners['click'][0].func.apply(mboxObj.busStopsMarkers[i],[evt]);
  }
}

mbox.prototype.putCarPath = function(response) {
  this.carPathArray=new Array();
  this.syncMapPoints=new Array();
  for (var i = 0; i < response.car.length; i++) {
    var tempText=response.car[i];
    this.carPathArray[i]=tempText.split('|');
    if(this.carPathArray[i][0].match(/I/)) {
      this.carPathArray[i].shift();
      this.syncMapPoints.push(i);
    }
    if(this.carPathArray[i] == null) {
      this.carPathArray[i] = tempText;
    }
  }
  var onePoint = this.carPathArray[0][0];
  if(typeof this.carPathArray[0][response.sourceHandle]!= 'undefined') {
    onePoint=this.carPathArray[0][response.sourceHandle];
  }  
  this.removeAndAddCarPoint(onePoint);
}

mbox.prototype.removeAndAddCarPoint = function(onePoint) { 
  if(this.carPoint) {
    var cacheID=this.carPoint.events.element._eventCacheID;
    OpenLayers.Event._removeElementObservers(OpenLayers.Event.observers[cacheID]);
    this.carMarkLayer.removeMarker(this.carPoint);
    this.carMarkLayer.clearMarkers();
  }
  var carCord = onePoint.split(" ");
  var carLoc = new OpenLayers.LonLat(carCord[0],carCord[1]);
  this.carPoint = new OpenLayers.Marker(carLoc,this.carIcon);
  this.carMarkLayer.addMarker(this.carPoint);
  this.carPoint.icon.imageDiv.style.zIndex='4000';
  if(MSIE6) this.carPoint.icon.imageDiv.title="";
  else this.carPoint.icon.imageDiv.title="Drag me to move along the route";
}

mbox.prototype.putTextNumbers = function() {
  var imageSize= new OpenLayers.Size(16,16);
  var imageIconOffset=function (imageSize) { return new OpenLayers.Pixel(-(imageSize.w),-(imageSize.h)); } 
  for(var i=1;i<(this.syncMapPoints.length-1);i++) {
    //var f="images/textdirs/"+(i+1)+".png";
    var f=imagePathsObj.textdirs.base+(i+1)+".png";
    var textIcon=new OpenLayers.Icon(f,imageSize,null,imageIconOffset);
    var po=this.carPathArray[this.syncMapPoints[i]][0].split(" ");
    var loc=new OpenLayers.LonLat(po[0],po[1]);
    var m=new OpenLayers.Marker(loc,textIcon);
    this.textDirLayer.addMarker(m);
    m.icon.imageDiv.title='Text Direction Number';
  }
}

mbox.prototype.removeBusStopPopup = function () {
    if(mboxObj.busStopPopup) mboxObj.map.removePopup(mboxObj.busStopPopup);
}

mbox.prototype.putBusStops = function (busStops) {
  mboxObj.removeBusStopPopup();
  mboxObj.busStopsMarkers=new Array();  
  var imageSize= new OpenLayers.Size(16,16);
  var imageIconOffset=function (imageSize) { return new OpenLayers.Pixel(-(imageSize.w),-(imageSize.h)); } 
  var f=imagePathsObj.busStop;
  var busIcon=new OpenLayers.Icon(f,imageSize,null,imageIconOffset);
  for(var i in busStops) {
  var loc=lonLatObjFrmPoint(busStops[i].geom);
  var m=new OpenLayers.Marker(loc,busIcon.clone());
  m.busStopName=busStops[i].name;
  m.lonlat=loc;
  m.events.register("click",m,this.busStopPopup);
  this.busStopsLayer.addMarker(m);
  m.icon.imageDiv.title=busStops[i].name || '';
  mboxObj.busStopsMarkers.push(m);
    }
}

mbox.prototype.moveCarTo = function(index) {
  //textChange(myArray[parentIndex]); future enhancement
  if (!this.enableCarDisplay) return;
  var stringSplit=index.split(":");
  var parentIndex=stringSplit[0];
  var childIndex=stringSplit[1];
  var onePoint;
  if(this.carPathArray[parentIndex].length == 1) {
    onePoint = this.carPathArray[parentIndex][0];
  } else {
    onePoint = this.carPathArray[parentIndex][childIndex];
  }
  this.removeAndAddCarPoint(onePoint);
}

mbox.prototype.zoom2RoadDp = function(textIndex) {
  var zoom={};
  zoom.point=new Array();
  for(var i=0;i<this.carPathArray[this.syncMapPoints[textIndex]].length;i++) {
    var a=this.carPathArray[this.syncMapPoints[textIndex]][i].split(" ");
    zoom.point[i]={};
    zoom.point[i].lon=a[0];
    zoom.point[i].lat=a[1];
  }
  this.zoomToFit(zoom);
}

mbox.prototype.displayRoute = function(response) {
  //this.clearAll();  // not sure why is it needed TBD
  this.routeActive = true;
  this.writeWkt(this.route,response.edge);
  this.writeWkt(this.routeNoVid,response.novid);
  this.writeWkt(this.routeNoVb,response.novb);
  this.writeWkt(this.routeNoDp,response.nodp);
  if(!ioAreaObj.embed  ||
    (ioAreaObj.embed && ioAreaObj.embed.fix=='end')) {
    routeEndsObj.add('start',response.startEntity);
    //  this.putStartEndPoint('start',response.startEntity);
  } 
  if(!ioAreaObj.embed  ||
    (ioAreaObj.embed && ioAreaObj.embed.fix=='start')) {
    routeEndsObj.add('end',response.endEntity);
    //  this.putStartEndPoint('end',response.endEntity);
  }
  if(ioAreaObj.embed && !ioAreaObj.embed.locateStores) {
    firstTimeRule={};   
    firstTimeRule.newFix=ioAreaObj.embed.other;
    firstTimeRule.geom=routeEndsObj[ioAreaObj.embed.other].geom;
    var host=document.location.hostname;
    if(document.location.pathname.match(/stage/)) host+='/stage';

    ioAreaObj.link='http://'+host+'/which.php?urlid='+vidteq.urlId+'&firstTimeRule='+JSON.stringify(firstTimeRule);     
    } 
  // TBD I can use these markers for future use
  this.putCarPath(response);
  this.enableCarDisplay = true;
  if(ioAreaObj.embed && ioAreaObj.embed.firstTimeRule && ioAreaObj.embed.firstTimeRule.busId) {
  this.putBusStops(response.busStops);
  } 
  else {
  this.putTextNumbers();  // implicit dependency to carPath
  this.putImageData(response.imgData);  
  }
  this.fitCurrentRoute(); // implicit dependency to carPath
  if(typeof(mboxObj.viaBallMarkerAdded)!='undefined') {
    for(var i=0;i<mboxObj.viaBallMarkerAdded.length;i++) {
        mboxObj.addViaMarkerToLayer(i);
        }
    }
}

mbox.prototype.lonLatObjFrmPoint = function(point) {
  if(typeof(point) == 'undefined' || point == null) return null;
  var temp=point.replace(/POINT\(/,"");
  temp=temp.replace(/\)/,"");
  temp=temp.replace(/\,/," ");
  var pt=temp.split(" ");
  var p={};
  p.lon=parseFloat(pt[0]);
  p.lat=parseFloat(pt[1]);
  return p; 
}

mbox.prototype.computeDistance = function(lonA,latA,lonB,latB) {
  return parseFloat((10000000*(lonA-lonB)*(lonA-lonB) + (latA-latB)*(latA-latB)));
}

mbox.prototype.releaseCarAfterDrag = function(dragLon,dragLat) {
  var splitLonLat=this.carPathArray[0][0].split(" ");
  var leastDist=this.computeDistance(parseFloat(dragLon),parseFloat(dragLat),parseFloat(splitLonLat[0]),parseFloat(splitLonLat[1]));
  var nearestIndex=0;
  for(var i=1;i<this.carPathArray.length;i++) {
    splitLonLat=this.carPathArray[i][0].split(" ");
    var dist = this.computeDistance(parseFloat(dragLon),parseFloat(dragLat),parseFloat(splitLonLat[0]),parseFloat(splitLonLat[1]));
    if(dist!=0 && dist < leastDist) {
      nearestIndex=i;
      leastDist = dist;
    }
  }
  var onePoint = this.carPathArray[nearestIndex][0];
  this.removeAndAddCarPoint(onePoint);
  this.enableCarDisplay = true;  // TBD wait till video play is reint
  fvtObj.getVideoObj(fvtObj.videoSwf).playVideo(nearestIndex);
}

mbox.prototype.getCenter= function() {
  var center = this.map.getCenter();
  return center;
}

mbox.prototype.getBound =function () {
  var bound ;
  bound =this.map.getExtent();
  return bound;  
}

mbox.prototype.createCatLayer= function(obj,response) {
  var createCatLayer={};
  var srfResponse=response.srf[0].results;
  var catObj=obj;
  createCatLayer.catname="Category";
  createCatLayer.catname+=obj.name;
  var matchCat=/category/gi;
  var matchCatName = new RegExp(createCatLayer.catname);
  var nameToTest= this.map.getLayersByName(matchCat);
  if (typeof( nameToTest[0])!='undefined'){
    if (matchCatName.test( nameToTest[0].name)) {
      makeAllBackgroundWhite();
      mboxObj.clearCatLayer();
      return;
    } else { mboxObj.destroyCatLayer(); }
  }
  ioAreaObj.toggleButtons({'clearroutetab' : true});
  createCatLayer.catIcon=obj.categoryIcon;
  createCatLayer.categoryClusterIcon=obj.categoryClusterIcon;
  createCatLayer.shadow= obj.shadow;
  createCatLayer.shadowIcon= obj.shadow_p;
  createCatLayer.Title=obj.name;
  createCatLayer.strategy = new OpenLayers.Strategy.Cluster({distance:40,threshold:2});
  createCatLayer.defaultStyle= new OpenLayers.Style({
    externalGraphic: "${icon}",
    backgroundGraphic: "${shadowIcon}",
    backgroundXOffset: 0,
    backgroundYOffset: -18,
    graphicZIndex: 20000,
    backgroundGraphicZIndex: 10000,
    pointRadius: 16,
    graphicTitle: "${title}"
  },
  { context : {
      icon: function(feature) {
        if (typeof (feature.attributes.count) != 'undefined') {
          return createCatLayer.categoryClusterIcon;
        } else {return createCatLayer.catIcon;}
      },
      shadowIcon: function(feature) {
        if (typeof (feature.attributes.count) != 'undefined') {
          return createCatLayer.shadowIcon;
        } else { return createCatLayer.shadow;}
      },
      title: function(feature) {
        if (typeof (feature.attributes.count) != 'undefined') {
          return feature.attributes.count+" "+feature.cluster[0].data.srfResponse.category+" Here ";
        } else {return feature.data.srfResponse.address.name;}
      }
    }
  });
  createCatLayer.selectStyle= new OpenLayers.Style({
    externalGraphic: "${icon}",
    backgroundGraphic:"${shadowIcon}",
    backgroundXOffset: 0,
    backgroundYOffset: -18,
    graphicZIndex: 20000,
    backgroundGraphicZIndex: 10000,
    pointRadius: 20,
    graphicTitle: "${title}"
  },
  { context : {
      icon: function(feature) {
        if (typeof (feature.attributes.count) != 'undefined')
          {return createCatLayer.categoryClusterIcon;}
        else {return createCatLayer.catIcon;}
      },
      shadowIcon: function(feature) {
        if (typeof (feature.attributes.count) != 'undefined')
          {return createCatLayer.shadowIcon;}
        else {return createCatLayer.shadow;}
      },
      title: function(feature) {
         if (typeof (feature.attributes.count) != 'undefined')
           {return feature.attributes.count+" "+feature.cluster[0].data.srfResponse.category+" Here";}
         else {return feature.data.srfResponse.address.name;}
      }
    }
  });        
  createCatLayer.layerCat = new OpenLayers.Layer.Vector(
    createCatLayer.catname,
    { strategies: [createCatLayer.strategy],
      styleMap: new OpenLayers.StyleMap({
        "default" :createCatLayer.defaultStyle,
        "select" : createCatLayer.selectStyle
      }),
      isBaseLayer: false,
      rendererOptions: {yOrdering: true}
    }
  );
  
  this.map.addLayer(createCatLayer.layerCat);
  createCatLayer.features = [];
  for (var i=0 ; i<srfResponse.length; i++){
    if(typeof(srfResponse[i]) !='undefined'){
      var geometry = lonLatObjFrmPoint(srfResponse[i].geom);
      createCatLayer.features.push(
        new OpenLayers.Feature.Vector( 
          new OpenLayers.Geometry.Point(geometry.lon, geometry.lat),
          { srfResponse:srfResponse[i] }
        )
      );
    }
  }
  createCatLayer.layerCat.addFeatures(createCatLayer.features)
  createCatLayer.hover = new OpenLayers.Control.SelectFeature(
    createCatLayer.layerCat, 
    { clickout:true,
      toggle:true,
      hover: false,
      opacity:1,
      highlightOnly: false
    }
  );
  this.map.addControl(createCatLayer.hover);
  createCatLayer.hover.activate();
  createCatLayer.layerCat.events.on({"featureselected": mboxObj.categoryPopup});
  createCatLayer.layerCat.events.on({"featureunselected": mboxObj.removeOpenCatPopup});
  createCatLayer.layerCat.events.on({"beforefeatureremoved": mboxObj.removeOpenCatPopup});
  ioAreaObj.displayMessage("Category Layer Has been Loaded");
  ioAreaObj.removeCurtain();
  return createCatLayer;
}

mbox.prototype.catToolTipdisplayOnOpenPopup =function () {
  //var f=event.feature;
    $('#map')[0].title=""; 
}

mbox.prototype.mapToolTipdisplayBack =function () {
    $('#map')[0].title="Right Click On Map For More Options"; 
}

mbox.prototype.getLayerByName= function (obj) {
  var name=this.map.getLayersByName(obj);
  return name;
}

mbox.prototype.categoryPopup = function(event) {
  var f=event.feature;
  ioAreaObj.displayMessage('&nbsp');
  var htmlContent;
  if (typeof(f.attributes.count) != 'undefined'){
      var max=20;
      var width =150;
      htmlContent=mboxObj.prepareContentAndReturnSizeForClusterPopUp(f);
   } else {
      var width= 200;
      htmlContent= mboxObj.prepareContentAndReturnSizeForCatPopup(f);
  }
  this.openCatPopup=new OpenLayers.Popup.Anchored("categoryPopupDiv",
  //this.openCatPopup=new OpenLayers.Popup.AnchoredBubble("categoryPopupDiv",
               new OpenLayers.LonLat(f.geometry.x,f.geometry.y),
               htmlContent.size,
               htmlContent.content,null,false
           );
  mboxObj.catToolTipdisplayOnOpenPopup();
  this.openCatPopup.setBackgroundColor("white");
  //this.openCatPopup.setBorder("4px");
  this.openCatPopup.setOpacity(1);
 // this.openCatPopup.setBorderColor("black");
  this.openCatPopup.div.style.zIndex=18000;
  this.map.addPopup(this.openCatPopup);
  mboxObj.makeToFromClickable(htmlContent);
  if (htmlContent.clusterSize){
  	for(var i=0;i<htmlContent.clusterSize;i++){
      var temp=f.cluster[i];
      $('#'+i+'catSingleName')[0].onclick=function (){
         var localIndex = parseInt(this.name);
      	 var fet=f.cluster[localIndex];
 	  	 mboxObj.transitToCategorySinglePopup(fet);
 	    // htmlContent.replaceWithSinglePopupContent.apply(this,[]);
 	  	};
 	  //$('#catSingleName'+i).click(htmlContent.replaceWithSinglePopupContent(temp))
    }
  }
  
 document.getElementById('categoryPopupDiv').setClassName='categoryPopupDiv';
 if (self.navigator.userAgent.match(/MSIE/)){
    //var newHeight=htmlContent.size.h+5;
  //  this.openCatPopup.setSize(OpenLayers.Size(htmlContent.size.w+5,htmlContent.size.h+5));
   $("#catmain").css('width','290px');
   $("#nameCat").css('width','290px');
  }
}
mbox.prototype.makeToFromClickable = function (obj){
  var htmlContent= obj;
  if (htmlContent.toFunction) {
    $('#catmainTo').click(htmlContent.toFunction);
  }
  if (htmlContent.fromFunction) {
   // attach this function to wellknown dom id 'From'
   $('#catmainFrom').click(htmlContent.fromFunction);
  }
}
mbox.prototype.prepareContentAndReturnSizeForCatPopup =function (obj){
  var f=obj;
  var max=20;
  var width =300;
  var height = 200;
  var zoom=mboxObj.getCurrentZoom();
  var htmlContent={};
  if(typeof(f.data.srfResponse.image)!='undefined') {
   var category=f.data.srfResponse.category;
   category=category.replace(/s$/,"");
   htmlContent.content="<div id='catmain' oncontextmenu='return false;' style='postion:absoulte;padding:0px; width:300px;height:"+height+"px'><div  id='nameCat' style='border:opx;padding:0px;background-color:#ff9933;text-align:center;width:300px;height:15px'><a  onfocus='this.blur();' class='cat_button' style='color:black;'><b>"+category+"</b></a></div>";
   
  
        htmlContent.content+="<div id='name' style='position:absolute;margin-top:2px;width:180px;height:150px;' ><div class='cat_button' style='text-align:left;width:100px;height:50px;postion:absolute;color:black'><b>"+f.data.srfResponse.address.name+"</b>";
   if(typeof(f.data.srfResponse.address.addr1)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.addr1;}
   if(typeof(f.data.srfResponse.address.addr2)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.addr2;}

   if(typeof(f.data.srfResponse.address.addr4)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.addr4;}
   if(typeof(f.data.srfResponse.address.addr3)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.addr3;}
   if(typeof(f.data.srfResponse.address.pin)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.pin;}
   if(typeof(f.data.srfResponse.address.phone)!='undefined'){ htmlContent.content+= "<br>Contact :"+f.data.srfResponse.address.phone;}
   
   htmlContent.content+="<br>";
   htmlContent.content+="</div>";
   htmlContent.content+="<div id='bottomAd' class='cat_button'  style ='position:absolute; bottom:-25px ;width:"+width+"px;height:20px'>";
   htmlContent.content+="Directions : </b><a id=catmainTo style='color:blue;cursor:pointer'>To </a> | <a id=catmainFrom style='color:blue;cursor:pointer'> From</a>";
   
   if(zoom<6){
   htmlContent.content+= "  |  "+" <a style='color:blue;cursor:pointer;text-align:right'onclick=\"javascript:mboxObj.zoomToBottom("+f.geometry.x+","+f.geometry.y+")\">";
    htmlContent.content+="Zoom To Street Level</a>";
   }  
   
   
   htmlContent.content+="</div></div>";
   htmlContent.toFunction = function () {
    //  alert("I am in to function ");
      f.data.srfResponse.index = -1;
      f.data.srfResponse.type = 'rcm';
      delete f.data.srfResponse.distance; 
      routeEndsObj.replaceEntity('end',f.data.srfResponse);
    }
    htmlContent.fromFunction = function () {
     // alert("I am in from function ");
      f.data.srfResponse.index = -1;
      f.data.srfResponse.type = 'rcm';
     delete f.data.srfResponse.distance; 
      routeEndsObj.replaceEntity('start',f.data.srfResponse);
    }  
   var imageSource=cloneImageUrl+f.data.srfResponse.image;
   htmlContent.content+="<div id='yo' height=80 width=80 style='border-color:#777777;border:0px;position:relative;float:right;margin-right:0px;margin-top:2px;overflow:hidden;padding:0px;background-color:#b0c4de'><a class='cat_button' style='color:black;cursor:pointer'  onclick=\"javascript:mboxObj.getBackThumbNail()\"><img id='popimage' class='imagepop' style='border:0px; padding:0px; solid white; alt='Image' height=80 width=80 src='"+imageSource+"'</a></div>";
  }else {width=120;
   height=100;
  htmlContent.content="<div id='catmain1' oncontextmenu='return false;' style='postion:absoulte; width:"+width+"px;height:"+height+"px'><div  id='nameCat1' style='border:4px;padding:0px;background-color:#ff9933;text-align:center;width:"+width+"px;height:15px'><a  onfocus='this.blur();' class='cat_button' style='color:black;'><b>"+f.data.srfResponse.category+"</b></a></div>";
   htmlContent.content+="<div id='name' style='position:absolute;width:100px;height:70px;margin-top:2px' ><div class='cat_button'  style='width:100;height:40px;text-align:left'><b>"+f.data.srfResponse.address.name+"</b>";
   if(typeof(f.data.srfResponse.address.addr4)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.addr4;}
   if(typeof(f.data.srfResponse.address.addr3)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.addr3;}
   if(typeof(f.data.srfResponse.address.pin)!='undefined'){ htmlContent.content+= "<br>"+f.data.srfResponse.address.pin;}
   if(typeof(f.data.srfResponse.address.phone)!='undefined'){ htmlContent.content+= "<br> Contact : "+f.data.srfResponse.address.phone;}
   
   htmlContent.content+="<div id='bottomAd'  class='cat_button'  style ='position:absolute; bottom:2px;left:0px;width:"+width+"px;height:20px'>"
   htmlContent.content+="Directions : </b><a id=catmainTo style='color:blue;cursor:pointer'>To </a> | <a id=catmainFrom style='color:blue;cursor:pointer'> From</a>";
   htmlContent.toFunction = function () {
    //  alert("I am in to function ");
      f.data.srfResponse.index = -1;
      f.data.srfResponse.type = 'rcm';
      delete f.data.srfResponse.distance; 
      routeEndsObj.replaceEntity('end',f.data.srfResponse);
    }
    htmlContent.fromFunction = function () {
     // alert("I am in from function ");
      f.data.srfResponse.index = -1;
      f.data.srfResponse.type = 'rcm';
     delete f.data.srfResponse.distance; 
      routeEndsObj.replaceEntity('start',f.data.srfResponse);
    } 
   if(zoom<6){
   htmlContent.content+= "  <br>  "+" <a style='color:blue;cursor:pointer;text-align:right'onclick=\"javascript:mboxObj.zoomToBottom("+f.geometry.x+","+f.geometry.y+")\">"
    htmlContent.content+="Zoom To Street Level</a>";
   }
      htmlContent.content+="</div></div>";
   }
   
 // imagePopupContent+="<div id= 'direction' style='position:relative;width:100px;margin-top:100px height= 10px;background-color:#b0c4de;color:#ffff'><a>From</a></div>";
   htmlContent.content+= "</div>";
   htmlContent.size= new OpenLayers.Size(width,height);
   return htmlContent;
}

mbox.prototype.prepareContentAndReturnSizeForClusterPopUp= function (obj){
  //var htmlContent= f.data.srfResponse.
  var zoom=mboxObj.getCurrentZoom();
  var f=obj;
  var max=20;
  var width =150;
  var height =20;
  var htmlContent={};
  htmlContent.content="<div oncontextmenu='return false;style='height=30px; width="+width+"px' ><div style='padding:0px'><div style='background-color:#ff9933'style='right:2px;left:2px'><a onfocus='this.blur();' class='cat_button' style='color:black;'><b>"+f.attributes.count+" "+f.cluster[0].data.srfResponse.category+ " Here.</b></div><div> ";
  if (zoom<=5){
   for (var i=0;i<f.cluster.length;i++){
  	height=height+15;
    var abc=f.cluster[i]
    htmlContent.content+= "<a style='color:black;cursor:pointer'  class='cat_button' onclick=\"javascript:mboxObj.zoomToBottom("+abc.geometry.x+","+abc.geometry.y+")\">"
    htmlContent.content+=abc.data.srfResponse.address.name+"<br></a>";
    if (abc.data.srfResponse.address.name.length>max){
      max=abc.data.srfResponse.address.name.length;
      width=max*7;
     
    }
     if (i==3){break;}
  }
  	  	
  //width=width+5;
  var extent =new OpenLayers.Bounds(f.geometry.bounds.left,f.geometry.bounds.bottom,f.geometry.bounds.right,f.geometry.bounds.top);
  for (i=0; i<f.attributes.count;i++){
        extent.extend(f.cluster[i].geometry);
  }
  
  htmlContent.content+= "</div><div class='simple'><a  class='cat_button' style='color:blue;cursor:pointer'  onclick=\"javascript:mboxObj.zoomToGivenBound("+extent.left+","+extent.bottom+","+extent.right+","+extent.top+")\"><b><i>Zoom</a><a class='cat_button'></i></b> in to get More info.</a></div>";}
  
  else {
  	htmlContent.clusterSize=f.cluster.length;
  	htmlContent.f=f;
  	for (var i=0;i<f.cluster.length;i++){
  	  height=height+15;
  	  htmlContent[i]= f.cluster[i];
      var abc=f.cluster[i];
      var srfResponse= abc.data.srfResponse;
      htmlContent.content+= "<a id="+i+"catSingleName name="+i+"  whichIndex= "+i+" style='color:black;cursor:pointer'  class='cat_button' >";
      htmlContent.content+=abc.data.srfResponse.address.name+"<br></a>";
      if (abc.data.srfResponse.address.name.length>max){
       max=abc.data.srfResponse.address.name.length;
       width=max*7;
      }
  	}
 }
 width=width+5;
  htmlContent.size=new OpenLayers.Size(width,height);
  // var contentSize =  
  return htmlContent;
}

mbox.prototype.getLayersByName =function (matchCat){
  
   return this.map.getLayersByName(matchCat);
}

mbox.prototype.transitToCategorySinglePopup = function (obj){
	
	var matchCat=/category/gi;
    var whichLayer= this.map.getLayersByName(matchCat);
    var htmlContent= mboxObj.prepareContentAndReturnSizeForCatPopup(obj);
    whichLayer[0].openCatPopup.setSize(htmlContent.size);
    whichLayer[0].openCatPopup.contentDiv.innerHTML= htmlContent.content;
    mboxObj.makeToFromClickable(htmlContent);
   // whichLayer[0].openCatPopup.contentDiv.innerHTML+=srfResponse.data.srfResponse.address.name;
    // whichLayer[0].map.removePopup(whichLayer[0].openCatPopup)
	
}
mbox.prototype.updateCatPopupSize =function () {//not working
 
  var tmp;
  tmp=this.map.getLayersByName ("OpenLayers.Popup.AnchoredBubble");
  this.openCatPopup.setSize(new OpenLayers.Size(500,500));
  return ;
}

mbox.prototype.enlargeThumbNail =function () {
  var divsize= $("#popimage").css("width");
  $("#nameCat").hide('slide',200);
  $("#name").hide('slide',200);
  if (self.navigator.userAgent.match(/MSIE/)){
    $("#yo").animate({width:"290px",height:"190px",left:"0px",right:"10px"},200);
    $("#popimage").animate({width:"290px",height:"190px",left:"2px",right:"10px"},200);
  } else {
    $("#yo").animate({width:"300px",height:"195px",left:"0px",right:"10px"},200);
    $("#popimage").animate({width:"300px",height:"195px",left:"2px",right:"10px"},200);
  }
}

mbox.prototype.getBackThumbNail =function () {
  var divsize= $("#popimage").css("width");
  if(divsize=="300px" || divsize =="290px"){
   $("#nameCat").show('slide',200);
   $("#name").show('slide',200);
   $("#yo").animate({width:"80px",height:"80px",left:"0px",right:"10px"},200);
   $("#popimage").animate({width:"80px",height:"80px",right:"0px",top:"2px"},200);
  } else {mboxObj.enlargeThumbNail();}  
}

mbox.prototype.removeOpenCatPopup = function() {
  if(typeof(this.openCatPopup) != 'undefined' && this.openCatPopup != null) {
    this.map.removePopup(this.openCatPopup);
    this.openCatPopup.destroy();
    this.openCatPopup=null;
    mboxObj.mapToolTipdisplayBack();
  }
}

mbox.prototype.destroyCatLayer =function () {
  var matchCat=/category/gi;
  var whichLayer= this.map.getLayersByName(matchCat);//returns an array of layers.
  //makeAllBackgroundWhite();
 // mboxObj.destroyCatLayer(nameToTest[0]);
  mboxObj.removeOpenCatPopup;
  if ( whichLayer[0]){
    whichLayer[0].removeFeatures(whichLayer[0].features);
    this.map.removeLayer(whichLayer[0]);
    whichLayer[0]=null;
    mboxObj.mapToolTipdisplayBack();
  }
}

mbox.prototype.clearCatLayer = function () {
  mboxObj.destroyCatLayer();
  mboxObj.removeOpenCatPopup();
  mboxObj.mapToolTipdisplayBack();
  makeAllBackgroundWhite();
}

mbox.prototype.zoomToBottom =function (x,y) {
  var curx=x;
  var cury=y;
  var curzoom=this.map.getZoom();
  var point = new OpenLayers.LonLat(x,y) 
  this.map.setCenter(point,6);
}

mbox.prototype.zoomToGivenBound= function (left,bottom,right,top) {
  var extent=new OpenLayers.Bounds(left,bottom,right,top);
  this.map.zoomToExtent(extent,false);
}
mbox.prototype.zoomToPfLayerExtent=function (extent){
  this.map.zoomToExtent(extent,false);	
}
mbox.prototype.undoExpandMapPopVideo = function() {
  document.getElementById('mapTd').height=500+"px";
  document.getElementById('map').style.height=525+"px";
  if(this.routeActive) {
    this.fitCurrentRoute();
  } else {
    this.map.setCenter(new OpenLayers.LonLat(globalLon, globalLat), globalZoom);
  }
  // TBD
  //if(biasWmsLayer){
  //    map.removeLayer(biasWmsLayer);
  //            map.removeLayer(vidteq.bias.biasMarkerLayer);
  //            vidteq.bias.biasMarkerLayer=null;
  //            vidteq.bias=null;
  //            map.layers[1].setOpacity(1)
  //            document.getElementById('map').title='Right Click on Map for more options';
  //            removeBiasLegend();
  //            //$('#biaslink')[0].onclick=biasMap;
  //    
  //    }
}

mbox.prototype.expandMapPopVideo = function() {
  //document.getElementById('mapTd').height=document.body.offsetHeight-450+"px";
  //document.getElementById('map').style.height=document.body.offsetHeight-450+"px";
  if(this.routeActive) {
    this.fitCurrentRoute();
  } else {
    this.map.setCenter(new OpenLayers.LonLat(globalLon, globalLat), globalZoom);
  } 
}

mbox.prototype.addEmbedCenter = function () {
  if(ioAreaObj.embed) {
    if(ioAreaObj.embed.fix=='start') {
      ioAreaObj.disableField({a:'starttextbox'});
      ioAreaObj.enableField({b:'endtextbox'});
    } else if(ioAreaObj.embed.fix=='end') {
      ioAreaObj.disableField({a:'endtextbox'});
      ioAreaObj.enableField({b:'starttextbox'});
    }
    // TBD this does not belong here
    var entity = ioAreaObj.getEntity.apply(ioAreaObj,['center',1]);
    entity=ioAreaObj.prepareCenterEntity(entity); 
    routeEndsObj.addByIndex(ioAreaObj.embed.fix,1,'center'); 
    if(ioAreaObj.embed.place.popup && ioAreaObj.embed.place.popup.open==1) mboxObj.popoutCenterPlace(); 
  }
}

mbox.prototype.popoutCenterPlace =function (e) { 
  //whichObject=(ioAreaObj.embed.fix=='start')?(mboxObj.startMarker):(mboxObj.endMarker);
  var myCenter = routeEndsObj.getCenter();
  if (typeof(myCenter) == 'undefined' || myCenter == null || 
      !myCenter.markerIndex) {
  }
  var whichObject=mboxObj.allMarkers[myCenter.markerIndex];
  if(self.navigator.appName.match(/Microsoft/i)) {  
    try { whichObject.events.listeners['click'][0].func.apply(whichObject,[window.event]); } catch(e) {}
  } else {  
    evt={};
    window.event=evt;
    whichObject.events.listeners['click'][0].func.apply(whichObject,[evt]);
  }
}

mbox.prototype.popoutTheMinimap = function () {
  var h=typeof(ioAreaObj.embed.expandTo.height)!='undefined'?ioAreaObj.embed.expandTo.height:600;
  var w=typeof(ioAreaObj.embed.expandTo.width)!='undefined'?ioAreaObj.embed.expandTo.width:800;
  w=w<=800?800:w;
  h=h<=600?600:h;
  var url="http://"+document.location.host+"/stage/embed2.php?q="+ioAreaObj.embed.expandTo.et+"&place="+JSON.stringify(ioAreaObj.embed.expandTo.place);
  url+="&pf=2&h="+h+"&w="+w; 
  window.open(url,'Vidteq','status=1,width='+w+',height='+h+',scrollbars=0,resizable=1');
}   

//New Layer to show the upcoming projects and landmarks specific to a particular project
//Named as proximity feature Layer
mbox.prototype.createPfLayer = function (response) {
	//ioAreaObj.changeBackOpacity(0.2);
  response= JSON.parse(response);
  var landMarkLayer={};
  // the response will contain a variety of geometries 
  //store it in a geometry components
  var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style.fillOpacity = 0.8;
    layer_style.strokeColor="#00FF00";
    layer_style.graphicOpacity = 1;
    var count=200;
    landMarkLayer.defaultStyle= new OpenLayers.Style({//style for default feature 
      fill : "${fill}",
      fillOpacity: 0.4,
      fillColor: "${fillColor}",
      pointRadius: "${pointRadius}",
      stroke: true,
      strokeColor:"${strokeColor}",
      strokeWidth: "${strokeWidth}",
      graphicTitle: "${title}",
      strokeDashstyle: "${strokeDashstyle}",
      label: "${label}",
      graphicTitle: "blah",
      labelAlign: "${labelAlign}",
      fontColor: "${fontColor}",
      fontWeight:"bold",
      labelXOffset:"30",
      labelYOffset:"-20",
      display:"${display}",
      fontSize: 12
    },
    { context : {
      pointRadius : function(feature) {
      	
        if (typeof (feature.data.style) != 'undefined') {
        	//var tmp = JSON.parse(feature.data.style);
        	if (typeof (feature.data.style.pointRadius) != 'undefined') {
             return feature.data.style.pointRadius;
          } else { return "6"; }
        } else { return "6"; }
      },
      strokeDashstyle : function(feature) {
        if (typeof (feature.data) != 'undefined') {
         if(typeof(feature.data.strokeStyle)!='undefied')
          {if (feature.data.strokeStyle=='dashdot'){ return "dashdot";}}
          
        }
      },
      display: function (feature){
      	if (typeof(feature.data.style)!='undefined' ){
      	   if (feature.data.style.noDisplay){ return "none";}
      	}
      	else { return  true;}//it does'nt hv a effect  except none
      	},
      labelAlign : function (feature) {
      	
        if (typeof (feature.data.style) != 'undefined') {
          if (typeof (feature.data.style.labelAlign) != 'undefined') {
            return feature.data.style.labelAlign;
          } 
        } 
        else return "lc";
      },
      fill : function  (feature) {
      	var zoom=mboxObj.getCurrentZoom();
      	if (zoom<3){ return 0; }
      	return 1;
     	},
      fillColor : function (feature) {
      	 if (typeof (feature.data.code)!= 'undefined'){
      	 	 if (feature.data.code==12){ return '#abababa'}//commercial
      	 	 if (feature.data.code==13){ return '#cccccc'}//industrial
      	 	 if (feature.data.code==14){ return '#0000ff'}//waterbodies
      	 	 if (feature.data.code==15){ return '#e5e5e5'}//openSpace
      	 	 if (feature.data.code==16){ return '#00ff00'}//agriculture
      	 	 if (feature.data.code==17){ return '#'}//Utilities 
      	 	 if (feature.data.code==11){ return '#ffc0cb'}//residential
      	 	 if (feature.data.code==18){ return '#c887b1'}//public
      	 	}
      },
      label :function(feature) {
        var zoom=mboxObj.getCurrentZoom();
         if (typeof (feature.data.style) != 'undefined') {
           if (typeof (feature.data.style) != 'undefined' && 
            typeof (feature.data.style.zoomMin) != 'undefined' &&
            typeof (feature.data.style.zoomMax) != 'undefined' &&
            (zoom < feature.data.style.zoomMin || zoom > feature.data.style.zoomMax)) { return ""; }
          if (typeof (feature.data.label)!= 'undefined'){
            return feature.data.label;}
		 }
	          else  return ""; 
      },
      fontColor: function (feature) {
        if (typeof (feature.data.style) != 'undefined') {
          return feature.data.style.fontColor;
        } 
      },
      strokeColor: function(feature) {
         if (typeof (feature.data) != 'undefined') {
           if (typeof (feature.data.strokeColor) != 'undefined') {
             return feature.data.strokeColor;
           }
        }  else return "0000ff";
      },
      strokeWidth: function(feature) {
       var zoom=mboxObj.getCurrentZoom();
        if (typeof (feature.data) != 'undefined') {
          if (typeof (feature.data.strokeWidth) != 'undefined') {
          	 var size=feature.data.strokeWidth;
             return size;
          } 
        } 
      }
    }});   
    landMarkLayer.layer = new OpenLayers.Layer.Vector(
              "LandMarkLayer",
               {
               styleMap: new OpenLayers.StyleMap({
                 "default" :landMarkLayer.defaultStyle
               }), isBaseLayer: false
    });
    landMarkLayer.layerPolygon = new OpenLayers.Layer.Vector(
              "LandMarkLayerPolygon",
               {
               styleMap: new OpenLayers.StyleMap({
                 "default" :landMarkLayer.defaultStyle
               }), isBaseLayer: false
    });
  var features = [];
  var featuresPolygon = [];
  var srfResponse = response.srf[0].results;
  for (var i=0 ; i<srfResponse.length; i++){
     if(typeof(srfResponse[i]) !='undefined' && typeof(srfResponse[i].lineStyle) !='undefined'){
       var line=srfResponse[i].geom;
       var style=JSON.parse(srfResponse[i].lineStyle);
       var m=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.fromWKT(line),style);
      features.push(m);
     }
  }
  for (var i=0 ; i<response.srf[1].results.length; i++){
    var v = new OpenLayers.Geometry.fromWKT(response.srf[1].results[i].geom);
    var style = JSON.parse(response.srf[1].results[i].style);
   response.srf[1].results[i].style= style;
    var p = new OpenLayers.Feature.Vector(v,response.srf[1].results[i]);
    features.push(p);
  }
  landMarkLayer.layer.addFeatures(features);
  for (var i=0 ; i<response.srf[2].results.length; ++i){
    if (typeof(response.srf[2].results[i].geom)!='undefined'){
      var w = new OpenLayers.Geometry.fromWKT(response.srf[2].results[i].geom);
      var x=new OpenLayers.Feature.Vector(w,response.srf[2].results[i]);
      featuresPolygon.push(x);
     }
  }
  var featuresClickable=[]
  for (var i=0;i<response.srf[3].results.length;i++){
  	  mboxObj.createPfClickableMarkers(response.srf[3].results[i]);
  	  var v = new OpenLayers.Geometry.fromWKT(response.srf[3].results[i].geom);
     var style = JSON.parse(response.srf[3].results[i].style);
   response.srf[3].results[i].style= style;
     var p = new OpenLayers.Feature.Vector(v,response.srf[3].results[i]);
    featuresClickable.push(p);
  }
  landMarkLayer.layer.addFeatures(featuresClickable);
  landMarkLayer.layer.addFeatures(featuresPolygon);
  landMarkLayer.select = new OpenLayers.Control.SelectFeature(
                    landMarkLayer.layer, 
                    { clickout:false,
                      toggle:false,
                      hover: true,
                      highlightOnly: true
                   });
  this.map.addControl(landMarkLayer.select);
 // landMarkLayer.select.activate();
  this.map.addLayer(landMarkLayer.layer);
  this.map.addLayer(landMarkLayer.layerPolygon)
  this.map.setLayerIndex (landMarkLayer.layer,2);
  this.map.setLayerIndex (landMarkLayer.layerPolygon,1);
  var pfLayerExtent=landMarkLayer.layer.getDataExtent();
  mboxObj.clearRouteAndSrf();
  mboxObj.zoomToPfLayerExtent(pfLayerExtent);
  ioAreaObj.changeBackOpacity(1);
   
}

mbox.prototype.removePfLayer = function  () {
  var matchLayer=/LandMarkLayer/gi;
  var whichLayer= this.map.getLayersByName(matchLayer);//returns an array of layers.
  for (var i=0 ; whichLayer[i]; i++){
   //if ( whichLayer[i]){
    whichLayer[i].removeFeatures(whichLayer[i].features);
    this.map.removeLayer(whichLayer[i]);
    whichLayer[i]=null;
    //}
  }
  this.pfLayerMarkers.clearMarkers();
}

mbox.prototype.createPfClickableMarkers = function (response) {
	
	var lonLat = mboxObj.lonLatObjFrmPoint(response.geom);
	var size;
	if (response.size){	size = new OpenLayers.Size(response.size,response.size);}
	else{ size=new OpenLayers.Size(25,25);}
	//var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    var iconImage= imageLogosLoc+""+response.icon;
    var icon =   new OpenLayers.Icon(iconImage,size);
	var marker = new OpenLayers.Marker(new OpenLayers.LonLat(lonLat.lon,lonLat.lat),icon);
	
	//marker.content=mboxObj.prepareContent4PfLayerClickable(response);
	marker.content="<div class='cat_button' style='margin-top:5px;margin-left:4px;width:190px;height:140px;border-style:solid;border-width:1px;text-align:center'>";
	marker.content+="<div style='width:186px;background-color:#CCFFFF;margin-top:2px;margin-left:2px'><b>"+response.name+"</b></div>";
	marker.content+= "<br><div style:'font-size=10px'>"+response.description+"</div>";
	//response.distance="5km";
	var response1= JSON.parse(response.style);
	//if (parseInt(response1.giveDistance)){
	   marker.content+="<div style='position:absolute;bottom:10px;left:20px;text-align:left'><b> Approx. Distance From Project: </b>"+response.distance+"KM</div>";
//}
	marker.content+="</div>"
    //marker.size=marker.content.size;
      //m.events.register("mouseover",m,function () {mboxObj.popupBiasWfsLayer.apply(mboxObj,[]);})
      marker.events.register("mouseover",marker,mboxObj.popupBiasWfsLayer);
      marker.events.register("mouseout",marker,function () { mboxObj.map.removePopup(mboxObj.biasPopup)});
	marker.size= new OpenLayers.Size(200,145);
	//marker.events.register('mousedown', marker, function(evt) {  OpenLayers.Event.stop(evt); });
	//marker.evernts.register('loadstart',marker.functio(evt) {mboxObj.addOrRemovepfMarker(evt);OpenLayers.Even.stop(evt);})
	//marker.setOpacity(.9);
	this.pfLayerMarkers.addMarker(marker);
	//this.map.addLayer(pfLayerMarkers);
	
}

mbox.prototype.prepareContent4PfLayerClickable =function (response){
	var htmlContent;
	htmlContent= "<div id='pfClickable'> ";
	htmlContent+=  "<div  oncontextmenu='return false;style='height=30px;>"+response.name+"</div>";
	htmlContent+= "<div id= 'pfDesc'>"+response.description+"</div>";
	htmlContent.size= new OpenLayers.Size (300,300);
	return htmlContent;
	}
mbox.prototype.addOrRemovepfMarker = function (evt) {
   zoom =mboxObj.getCurrentZoom;
   if (zoom < 4){
   	 var matchCat=/pfLayerMarker/gi;
     var whichLayer= this.map.getLayersByName(matchCat);
     whichLayer.removeFeature(whichlayer.features) ;
   }	
  //else {mboxObj.createPfClickableMarkers;}
}
function routeEnds () {
  this.start = {};
  this.end = {};
}

// RouteEnd functions
routeEnds.prototype.isNotEmpty = function(which) {
  if (typeof(this[which]) == 'undefined' || this[which] == null) return false ;
  for(var prop in this[which]) {
    if(this[which].hasOwnProperty(prop)) return true; 
  }
  return false;
}

routeEnds.prototype.isEqual = function(which,entity) {
  if (!this.isNotEmpty(which)) return false;
  if (this[which] == entity) return true;
  // not sure if above statement works
  //if (this[which].index == entity.index &&
  //    this[which].parentType == entity.parentType) return true;
  return false; 
}

routeEnds.prototype.get = function(which) {
  if (!this.isNotEmpty(which)) return null;
  // TBD we need store a PreRoute version
  var pObj=mboxObj.lonLatObjFrmPoint(this[which].geom);
  var str = pObj.lon+","+pObj.lat;
  return (str);
}

routeEnds.prototype.getRouteStr = function() {
  this.link=encodeURI("?q=route&start="+this.get('start')+"&end="+this.get('end'));
  return (this.link);
}

routeEnds.prototype.refresh = function(which) {
  if (!this.isNotEmpty(which)) return;
  if (this[which].type && (this[which].type == 'center' || this[which].type == 'rcm')) {
    mboxObj.removeStartEndPoint(which);
    mboxObj.putStartEndPoint(which,this[which]);
  } else {
    mboxObj.refreshLocatorPoint(this[which]);
  }
}

routeEnds.prototype.detach = function(which) {
  if (!this.isNotEmpty(which)) return;
  if (!this[which].type || this[which].type != 'center') {
    
    //this[which].icon = (which == 'start') ? startIcon : endIcon;
    this[which].icon = (which == 'start') ? mboxObj.startIcon : mboxObj.endIcon;
    this[which].index = -1;
    this[which].type = 'rcm';
  }
  // TBD do I show ?
}
routeEnds.prototype.replaceEntity = function(which,entity) {
  this.remove(which);
  this.add(which,entity);
}

routeEnds.prototype.replace = function(which,index,source) {
  this.remove(which);
  this.addByIndex(which,index,source);
}

routeEnds.prototype.remove = function(which,removeCenterAsWell) {
  if (!this.isNotEmpty(which)) return;
  if (this[which].type && this[which].type == 'center') {
    if (typeof(removeCenterAsWell) == 'undefined' || !removeCenterAsWell) return;
  }
  if (this[which].index == -1 ) {
    mboxObj.removeStartEndPoint(which);
    this[which]={};
  } else { 
    var entity = this[which];
    if (this[which].type && this[which].type == 'center') {
      mboxObj.removeStartEndPoint(which);
    } else {
      this[which] = {};
      mboxObj.refreshLocatorPoint(entity);
    }
    if (mboxObj.isPopupActiveFor(entity)) {
      if (entity.icon) document.getElementById('popupIcon').src=entity.icon.mapUrl;
      if (entity.markIcon) document.getElementById('popupIcon').src=entity.markIcon.mapUrl;
      // TBD - rather remove the popup, icon is not present in some cases
    }
  }
  this[which] = {};
}

routeEnds.prototype.addByIndex = function(which,index,source) {
  if ( index == -1 ) { // RCM case
    this[which] = {
      index : index,
      type  : 'rcm', 
      lonlat : { lon : source.lon, lat : source.lat },
      geom : "POINT("+source.lon+" "+source.lat+")",
      address : { name : 'tbd' }
    };
    mboxObj.putStartEndPoint(which,this[which]);
    ioAreaObj.getRoadName(source,which);  // return TBD
  }  else { // srf select case
    this[which] = ioAreaObj.getEntity.apply(ioAreaObj,[source,index]);
    // Catch - remove other end if other end is same as this end
    var notOfWhich = 'end';
    if (which == 'end') notOfWhich = 'start';
    if (this.isNotEmpty(notOfWhich) && this[which] == this[notOfWhich] ) 
      this.remove(notOfWhich);
    if (source == 'center') {
      mboxObj.putStartEndPoint(which,this[which]);
    } else { 
      mboxObj.refreshLocatorPoint(this[which]);
    }
    //var iconUrl = startIconUrl;
    var iconUrl = imagePathsObj.startIconUrl;
    //if(which=='end') iconUrl = endIconUrl;
    if(which=='end') iconUrl = imagePathsObj.endIconUrl;
    if (this[which].type && this[which].type == 'center' && this[which].icon) iconUrl = this[which].icon.mapUrl;
    if (mboxObj.isPopupActiveFor(this[which])) document.getElementById('popupIcon').src=iconUrl;
    var name = this.getName(which);
    ioAreaObj.fillIoForm.apply(ioAreaObj,[which,name]);
  }
}

// small function till we make everything ok
routeEnds.prototype.getName = function(which) {
  var name;
  if (typeof(this[which].name)!='undefined') name = this[which].name;
  if (typeof(this[which].address)!='undefined' &&
      typeof(this[which].address.name)!='undefined') name = this[which].address.name;
  if (typeof(name) == 'undefined') name = this[which].geom;
  return name;
}

routeEnds.prototype.add = function(which,entity) {
  this[which] = entity;
  // Catch - remove other end if other end is same as this end
  var notOfWhich = 'end';
  if (which == 'end') notOfWhich = 'start';
  if (this.isNotEmpty(notOfWhich) && this[which] == this[notOfWhich] ) 
    this.remove(notOfWhich);
  if (this[which].type && this[which].type == 'rcm') { 
    mboxObj.putStartEndPoint(which,this[which]);
    if ((typeof(this[which].address)!='undefined' &&
        typeof(this[which].address.name)!='undefined') || 
        typeof(this[which].name!='undefined')) {
      ioAreaObj.fillIoForm.apply(ioAreaObj,[which,this.getName(which)]);
    } else {
      ioAreaObj.getRoadName(this[which].lonlat,which);  // return TBD
    }
  } else { // srf select case
    if (this[which].type && this[which].type == 'center') {
      mboxObj.putStartEndPoint(which,this[which]);
    } else { 
      mboxObj.refreshLocatorPoint(this[which]);
    }
    //var iconUrl = startIconUrl;
    var iconUrl = imagePathsObj.startIconUrl;
    //if(which=='end') iconUrl = endIconUrl;
    if(which=='end') iconUrl = imagePathsObj.endIconUrl;
    if (this[which].type && this[which].type == 'center' && this[which].icon) iconUrl = this[which].icon.mapUrl;
    if (mboxObj.isPopupActiveFor(this[which])) document.getElementById('popupIcon').src=iconUrl;
    var name = this.getName(which);
    ioAreaObj.fillIoForm.apply(ioAreaObj,[which,name]);
  }
}

routeEnds.prototype.swap = function() {
  var startPresent = this.isNotEmpty('start');
  var endPresent = this.isNotEmpty('end');
  var start,end;
  if (startPresent) {
    start = this['start'];
    this.remove('start',true);
  }
  if (endPresent) {
    end = this['end'];
    this.remove('end',true);
  }
  if (startPresent) { this.add('end',start); }
  if (endPresent) { this.add('start',end); }
}

routeEnds.prototype.getCenter = function() {
  if (this.isNotEmpty('start') && this['start'].type && this['start'].type == 'center') { return this['start']; }
  if (this.isNotEmpty('end') && this['end'].type && this['end'].type == 'center') { return this['end']; }
  return null;
}



