/*
 * 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();
  this.gui.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();
  this.gui.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 globalLon = 77.6;
//var globalLat = 12.96;
//var globalZoom = 10;

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

  var that = this;
  this.routeStyle = OpenLayers.Util.applyDefaults({
    graphicZIndex: 101,
    strokeWidth: 8,
    cursor:'hand',
    strokeColor: "#9900CC",
    fillOpacity: 0,
    strokeOpacity: .6
  }, OpenLayers.Feature.Vector.style['default']);
  this.routeEMapStyle= new OpenLayers.Style (
    {
      graphicZIndex: 101,
      strokeWidth: 2,
      cursor : "pointer",
      strokeColor: "${strokeColor}",
      graphicTitle:"routeno"
    },
    //{ context :{ strokeColor : function (feature) { var col = "rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")"; console.log(col); return col; } } }
    { context :{ 
       strokeColor : function (feature) { if (feature.eMapColor) { return feature.eMapColor; } else { return "#9900CC"; } },
       routeno : function(feature) { return  "OKE";} 
     } }
  );
  if (typeof(missingVideoDebug) != 'undefined' &&  missingVideoDebug) {
    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.srfLayerStyle= new OpenLayers.Style (
  //  {
  //    externalGraphic : "${icon}",
  //    graphicWidth : 30,
  //    graphicHeight : 30,
  //    //graphicYOffset : -30,//am putting this as it seems there's a lit shift down in vector layer than the original marker layer
  //    graphicTitle: 'Click to get information about this place'
  //  },
  //  { context :{
  //    icon : function (feature) {
  //      if (feature.data.type=='center'){ return feature.data.icon.mapUrl;
  //      } else if (feature.data.startOrEnd=='start'){ return that.startIcon.mapUrl;
  //      } else if(feature.data.startOrEnd=='end'){ return that.endIcon.mapUrl;  
  //      } else return feature.data.markIcon.mapUrl 
  //    }
  //  }}
  //);
  this.carMarkLayerStyle= new OpenLayers.Style (
    {
      externalGraphic : imagePathsObj.car+'?r='+cfg._rStr,
      //externalGraphic : "${icon}",
      graphicOpacity : "${opac}",
      cursor : "pointer",
      graphicWidth : 24,
      graphicHeight : 24,
      graphicYOffset : -12,
      graphicXOffset : -12,
      //graphicZIndex: 4000,
      graphicTitle: "Drag me to move along the route"
    },
    { context :{ opac : function (feature) { if (feature.data.shadow) {return 0.5;} else {return 1;} } } }
  );
 
  this.textDirStyle= new OpenLayers.Style (
    {
      externalGraphic : "${icon}",
      graphicWidth : 16,
      graphicHeight : 16,
      graphicYOffset : -16,
      graphicXOffset : -16,
      graphicTitle: "${title}"
    },
    { context :{ icon : function (feature) { return feature.data.icon; },
                 title : function (feature) { return feature.data.title; } } }
  );
  this.busStopsStyle= new OpenLayers.Style (
    {
      externalGraphic : "${icon}",
      graphicWidth : 16,
      graphicHeight : 16,
      graphicYOffset : -16,
      graphicXOffset : -16,
      graphicTitle: "${title}"
    },
    { context :{ icon : function (feature) { return imagePathsObj.busStop; },
                 title : function (feature) { return feature.data.title; } } }
  );
  this.imageOnRouteStrategy = new OpenLayers.Strategy.Cluster({distance:10,threshold:2});
  this.imageOnRouteStyle= new OpenLayers.Style (
    {
      //externalGraphic : "${icon}",
      externalGraphic : imagePathsObj.poi+'?r='+cfg._rStr,
      graphicWidth : 10,
      graphicHeight : 10,
      cursor : "pointer",
      //graphicZIndex: 3999,
      //graphicYOffset : -30,//am putting this as it seems there's a lit shift down in vector layer than the original marker layer
      graphicTitle: 'Click to see image'
    },
    { context : { icon: imagePathsObj.poi+'?r='+cfg._rStr }}
  );
  this.startEndStyle= new OpenLayers.Style ({
    externalGraphic : "${icon}",
    graphicWidth: "${graphicWidth}",
    graphiHeight : "${graphiHeight}",
    cursor : "pointer",
    display : "${display}",
    //graphicYOffset : 0,//am putting this as it seems there's a lit shift down in vector layer than the original marker layer
    //graphicXOffset : 0,//am putting this as it seems there's a lit shift down in vector layer than the original marker layer
    graphicTitle: "${title}"
  },
  {context :{
    icon : function (feature) {
      if ((feature.data.type=='center' || feature.data.type=='via') && feature.data.icon) {
        return feature.data.icon.mapUrl;
      } else if (feature.data.startOrEnd=='start'){
        return that.startIcon.mapUrl;
      } else if(feature.data.startOrEnd=='end'){
        return that.endIcon.mapUrl;  
      } else { return  null;}
    },
    graphicWidth : function(feature) {
      if (feature.data.icon){ return feature.data.icon.w; }
      else return 32;
    },
    graphicHeight : function(feature) {
      if (feature.data.icon){ return feature.data.icon.h; }
      else return 32;
    },
    title : function (feature) {
      if (feature.data.type=='via'){
        return 'Via Place';
      } else if (feature.data.type=='center'){
        return feature.data.address.name;
      } else if (feature.data.startOrEnd=='start'){
        return 'Start Place';
      } else if(feature.data.startOrEnd=='end'){
        return 'End Place';  
      } else return  null;
    },
    display : function (feature) {
      if (feature.data.dontDisplay) { return 'none'; }
        return true; 
    }
  }});
  this.landmarkStyle= new OpenLayers.Style(
    {//style for default feature 
      graphicZIndex: 10,
      strokeWidth: 2,
      strokeColor: "#3d71bf",
      fillColor: "${fillColor}",
      //stroke: true,
      // backgroundGraphicZIndex: 10000,
      // pointRadius: 16,
      externalGraphic : "${icon}",
      graphicWidth: "${graphicWidth}",
      graphiHeight : "${graphiHeight}",
      //graphicXOffset: "${labelXOffset}",
      //graphicYOffset: "${labelYOffset}",
      backgroundHeight: 25,
      graphicTitle : "${title}",
      display : "${display}"
    },
    {  context : {
      icon : function(feature) {
        if (typeof (feature.attributes.count) != 'undefined') {
          var mainPoint=feature.cluster[0];
          for (var i in feature.cluster) {  
            var curPri=parseInt(feature.cluster[i].data.priority);
            var lastPri=parseInt(mainPoint.data.priority);
            if (curPri>=lastPri){
              mainPoint=feature.cluster[i];
            }
          }
          return  cfg.imageLogosLoc+"landmark/"+mainPoint.data.icon;
        } else {return  cfg.imageLogosLoc+"landmark/"+feature.data.icon}
      },
      strokeWidth : function (feature){
        if (typeof(feature.data.strokeWidth)!='undefined' && feature.data.strokeWidth){
          return feature.data.width;           
        }  else return 0;
      },
      strokeColor : function (feature) {
        if (typeof(feature.data.strokeColor)!='undefined' && feature.data.strokeColor){
          return feature.data.strokeColor;
        } else return "";
      },
      title : function (feature) {
        if (typeof(feature.data.name)!='undefined' && feature.data.name)
          return feature.data.name;
        else return "Blah";
      },
      fillColor :function  (feature) {
        if (typeof(feature.data.fillColor)!='undefined' && feature.data.fillColor){
          return feature.data.fillColor;
        } else return "";
      }, 
      graphicWidth : function(feature) {
        if (feature.data.width){ return feature.data.width;             }
        else return 20;
      },
      graphicHeight : function(feature) {
        if (feature.data.height){ return feature.data.height; }
        else return 25;
      },
      labelXOffset : function (feature){
        if (typeof(feature.data.xoffset) != 'undefined' && feature.data.xoffset){
          return feature.data.xoffset;
        } else return 0;
      },
      labelYOffset : function (feature){
        if (typeof(feature.data.yoffset) != 'undefined' && feature.data.yoffset){
          return feature.data.yoffset;
        } else return 0;
      },
      display : function (feature){
        var displayValMin = 'none';
        var displayValMax = 'none';
        //var zoom=mboxObj.getCurrentZoom();
        var zoom=that.getCurrentZoom();
        if (typeof(feature.data.minzoom)!='undefined' &&
             zoom >= parseInt(feature.data.minzoom )) {
          displayValMin = 1;
        }
        if (typeof(feature.data.maxzoom)!='undefined' &&
             zoom <= parseInt(feature.data.maxzoom )) {
          displayValMax = 1;
        }
        if (displayValMin == 1 && displayValMax == 1) { return 1; }
        return 'none';
      }
    }
  });
  this.pfLayerStyle= new OpenLayers.Style(
    {
      //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: 8
    },
    { context : {
      pointRadius : function(feature) {
        if (typeof (feature.data.style) != 'undefined' && feature.data.style) {
          //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' && feature.data.style ){
      	  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' && feature.data.style) {
          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' && feature.data.style &&
              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' && feature.data.style) {
          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;
          } 
        } 
      }
  }});   
  this.srfStyle= new OpenLayers.Style ({
    externalGraphic : "${icon}",
    graphicWidth : 30,
    graphicHeight : 30,
    cursor:'pointer',
    display: "${display}",
    //graphicYOffset : -30,//am putting this as it seems there's a lit shift down in vector layer than the original marker layer
    graphicTitle: 'Click to get information about this place'
  },
  {context :{
    icon : function (feature) {
      if (feature.data.type=='center' && feature.data.icon){ 
        return feature.data.icon.mapUrl;
      } else if (feature.data.startOrEnd=='start'){ 
        return that.startIcon.mapUrl;
      } else if(feature.data.startOrEnd=='end'){ 
        return that.endIcon.mapUrl;  
      } else if (feature.data.markIcon){ 
        return feature.data.markIcon.mapUrl; 
      } else {  
        return null; 
      } 
    },
    display : function (feature) {
      if (feature.data.seFeature) { return 'none'; }
      return true; 
    }
  }});
  this.rcmItems = [
    { id:"clearoption0",text:"Clear",disabled:false,
      cond: function () {
       if (document.getElementById("clearroutetab") && (document.getElementById("clearroutetab").className!='maptabdisabled' || document.getElementById("clearroutetab").className!='maptabdisabled1')) { return true; } else { return false; }
      },
      onClickFunc: function () { clearAll(); }
    },
    { id:"clearoption1",text:"Clear",disabled:true,
      cond: function () {
       if (document.getElementById("clearroutetab") && (document.getElementById("clearroutetab").className!='maptabdisabled' || document.getElementById("clearroutetab").className!='maptabdisabled1')) { return false; } else { return true; }
      },
      onClickFunc : function () { void(0); }
    } ,
    { id:"locateStores",text:"Locate Nearest Store",disabled:false,
      cond: function () {
        if(ioAreaObj.embed && ioAreaObj.embed.locateStores) { return true; } else { return false; }
      },
      onClickFunc : function () { ioAreaObj.setupAndCallNBS({point:mboxObj.rcmLonlat,tip:'start'}); }
    },
    { id:"viaoption0",text:"Via",disabled:false,
      cond: function () {
        if(ioAreaObj.embed && ioAreaObj.embed.locateStores && mboxObj.routeActive) { return true; } else { return false; }
      },
      onClickFunc : function () { ioAreaObj.placeViaAndRoute(mboxObj.rcmLonlat); }
    },
    { id:"viaoption1",text:"Via",disabled:false,
      cond: function () {
        if(ioAreaObj.embed && ioAreaObj.embed.locateStores) { return false; } else { if (mboxObj.routeActive) { return true; } else { return false; } }
      },
      onClickFunc : function () { ioAreaObj.placeViaAndRoute(mboxObj.rcmLonlat); }
    },
    { id:"startoption",text:"Directions From",disabled:false,
      cond: function () {
        if(ioAreaObj.embed && ioAreaObj.embed.locateStores) { return false; } else { return true; }
      },
      onClickFunc : function () { 
        mboxObj.addRcmStartOrEndMarker.apply(mboxObj,['start',mboxObj.rcmLonlat]); 
        if (ioAreaObj.embed) { ioAreaObj.goVid(); }
      }
    },
    { id:"endoption",text:"Directions To",disabled:false,
      cond: function () {
        if(ioAreaObj.embed && ioAreaObj.embed.locateStores) { return false; } else { return true; }
      },
      onClickFunc : function () { 
        mboxObj.addRcmStartOrEndMarker.apply(mboxObj,['end',mboxObj.rcmLonlat]); 
        if (ioAreaObj.embed) { ioAreaObj.goVid(); }
      }
    },
    { id:"govidoption",text:"GO VID",disabled:false,
      cond: function () {
        if (mboxObj.routeActive) { return false; } else { return true; }
      },
      onClickFunc : function () { ioAreaObj.invokeTheMode.apply(ioAreaObj,[]); return false; }
    }
  ];
  //this.routeEnds = new routeEnds();
  this.init();
}

mbox.prototype.overrideOLClasses=function () {
  var that = this;
  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) {
      that.killRcmPopup();
      if (that.mapClickToGuiFunc) { that.mapClickToGuiFunc(); }
      // TBD need to be attached properly
     // if (mboxObj.imagetab.active) { mboxObj.popupWfsLayer.apply(mboxObj,[e]) }
      if(typeof(__experimentalUI)!='undefined' && __experimentalUI) closeAnyDropDowns();
      if(this.map.popups.length > 0 && 'undefined' != typeof(accountDetails) && accountDetails.q == 'locatestores'){
    	if(that.catMngr){
	  that.catMngr.removeOpenCatPopup(e);
	}
      }
      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) {
      that.killRcmPopup();
      if (that.mapDblClickToGuiFunc) { that.mapDblClickToGuiFunc(); }
      // TBD need to be attached properly
       if(typeof(__experimentalUI)!='undefined' && __experimentalUI) closeAnyDropDowns();
       return false;
   }
  });
} 
  
//var myZoomis;
mbox.prototype.init = function () {
  try {
    if(this.gui.embed ) {
      if (accountDetails.q == 'EScheduler' && 
          !this.gui.embed.firstTimeRule) {
        this.eMap= new _eMap(this,accountDetails.mode);
      }
      if (typeof(accountDetails.config.landMarkLayer)!= 'undefined' && parseInt(accountDetails.config.landMarkLayer)) {
        callMakeLandMarkLayer(); 
      }
      // Access to accountDetails is not appropriate for mbox - TBD
    } else {
      if (self.navigator.userAgent.match(/MSIE\s[6]/)){//switch for disabling the Cat Scroll Panel in case of MSIE
        $("#scrolltabv").css('display','none');
      }else{
        $("#scrolltabv").css('display','none');
        //this.catMngr = new _catMngr(this,'h');
        this.catMngr = new _catMngr(this,'h',40);
        //call explicitly to create brand icon bar
        this.catMngr.getAndCreateBrandScroll();
      }
    }
  } catch(e) {};
  this.overrideOLClasses();     
  this.locatorPoint = new Array();
  //this.allMarkers = new Array();
  this.viaBallSize = new OpenLayers.Size(24,24);
  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.imageBusStopIconUrl = imagePathsObj.biasstops;
  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],
    resolutions: cfg.resolutions.split(','),
    //maxExtent:new OpenLayers.Bounds (76.9921875,12.3046875,78.22265625,13.7109375),
    maxExtent:new OpenLayers.Bounds.fromString(cfg.maxExtent),
    fallThrough:true,
    controls: [],
    theme:null
 
  }
  //console.log("one ...");
  this.map = new OpenLayers.Map( this.mapDom , mapOptions );
  //this.map.panTween = new OpenLayers.Tween(OpenLayers.Easing.Linear.easeIn);
  this.map.panDuration = 200;
  
  //console.log("two ...");
  
  // now layer creation
  // layer index 2 - base layer
  this.baseLayer = new OpenLayers.Layer.WMS( "BANGALORE_ALL",
       //tilecacheBaseUrl,
       cfg.tilecacheBaseUrl,
    //{ layers: tilecacheBaseLayer,
    { layers: cfg.tilecacheBaseLayer,
      format: 'image/png' },
    {  attribution: '<div><a style=text-decoration:none;height:55px;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=55px; width=80px; style=border:0px solid black;text-decoration:none;height:55px;width:80px;background-color:transparent; /></a></div>',
       transitionEffect: 'resize',
       buffer: 0
    }
  );
  this.map.addLayer(this.baseLayer);
  
  //indexed at last
  //myZoomis = this.map.getZoom();
  
  // 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);
  this.map.raiseLayer(this.clickPointMark,-1);
  //console.log("four ...");
    

  this.landmarkLayer = new OpenLayers.Layer.Vector(
    "LandMarkLayer1",
    {
      styleMap: new OpenLayers.StyleMap({
        "default" : this.landmarkStyle
      }), 
      isBaseLayer: false
  });
  this.map.addLayer(this.landmarkLayer);
  var that = this;
  var addLandMarkPopupWrap = function (evt) {
    //that.addLandMarkPopup(evt,this);
    that.addNewLandMarkPopup(evt,this);
  }
  var removeOpenLandMarkPopupWrap = function (evt) {
    that.removeOpenLandMarkPopup(evt,this);
  }
  this.landmarkLayer.events.on({"featureselected": addLandMarkPopupWrap});
  this.landmarkLayer.events.on({"featureunselected": removeOpenLandMarkPopupWrap});

  // layer index 3 - route layer
  //this.route = new OpenLayers.Layer.Vector( "One route",
  //  {style: this.routeStyle}
  //);
  var curRouteStyle = this.routeStyle;
  if (this.eMap) { curRouteStyle = this.routeEMapStyle; }
  this.route = new OpenLayers.Layer.Vector( "One route",
  { styleMap: new OpenLayers.StyleMap({
      "default" : curRouteStyle,
      "onSelect": curRouteStyle
    }), 
    isBaseLayer : false
  });
  this.map.addLayer(this.route);
  // layer index 4 
  if (typeof(missingVideoDebug) != 'undefined' &&  missingVideoDebug) {
    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.Vector("Car Marker",
  { 
    styleMap: new OpenLayers.StyleMap({
      "default" : this.carMarkLayerStyle,
      "onSelect":this.carMarkLayerStyle
    }), 
    isBaseLayer : false
  });
  //this.carMarkLayer.div.style.zIndex='4000';   // TBD
  this.locatorPointLayer= new OpenLayers.Layer.Vector(
    "srfLayer",
    { styleMap: new OpenLayers.StyleMap({
        "default" : this.srfStyle
        }), isBaseLayer: false
    }
  );
  this.map.addLayer(this.locatorPointLayer);
  var that = this;
  var popupLocationWrap = function (evt) { that.popupLocation(evt); };
  var putALogWrap = function (evt) { that.putAlog("this close event is happening"); };
  this.locatorPointLayer.events.on({"featureselected": popupLocationWrap});
  this.locatorPointLayer.events.on({"featureunselected": putALogWrap});

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

  this.textDirLayer = new OpenLayers.Layer.Vector(
    "textdir",
    {
      styleMap: new OpenLayers.StyleMap({
      "default" : this.textDirStyle
    }), isBaseLayer: false
  });
  this.map.addLayer(this.textDirLayer);
  this.map.addLayer(this.carMarkLayer);

  this.imageOnRouteLayer= new OpenLayers.Layer.Vector(
    "imageOnRouteLayer",
    {
      strategies: [this.imageOnRouteStrategy],
      styleMap: new OpenLayers.StyleMap({
      "default" : this.imageOnRouteStyle
    }), isBaseLayer: false
  });
  this.map.addLayer(this.imageOnRouteLayer);
  var popupOneImageWrap = function (evt) { that.popupOneImage(evt); };
  this.imageOnRouteLayer.events.on({"featureselected":  popupOneImageWrap});
  this.imageOnRouteLayer.events.on({"featureunselected": putALogWrap});
  this.busStopsLayer = new OpenLayers.Layer.Vector(
    "Bus Stops Layer",
    {
      styleMap: new OpenLayers.StyleMap({
      "default" : this.busStopsStyle
    }), isBaseLayer: false
  });
  this.map.addLayer(this.busStopsLayer);
  var popupOneBusStopWrap = function (evt) { that.popupOneBusStop(evt); };
  var removeOneBusStopWrap = function (evt) { that.removeBusStopPopup(evt); };
  this.busStopsLayer.events.on({"featureselected":popupOneBusStopWrap});
  this.busStopsLayer.events.on({"featureunselected":removeOneBusStopWrap});
  
  this.pfLayerMarkers= new OpenLayers.Layer.Markers("pfLayer Marker");
  this.map.addLayer(this.pfLayerMarkers);
  
  this.startEndMarkLayer= new OpenLayers.Layer.Vector(
    "startEndLayer",
    {
      styleMap: new OpenLayers.StyleMap({
      "default" : this.startEndStyle
    }), isBaseLayer: false
  });
  this.map.addLayer(this.startEndMarkLayer);
  var that = this;
  var popupLocationWrap = function (evt) { that.popupLocation(evt); };
  var putALogWrap = function (evt) { that.putAlog("this close event is happening"); };
  this.startEndMarkLayer.events.on({"featureselected": popupLocationWrap});
  this.startEndMarkLayer.events.on({"featureunselected": putALogWrap});

  /*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';
    }
  });*/
  //var that = this;
  //this.dragCar = new OpenLayers.Control.DragFeature(this.carMarkLayer, {
  //  onComplete : function (e) {
  //    //if(e) {
  //    //  mboxObj.releaseCarAfterDrag.apply(mboxObj,[parseFloat(this.feature.geometry.x),parseFloat(this.feature.geometry.y)]);
  //    //}
  //    if(e) {
  //      that.releaseCarAfterDrag.apply(that,[parseFloat(this.feature.geometry.x),parseFloat(this.feature.geometry.y)]);
  //    }
  //  },
  //  onDrag : function (e) {
  //    //if(this.feature.data.car) {
  //    //  mboxObj.carDisable = true;
  //    //  if (!mboxObj.carShadowPoint) {
  //    //    mboxObj.carShadowPoint = new OpenLayers.Feature.Vector(this.feature.geometry.clone(),{shadow:true});
  //    //    mboxObj.carMarkLayer.addFeatures([mboxObj.carShadowPoint]);
  //    //  }
  //    //}
  //    if(this.feature.data.car) {
  //      that.carDisable = true;
  //      if (!that.carShadowPoint) {
  //        that.carShadowPoint = new OpenLayers.Feature.Vector(this.feature.geometry.clone(),{shadow:true});
  //        that.carMarkLayer.addFeatures([that.carShadowPoint]);
  //      }
  //    }
  //  } 
  //});
  //this.map.addControl(this.dragCar);
  //this.dragCar.activate();
  //this.layerOrder = [
  //  this.textDirLayer,
  //  this.carMarkLayer,
  //  this.busStopsLayer,
  //  this.startEndMarkLayer,
  //  this.locatorPointLayer,
  //  this.imageOnRouteLayer,
  //  this.landmarkLayer
  //];
  //this.universalSelect = new OpenLayers.Control.SelectFeature(
  //  this.layerOrder,
  //  { clickout:true,
  //    toggle:true,
  //    hover: false,
  //    //multiple: false,
  //    //toggleKey: "ctrlKey",
  //    //multipleKey: "shiftKey",
  //    //box: true,
  //    //  opacity:1,
  //    highlightOnly: false
  //  }
  //);
  //this.map.addControl(this.universalSelect);
  //this.universalSelect.activate();
  //this.universalSelect.handlers.feature.stopDown = false;

  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 : cfg.tilecacheVideoLayer,
    statusName : "Video Layer",
    url  : cfg.tilecacheVideoUrl, 
    layerDetails : { layers: cfg.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 : cfg.tilecacheImageLayer,
    statusName : "Image Layer",
    url  : cfg.tilecacheImageUrl, 
    layerDetails : { layers: cfg.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 : cfg.tilecacheBiasLayer,
    statusName : "BIAS Layer",
    url  : cfg.tilecacheBiasUrl, 
    layerDetails : { layers: cfg.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({dragPanOptions: {enableKinetic: true}}));
  this.map.addControl( new OpenLayers.Control.MousePosition() );
  if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/android/i))) {
    this.map.addControl( new OpenLayers.Control.TouchNavigation({
      dragPanOptions: { enableKinetic: true}}
    ));
  }else{
  	this.map.addControl( new OpenLayers.Control.Navigation({dragPanOptions: {enableKinetic: true}}));
  }
  
  
  var ab=this.map.getControlsByClass("OpenLayers.Control.Attribution");
  ab[0].div.style.bottom="2px";
  try {
    if(this.gui.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(!cfg.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(this.gui.embed) this.tweakMapControls();

  var that = this;
  this.dragCar = new OpenLayers.Control.DragFeature(this.carMarkLayer, {
    onComplete : function (e) {
      if(e) {
        that.releaseCarAfterDrag.apply(that,[parseFloat(this.feature.geometry.x),parseFloat(this.feature.geometry.y)]);
      }
    },
    onDrag : function (e) {
      if(this.feature.data.car) {
        that.carDisable = true;
        if (!that.carShadowPoint) {
          that.carShadowPoint = new OpenLayers.Feature.Vector(this.feature.geometry.clone(),{shadow:true});
          that.carMarkLayer.addFeatures([that.carShadowPoint]);
        }
      }
    } 
  });
  this.map.addControl(this.dragCar);
  this.dragCar.activate();
  this.layerOrder = [
    this.textDirLayer,
    this.carMarkLayer,
    this.busStopsLayer,
    this.startEndMarkLayer,
    this.locatorPointLayer,
    this.imageOnRouteLayer,
    this.landmarkLayer
  ];
  this.universalSelect = new OpenLayers.Control.SelectFeature(
    this.layerOrder,
    { clickout:true,
      toggle:true,
      hover: false,
      //multiple: false,
      //toggleKey: "ctrlKey",
      //multipleKey: "shiftKey",
      //box: true,
      //  opacity:1,
      highlightOnly: false
    }
  );
  this.map.addControl(this.universalSelect);
  this.universalSelect.activate();
  this.universalSelect.handlers.feature.stopDown = false;

  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(this.gui.embed && this.gui.embed.place && this.gui.embed.place.lonlat) {
    var a;a={}; a.point=[]; a.point.push(this.gui.embed.place.lonlat); this.zoomToFit(a);
  } else {
    this.map.setCenter(new OpenLayers.LonLat(cfg.centerLon, cfg.centerLat), cfg.topZoom);
  }
  if(this.gui.embed && this.gui.embed.minimap) {  
    if(parseInt(this.gui.embed.height) < 240 ||  parseInt(this.gui.embed.width) < 320) {
      $('#'+this.mapDom)[0].style.cursor='pointer';
      $('#'+this.mapDom)[0].title='Click to get more detailed features';
      $('#'+this.mapDom)[0].onclick=this.popoutTheMinimap;
    }
  } else if(this.gui.embed && this.gui.embed.firstTimeRule && this.gui.embed.firstTimeRule.busId) {
  } else {
    var that = this;
    document.getElementById(this.mapDom).oncontextmenu = function (e) { that.attachRcmToMap.apply(that,[e]);return false; };
    $('#'+this.mapDom)[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.viaMarkers) {
    viaString+=this.viaMarkers[i].data.geom.lon+' '+this.viaMarkers[i].data.geom.lat;
    if(i!=(this.viaMarkers.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 viaMarkerIndex=0;
//  //      var viaBallLoc = new OpenLayers.LonLat(markerObj.lonlat.lon,markerObj.lonlat.lat);
//  //      if(!mboxObj.viaMarkers) {
//  //        mboxObj.viaMarkers=[];
//  //      } 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.addViaSet = function (viaSet) {
  if(!this.viaMarkers) this.viaMarkers=[];
  var features = [];
  for (var i in viaSet) {
    this.placeViaBallFlag=true;
    var icon = {mapUrl:imagePathsObj.viaBallMarkers+"v"+(this.viaMarkers.length+1)+".png"+'?r='+cfg._rStr,w:32,h:32};
    var data = {type:'via',geom:viaSet[i],icon:icon};
    var v = new OpenLayers.Geometry.Point(viaSet[i].lon,viaSet[i].lat);
    var oneFeature = new OpenLayers.Feature.Vector(v,data);
    features.push(oneFeature);
    this.viaMarkers.push(oneFeature);
  }
  this.startEndMarkLayer.addFeatures(features);
}

mbox.prototype.addVia = function (via) {
  var features = [];
  if(!this.viaMarkers) this.viaMarkers=[];
  via.icon = {mapUrl:imagePathsObj.viaBallMarkers+"v"+(parseInt(via.viaIdx)+1)+".png"+'?r='+cfg._rStr,w:32,h:32};
  var v = new OpenLayers.Geometry.Point(via.lonlat.lon,via.lonlat.lat);
  var oneFeature = new OpenLayers.Feature.Vector(v,via);
  this.viaMarkers.push(oneFeature);
  features.push(oneFeature);
  this.startEndMarkLayer.addFeatures(features);
}

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

//mbox.prototype.addViaMarkerToLayer = function(viaMarkerIndex) {
//  //If marker is already added, remove and reattach, to get the z-Index feeler for the user ! 
//  if(mboxObj.viaMarkers[viaMarkerIndex]) {
//    mboxObj.startEndMarkLayer.removeMarker(mboxObj.viaMarkers[viaMarkerIndex]);  
//  }
//  mboxObj.startEndMarkLayer.addMarker(mboxObj.viaMarkers[viaMarkerIndex]);
//  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(this.gui.embed.height)<=250 || parseInt(this.gui.embed.width)   <=250) {
     var ab=this.map.getControlsByClass('OpenLayers.Control.PanZoomBar');
     
    if(parseInt(this.gui.embed.height)<=60 || parseInt(this.gui.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(this.gui.embed.height)<200 || parseInt(this.gui.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 ) {
    this.gui.toggleButtons({"clearroutetab":true}); 
  } else { 
    this.gui.toggleButtons({"clearroutetab":false}); 
  }
}

mbox.prototype.loadImageWfsLayer = function () {
  this.gui.displayMessage("Loading Images .. please be patient");
  if(this.imagetab.active==true) {
    var zoomLevel=this.map.getZoom();
    zoomLevel+=10;
  }
  bounds=this.imagetab.tabLayer.layer.getTilesBounds();
  var reqData= {
    z:zoomLevel,
    b:bounds.left+" "+bounds.bottom+","+bounds.right+" "+bounds.top,
    maptile:"requestgml"
  }
  var that = this;
  $.getJSON(cfg.imgTileUrl,reqData,function (response) {  
    that.imgTile=response;  // TBD not sure about the context
    that.imgTile.boxes=new Array();
    for(i=0;i<that.imgTile.points.length;i++) {
      var ll=that.imgTile.points[i].split(",");
      ll[0]=parseFloat(ll[0]);
      ll[1]=parseFloat(ll[1]);
      var factor=8*that.map.getResolutionForZoom(that.map.getZoom());
      var minlon=ll[0]-factor;  
      var minlat=ll[1]-factor;
      var maxlon=ll[0]+factor;
      var maxlat=ll[1]+factor;
      that.imgTile.boxes[i]=new OpenLayers.Bounds(maxlon,maxlat,minlon,minlat);
      // TBD why extend ?
      that.imgTile.boxes[i].extend(new OpenLayers.LonLat(minlon,minlat));
      that.imgTile.boxes[i].extend(new OpenLayers.LonLat(maxlon,maxlat));
    }
    this.gui.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) {
  //this.gui.displayMessage(''); Has been in the system since incpetion of mbox.js 
  this.killRcmPopup();
  this.removeOpenPopup();
  //var imageSource=cloneImageUrl+imageName;
  var imageSource=cfg.cloneImageUrl+imageName;
  imagePOIName=(typeof(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() {
  var that = this;
  $.getJSON(cfg.imgTileUrl,{action:"requestBias"},function (response) {
    that.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]),that.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 () {that.popupBiasWfsLayer.apply(that,[]);})
      m.events.register("mouseover",m,that.popupBiasWfsLayer);
      m.events.register("mouseout",m,function () { that.map.removePopup(that.biasPopup)});
      that.biasWfsLayer.addMarker(m);
    }
    that.map.addLayer(that.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 = [];
  this.srfBound = null;
  //if(this.gui.embed) {
  //  this.removeStartEndPoint(this.gui.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;
  if (this.srfBound == null) { this.srfBound = new OpenLayers.Bounds(); }
  this.putAllLocatorPoints(srf,this.srfBound);
}

mbox.prototype.writeSrfToTableFinish = function(srf) {
  this.changeMapViewWithGravity(this.srfBound,20);
  //try { 
  //  if(this.gui.embed && this.gui.embed.locateStores && srf.results[0].parentType=='locateStores') this.callPopupLocation(0);
  //} catch(e) {}
  //this.autoPopup('start');
}

mbox.prototype.refreshLocatorPoint = function(entity) {
  if (this.locatorPointLayer) { this.locatorPointLayer.redraw(); }
}

//mbox.prototype.removeStartEndPoint = function(which) {
//  if (!this.startEndMarkLayer) { return; }
//  for (var i in this.startEndMarkLayer.features) {
//    if (!this.startEndMarkLayer.features[i].data.startOrEnd ||
//         this.startEndMarkLayer.features[i].data.startOrEnd != which) { continue; }
//    //delete this.startEndMarkLayer.features[i].data.startOrEnd;
//    if (this.startEndMarkLayer.features[i].data.shownLayer &&
//        this.startEndMarkLayer.features[i].data.shownLayer == 'startEndMarkLayer') {
//      delete this.startEndMarkLayer.features[i].data.shownLayer;
//    }
//    this.startEndMarkLayer.removeFeatures([this.startEndMarkLayer.features[i]]);
//  }
//}

//mbox.prototype.removeStartEndPointEntity = function(entity) {
//  if (entity.shownLayer == 'locatorPointLayer') {
//  }
//  if (entity.shownLayer == 'startEndMarkLayer') {
//    this.removeStartEndPoint(entity.startOrEnd);
//  }
//}

mbox.prototype.putImageData = function(imageData) {
  this.oneImageMarker=new Array();
  var features=[];
  for(var i=0;i<imageData.length;i++) {
    if(imageData[i].poiName) {
      var splitName=imageData[i].imgName.split("_");
      imageData[i].imageCaption=(imageData[i].poiName==undefined)?(" "):imageData[i].poiName;
       var v = new OpenLayers.Geometry.fromWKT("POINT("+imageData[i].lonlat.lon+" "+imageData[i].lonlat.lat+")");
      var pFeature = new OpenLayers.Feature.Vector(v,imageData[i]);
      features.push(pFeature);
      this.oneImageMarker[i]=pFeature;
    }
  }
  this.imageOnRouteLayer.addFeatures(features);
}   

//mbox.prototype.putStartEndPoint = function(which,entity) {
//   var features=[];
//   var v = new OpenLayers.Geometry.fromWKT(entity.geom);
//   //entity.startOrEnd=which ;
//   var pFeature = new OpenLayers.Feature.Vector(v,entity);
//   features.push(pFeature);
//   this.startEndMarkLayer.addFeatures(features);
//   entity.shownLayer = 'startEndMarkLayer';
//}   

mbox.prototype.putSePoint = function(entity) {
  if (entity.seFeature) { return; }
  var features=[];
  var v = new OpenLayers.Geometry.fromWKT(entity.geom);
  var pFeature = new OpenLayers.Feature.Vector(v,entity);
  this.startEndMarkLayer.addFeatures(features);
  features.push(pFeature);
  this.startEndMarkLayer.addFeatures(features);

  entity.seFeature = 'ping';
  if (this.seFeatureStore.ping) { entity.seFeature = 'pong'; }
  this.seFeatureStore[entity.seFeature] = pFeature;

  entity.shownLayer = 'startEndMarkLayer';
  if (this.locatorPointLayer) { this.locatorPointLayer.redraw(); }
}   

mbox.prototype.removeSePoint = function(entity) {
  if (!entity.seFeature) { return; }
  this.startEndMarkLayer.removeFeatures([this.seFeatureStore[entity.seFeature]]);
  delete this.seFeatureStore[entity.seFeature];
  delete entity.seFeature;
  if (this.locatorPointLayer) { this.locatorPointLayer.redraw(); }
}   

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,evt) {
  var evt = evt || {};
  var feature = this.locatorPoint[i];
  evt.feature = feature;
  if('undefined' != typeof(accountDetails) && 'locatestores' == accountDetails.q){
    if('undefined' == typeof(feature) || 'undefined' != typeof(feature.attributes.count) ){
      evt.feature = this.getFeatureFromCluster(i);
    } else {
       evt.feature = feature;
    }
  }
  this.popupLocation(evt);
}

mbox.prototype.autoPopup = function(tip) {
  var evt = {};
  for (var i in this.locatorPoint) {
    if (!this.locatorPoint[i].data.startOrEnd ||
       this.locatorPoint[i].data.startOrEnd != tip) { continue; }
    evt.feature = this.locatorPoint[i];
    break;
  }
  if (evt.feature) { this.popupLocation(evt);  return; }
}

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.popupLocation = function(evt,shortPop) {
  if('undefined' != typeof(accountDetails) && accountDetails.q == 'locatestores' && 'Category Layer' == evt.feature.layer.name ){
    if(this.catMngr){
      this.catMngr.categoryPopup(evt);
     // evt.register("featureselected",evt.feature,this.catMngr.onFeatureSelected);
      this.map.setCenter(new OpenLayers.LonLat(evt.feature.geometry.x,evt.feature.geometry.y), this.map.getZoom());
      return;
    }
  } else {this.removeOpenPopup();}
  var poi = new _poi(evt.feature.data,this.gui);
  //var mapHtml = getEntityHtmlNew('map',evt.feature.data,shortPop);
  var mapHtml = poi.getEntityHtml('map',shortPop);
  var size=(mapHtml.popupWidth)?(new OpenLayers.Size(mapHtml.popupWidth,mapHtml.popupHeight)):(new OpenLayers.Size(320,240));   
  this.openPopup=new OpenLayers.Popup.FramedCloud("locpopupdiv",new OpenLayers.LonLat(evt.feature.geometry.x,evt.feature.geometry.y),size,mapHtml.contentHTML,null,false,this.removeOpenPopup);
  this.openPopup.setBackgroundColor("white");
  this.openPopup.index = evt.feature.data.index;
  this.openPopup.entity = evt.feature.data;
  this.openPopup.autoSize=false;
  this.map.addPopup(this.openPopup);
  for (var i in mapHtml.funcList) { $('#'+i).click(mapHtml.funcList[i]); }
  // now that popup is drawn, regularize the width
  $('#finalPopContent').height($('#finalPopContent').outerHeight());
  var deltaW = $('#locpopupdiv').width()-$('#locpopupdiv_contentDiv').width();
  var deltaH = $('#locpopupdiv').height()-$('#locpopupdiv_contentDiv').height();
  size.h =  parseInt($('#finalPopContent').outerHeight())+10;
  if (deltaH < 55) {size.h += 5;} else { size.h -= 5; }
  if (deltaW < 20) {size.w += 5;} else { size.w -= 8; }
  this.openPopup.setSize(size);
  //document.getElementById('locpopupdiv').setClassName='locpop';
  //document.getElementById('locpopupdiv_contentDiv').setClassName='locpop';
  $('#locpopupdiv_contentDiv').css('left','5px');
  $('#locpopupdiv_contentDiv').css('overflow','hidden');
  this.openPopup.contentDiv.style.overflow='hidden';
  this.openPopup.disableFirefoxOverflowHack = false;
  this.openPopup.contentDisplayClass = '';
  //var closeHtml = getEntityHtmlClose('map',evt.feature.data,shortPop);
  var t = poi.getEntityHtmlClose('map',shortPop);
  //$('#locpopupdiv_contentDiv').append(closeHtml);
  $('#locpopupdiv_contentDiv').append(t.html);
  for (var i in t.funcList) { $('#'+i).click(t.funcList[i]); }
  OpenLayers.Event.stop(evt);
}

mbox.prototype.getRouteBound = function () {
  this.routeBound = new OpenLayers.Bounds();
  for(var i=0;i<this.syncMapPoints.length;i++) {
    var c = this.carPathArray[this.syncMapPoints[i]];
    this.routeBound.extend(OpenLayers.LonLat.fromString(c[0].replace(/ /,',')));
    this.routeBound.extend(OpenLayers.LonLat.fromString(c[c.length-1].replace(/ /,',')));
  }
}

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(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('undefined' != typeof(accountDetails) && accountDetails.q == 'locatestores'){
    if(this.catMngr){this.catMngr.clearCatLayer();}
  }
  for (var i in this.locatorPointLayer.features) {
    if (this.locatorPointLayer.features[i].data.shownLayer &&
        this.locatorPointLayer.features[i].data.shownLayer == 'locatorPointLayer') {
      delete this.locatorPointLayer.features[i].data.shownLayer;
    }
  }
  this.locatorPointLayer.removeFeatures(this.locatorPointLayer.features);
  this.locatorPoint=[];
}

mbox.prototype.removeImageMarkers = function() {
  if (this.imageOnRouteLayer) {
    this.imageOnRouteLayer.removeFeatures(this.imageOnRouteLayer.features);
    if (this.imageOnRouteLayer.strategies &&
        this.imageOnRouteLayer.strategies.length) {
      this.imageOnRouteLayer.strategies[0].clearCache();
    }
  }
}

// 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();
  if (this.catMngr) { this.catMngr.clearCatLayer(); }  // TBD may be we should name clear
  this.clearViaMarkers();
  this.clearRouteAndSrf();
}

// remember - there is viaBalls and viaMarkers as separate entity 
mbox.prototype.clearViaMarkers = function () {
  if (this.viaMarkers && this.startEndMarkLayer) {
    this.startEndMarkLayer.removeFeatures(this.viaMarkers);
  }
  this.viaMarkers=[]; 
}

mbox.prototype.clearRouteAndSrf = function () {
  this.killRcmPopup();
  this.carPathArray=[];     
  this.syncMapPoints=[];    
  this.removeAllLocatorPoints();
  //if(this.gui.embed) { this.removeStartEndPoint(this.gui.embed.other); }
  //else {
  //  this.removeStartEndPoint('start');
  //  this.removeStartEndPoint('end');
  //}
  this.removeOpenPopup();
  this.removeImageMarkers();
  this.route.removeFeatures(this.route.features);
  if (typeof(missingVideoDebug) != 'undefined' &&  missingVideoDebug) {
    this.routeNoVid.removeFeatures(this.routeNoVid.features);
    this.routeNoVb.removeFeatures(this.routeNoVb.features);
    this.routeNoDp.removeFeatures(this.routeNoDp.features);
  }
  if(this.textDirLayer) { this.textDirLayer.removeFeatures(this.textDirLayer.features); }
  if(this.busStopsLayer) { this.busStopsLayer.removeFeatures(this.busStopsLayer.features); }
  this.carDisable = true;
  if(this.carPoint) {
    this.carMarkLayer.removeFeatures(this.carMarkLayer.features);
    delete this.carPoint;
  }
  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.clearViaMarkers();
    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) {
  if (!this.rcmItems.length) return false;
  var eventObj=this.returnMouseLonLats(e);
  if(!eventObj) return false;
  this.rcmLonlat=this.map.getLonLatFromPixel(eventObj.xy); 
  this.pointLonlat="POINT("+this.rcmLonlat.lon+" "+this.rcmLonlat.lat+")"; 
  this.pushFeatures('clickPointMark',this.parser.read(this.pointLonlat));
  eventObj.xy.x+=10;
  eventObj.xy.y-=10;
  var h = 108; var w = 120; var p = 10;
  var popuplonlat=this.map.getLonLatFromPixel(eventObj.xy);

  var mapOptionsHTML="<div style='padding:"+p+"px;background-color:transparent;'><table id=mapOptionsTable height="+(h-2*p)+"px width="+(w-2*p)+"px style='border :none; text-align:center; overflow:hidden;background-color:"+vidteq.bgColor+";' cellborder='1' >";

  var optionsDecider = function (id,onclickFunc,text,disabled) {
    var ht=["<tr id='"+id+"'" ];
    if (onclickFunc.trim() != '') { ht.push("onclick='javascript:"+onclickFunc+";'"); }
    ht.push("class=rcmrow onmouseover=this.className='rcmhighlight' onmouseout=this.className='rcmrow'>");
    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;
  };

  for (var i in this.rcmItems) { 
    var one = this.rcmItems[i];
    if (one.cond()) {
      mapOptionsHTML+=optionsDecider(one.id,'',one.text,one.disabled);
    }
  }

  mapOptionsHTML+="</table></div>";

  this.rcmPopup=new OpenLayers.Popup("mapoptionsdiv",new OpenLayers.LonLat(popuplonlat.lon,popuplonlat.lat),new OpenLayers.Size(w,h),mapOptionsHTML,false);
  this.rcmPopup.setContentHTML(mapOptionsHTML);
  this.rcmPopup.panMapIfOutOfView=true;
  this.map.addPopup(this.rcmPopup);
  // 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=h+"px";
  document.getElementById('mapoptionsdiv').style.width=w+"px";  // final trim 
  $('#mapoptionsdiv').css('background-color','transparent');

  var boxImage = { url:imagePathsObj.refBox3, cornerW:10, cornerH:10, boxW:510, boxH:378, offsetW:0, offsetH:0 };
  utils.boxify(boxImage,'mapoptionsdiv_contentDiv',{lt:1,rt:1,lb:1,rb:1},1);
  for (var i in this.rcmItems) {
    var one = this.rcmItems[i];
    if ( $('#'+one.id).length ) { $('#'+one.id).click(one.onClickFunc); }
  }
  if(this.gui.embed && !this.gui.embed.locateStores) this.disableRcmOptions(this.gui.embed.fix);      
  var that = this;
  this.killOptionPopupVar=setTimeout(function () { that.killRcmPopup(); },30000);
  return false;
}

//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 h = 108; var w = 120; var p = 10;
//  var popuplonlat=mboxObj.map.getLonLatFromPixel(eventObj.xy);
//  var mapOptionsHTML="<div style='padding:"+p+"px;background-color:transparent;'><table id=mapOptionsTable height="+(h-2*p)+"px width="+(w-2*p)+"px style='border :none; text-align:center; overflow:hidden;background-color:white;' cellborder='1' >";
//
//  var optionsDecider = function (id,onclickFunc,text,disabled) {
//    var ht=["<tr id='"+id+"'" ];
//    if (onclickFunc.trim() != '') { 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;
//  };
//  var events = {};
//  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) {
//    events['locateStores'] = function () { ioAreaObj.setupAndCallNBS({point:mboxObj.rcmLonlat,tip:'start'}); };
//    mapOptionsHTML+=optionsDecider("locateStores",'',"Locate Nearest Store",false);
//    if(mboxObj.routeActive) {
//      events['viaoption'] = function () { ioAreaObj.placeViaAndRoute(mboxObj.rcmLonlat); };
//      mapOptionsHTML+=optionsDecider("viaoption",'',"Via",false);
//    }
//  } else {
//    if(mboxObj.routeActive)  {
//      events['viaoption'] = function () { ioAreaObj.placeViaAndRoute(mboxObj.rcmLonlat); };
//      mapOptionsHTML+=optionsDecider("viaoption",'',"Via",false);
//    }
//    mapOptionsHTML+=optionsDecider("startoption",'',"Directions From",false);
//    events['startoption'] = function () { 
//      mboxObj.addRcmStartOrEndMarker.apply(mboxObj,['start',mboxObj.rcmLonlat]); 
//      if (ioAreaObj.embed) { ioAreaObj.goVid(); }
//    };
//    mapOptionsHTML+=optionsDecider("endoption",'',"Directions To",false);    
//    events['endoption'] = function () { 
//      mboxObj.addRcmStartOrEndMarker.apply(mboxObj,['end',mboxObj.rcmLonlat]); 
//      if (ioAreaObj.embed) { ioAreaObj.goVid(); }
//    };
//    // events attached later
//  }
//  if(!mboxObj.routeActive) mapOptionsHTML+=optionsDecider("govidoption",'',"GO VID",false); 
//  events['govidoption'] = function () { ioAreaObj.invokeTheMode.apply(ioAreaObj,[]); return false; };
//  mapOptionsHTML+="</table></div>";
//  mboxObj.rcmPopup=new OpenLayers.Popup("mapoptionsdiv",new OpenLayers.LonLat(popuplonlat.lon,popuplonlat.lat),new OpenLayers.Size(w,h),mapOptionsHTML,false);
//  mboxObj.rcmPopup.setContentHTML(mapOptionsHTML);
//  mboxObj.rcmPopup.panMapIfOutOfView=true;
//  mboxObj.map.addPopup(mboxObj.rcmPopup);
//  // 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=h+"px";
//  document.getElementById('mapoptionsdiv').style.width=w+"px";  // final trim 
//  $('#mapoptionsdiv').css('background-color','transparent');
//
//  var boxImage = { url:imagePathsObj.refBox3, cornerW:10, cornerH:10, boxW:510, boxH:378, offsetW:0, offsetH:0 };
//  boxify(boxImage,'mapoptionsdiv_contentDiv',{lt:1,rt:1,lb:1,rb:1},1);
//  // now attach all the events
//  for (var i in events) { $('#'+i).click(events[i]); }
//  if(ioAreaObj.embed && !ioAreaObj.embed.locateStores) mboxObj.disableRcmOptions(ioAreaObj.embed.fix);      
//  //if($('#govidoption').length) {  
//  //  $('#govidoption').click(function () { ioAreaObj.invokeTheMode.apply(ioAreaObj,[]); return false; });
//  //}
//  //mboxObj.killOptionPopupVar=setTimeout('mboxObj.killRcmPopup()',30000);
//  return false;
//}

mbox.prototype.disableRcmOptions = function (str) {
  var whichOne=(str=='start')?($('#startoption')):($('#endoption'));
  whichOne[0].onclick=null;
  whichOne.unbind('click');
  var passString=(str=='start')?('From'):('To');
  try {    
    whichOne.html("<td><a class=simple style='color:#CDC8B1;'>Directions "+passString+"</a></td>");
    whichOne.css('cursor','default');
  } catch(e) {} 
  whichOne[0].onmouseover=whichOne[0].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));
    var wkt = this.parser.read(wktParent.wkt);
    if (wktParent.eMapColor) { wkt.eMapColor = wktParent.eMapColor; }
    features.push(wkt);
  } else {
    for (var i in wktParent.wkt) {
      var wkt = this.parser.read(wktParent.wkt[i]);
      if (wktParent.eMapColor) { wkt.eMapColor = wktParent.eMapColor; }
      if (wkt) features.push(wkt);
    }
  }  
  if ( features.length > 0 ) layer.addFeatures(features);
}

mbox.prototype.popupOneImage = function(evt) {
  // mboxObj.imageTilePopup(this.lonlat,this.imgName,this.imageCaption);
  if (typeof(evt.feature.attributes.count) == 'undefined') {
    this.imageTilePopup(evt.feature.data.lonlat,evt.feature.data.imgName,evt.feature.data.imageCaption);
  } else {
    this.imageTilePopup(evt.feature.cluster[0].data.lonlat,evt.feature.cluster[0].data.imgName,evt.feature.cluster[0].data.imageCaption);
   
  }
  // TBD arrow overlay 
  OpenLayers.Event.stop(evt);
}

// this function is already context neutral so ok
mbox.prototype.callPopupOneImage = function(i,evt) {
  var data=this.oneImageMarker[i].data;
  this.imageTilePopup(data.lonlat,data.imgName,data.imageCaption);
}

mbox.prototype.popupOneBusStop = function (evt) {
  this.imageTilePopup(evt.feature.data.lonlat,evt.feature.data.imagePath,evt.feature.data.busStopName);
  // TBD check if there is clustering
  return 0;
} 

mbox.prototype.callBusStopPopup = function(i,evt) {
  evt = evt || {};
  evt.feature = evt.feature || {};
  evt.feature.data = this.busStopsMarkers[i];
  this.popupOneBusStop(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 carCord = onePoint.split(" ");
    var l = new OpenLayers.LonLat(carCord[0],carCord[1]);
    this.carPoint.move(l);
    return;
  }
  var carCord = onePoint.split(" ");
  var v = new OpenLayers.Geometry.fromWKT("POINT("+carCord[0]+" "+carCord[1]+")");
  this.carPoint = new OpenLayers.Feature.Vector(v,{car:true});  // TBD atleast title is needed
  this.carMarkLayer.addFeatures([this.carPoint]);
}

mbox.prototype.putTextNumbers = function(response) {
  var features = [];
  for(var i=1;i<(this.syncMapPoints.length-1);i++) {
    var po=this.carPathArray[this.syncMapPoints[i]][0].split(" ");
    features.push(
      new OpenLayers.Feature.Vector( 
        new OpenLayers.Geometry.Point(po[0],po[1]),
        { icon : imagePathsObj.textdirs.base+(i+1)+".png"+'?r='+cfg._rStr,
          title : response.vid[i].direction }
      )
    );
  }
  this.textDirLayer.addFeatures(features);
}

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

mbox.prototype.putBusStops = function (busStops) {
  this.removeBusStopPopup();
  this.busStopsMarkers=new Array();  
  var features = [];
  for(var i in busStops) {
    var b = busStops[i];
    b.title = "stop no "+b.sl_no+"  "+b.name;
    features.push(
      new OpenLayers.Feature.Vector( 
        new OpenLayers.Geometry.fromWKT(b.geom),b
      )
    );
  }
  this.busStopsLayer.addFeatures(features);
}

mbox.prototype.moveCarTo = function(index) {
  var stringSplit=index.split(":");
  var parentIndex=stringSplit[0];
  var childIndex=stringSplit[1];
  var onePoint;
  if (typeof(this.carPathArray[parentIndex]) == 'undefined') { return; }
  if(this.carPathArray[parentIndex].length == 1) {
    onePoint = this.carPathArray[parentIndex][0];
  } else {
    onePoint = this.carPathArray[parentIndex][childIndex];
  }
  if (typeof(onePoint) == 'undefined') { return; }
  if (this.carDisable) {
    if(!this.carShadowPoint) { return; }
    var carCord = onePoint.split(" ");
    var carLocPx = this.map.getLayerPxFromViewPortPx(this.map.getPixelFromLonLat(new OpenLayers.LonLat(carCord[0],carCord[1])));
    this.carShadowPoint.moveTo(carLocPx);
    return;
  } 
  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);
  if (typeof(missingVideoDebug) != 'undefined' &&  missingVideoDebug) {
    this.writeWkt(this.routeNoVid,response.novid);
    this.writeWkt(this.routeNoVb,response.novb);
    this.writeWkt(this.routeNoDp,response.nodp);
  }
  if(!this.gui.embed  ||
    (this.gui.embed && this.gui.embed.fix=='end')) {
    routeEndsObj.add('start',response.startEntity);
  } 
  if(!this.gui.embed  ||
    (this.gui.embed && this.gui.embed.fix=='start')) {
    routeEndsObj.add('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';

  //  if (typeof(accountDetails) != 'undefined' && accountDetails.account=="Arthabfs"){
  //    ioAreaObj.link='http://www.arthabfs.com/map1.html?firstTimeRule='+JSON.stringify(firstTimeRule);     
  //  } else {
  //    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.carDisable = false;
  if(this.gui.embed && this.gui.embed.firstTimeRule && this.gui.embed.firstTimeRule.busId) {
    this.putBusStops(response.busStops);
  } else {
    this.putTextNumbers(response);  // implicit dependency to carPath
    this.putImageData(response.imgData);  
  }
  //this.fitCurrentRoute(); // implicit dependency to carPath
  //if(typeof(mboxObj.viaMarkers)!='undefined') {
  //  for(var i=0;i<mboxObj.viaMarkers.length;i++) {
  //    mboxObj.addViaMarkerToLayer(i);
  //  }
  //}
  // I really dont understand  why this was needed in the first place
  // TBD before removing the code re-confirm
  this.getRouteBound();
  this.changeMapViewWithGravity(this.routeBound);
}

mbox.prototype.changeMapViewWithGravity = function(bound,shrink) {
  if(this.gui.embed && this.gui.embed.place && this.gui.embed.place.lonlat) {
    var center = new OpenLayers.LonLat(this.gui.embed.place.lonlat.lon,this.gui.embed.place.lonlat.lat);
    bound.extend(center);
    this.changeMapView(bound,center,20);
  } else {
    this.changeMapView(bound,undefined,20);
  }
}

mbox.prototype.changeMapView = function(bound,gravity,shrink) {
  var realBound = bound;
  if (typeof(shrink) != 'undefined') {
    realBound = new OpenLayers.Bounds(
      bound.left - bound.getWidth() * shrink/200,
      bound.bottom - bound.getHeight() * shrink/200,
      bound.right + bound.getWidth() * shrink/200,
      bound.top + bound.getHeight() * shrink/200
    );
  }
  var targetZoom = this.map.getZoomForExtent(realBound);
  if (targetZoom != this.map.getZoom()) {
    if (typeof(gravity) != 'undefined') {
      var curCenter = this.map.getCenter();
      var curRes = this.map.getResolution();
      var newRes = this.map.getResolutionForZoom(targetZoom);
      this.map.setCenter(new OpenLayers.LonLat(
        gravity.lon - (gravity.lon - curCenter.lon) * newRes/curRes,
        gravity.lat - (gravity.lat - curCenter.lat) * newRes/curRes),targetZoom);
    } else {
      this.map.zoomTo(targetZoom);
    }
  }
  this.map.panTo(realBound.getCenterLonLat());
}

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 ((lonA-lonB)*(lonA-lonB) + (latA-latB)*(latA-latB));
}

mbox.prototype.releaseCarAfterDrag = function(dragLon,dragLat) {
  var lPI; var lD;
  for(var i in this.carPathArray) {
    var ll=this.carPathArray[i][0].split(" ");
    var dist = this.computeDistance(parseFloat(dragLon),parseFloat(dragLat),parseFloat(ll[0]),parseFloat(ll[1]));
    if (i == 0 || dist < lD) { lPI = i; lD = dist; }
  }
  var lCI = 0;
  for(var i=Math.max(0,lPI-1);i<=Math.min(lPI+1,this.carPathArray.length-1);i++) {
    var onePath = this.carPathArray[i];
    for(var j in onePath) {
      var ll=onePath[j].split(" ");
      var dist = this.computeDistance(parseFloat(dragLon),parseFloat(dragLat),parseFloat(ll[0]),parseFloat(ll[1]));
      if (dist < lD) { lPI = i; lCI = j; lD = dist; }
    }
  }
  this.removeAndAddCarPoint(this.carPathArray[lPI][lCI]);
  try { fvtObj.getVideoObj(fvtObj.videoSwf).playVideo(lPI); } catch (e) { }; // TBD make player to lCI
  // now wait for 2 sec before releasing car
  var that = this;
  setTimeout(function () { 
    that.carDisable = false; 
    if (that.carShadowPoint) {
      that.carMarkLayer.removeFeatures([that.carShadowPoint]);
      delete that.carShadowPoint;
    }
  },2000);
  //setTimeout(function () { 
  //  mboxObj.carDisable = false; 
  //  if (mboxObj.carShadowPoint) {
  //    mboxObj.carMarkLayer.removeFeatures([mboxObj.carShadowPoint]);
  //    delete mboxObj.carShadowPoint;
  //  }
  //},2000);
}

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.removeMapTitle =function () {
    $('#'+this.mapDom)[0].title=""; 
}

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

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

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

mbox.prototype.enlargeThumbNail =function (width,height) {
  var divsize= $("#popimage").css("width");
  var myIEWidth= 290;
  var myFFWidth=300;
  var myIEHeight=190;
  var myFFHeight=195;
  var biggerWidth=$("#myid").css("width");
  var biggerHeight=$("#myid").css("height");
  
  if(typeof(biggerWidth) && biggerWidth){
    var  widthInteger= biggerWidth.replace(/px$/,'');
    myIEWidth= widthInteger-30;
    myFFWidth=widthInteger-20;
  }
  if (typeof(biggerHeight) && biggerHeight){
    var  heightInteger= biggerHeight.replace(/px$/,'');
    myIEHeight=heightInteger-60;
    myFFHeight=heightInteger-50;
  }
  $("#nameCat").hide('slide',200);
  $("#name").hide('slide',200);
  $("#yo_video").hide('slide',200);
  if (typeof(width) && width){ }
  if (self.navigator.userAgent.match(/MSIE/)){
    $("#yo").animate({width:myIEWidth+"px",height:myIEHeight+"px",left:"0px",right:"10px"},200);
    $("#popimage").animate({width:"290px",height:myIEHeight+"px",left:"2px",right:"10px"},200);
  } else {
    $("#yo").animate({width:myFFWidth+"px",height:myFFHeight+"px",left:"0px",right:"10px"},200);
    $("#popimage").animate({width:myFFWidth+"px",height:myFFHeight+"px",left:"2px",right:"10px"},200);
  }
}

mbox.prototype.enlargeThumbNailVideo =function () {
  var divsize= $("#yo_video_object").css("width");
  $("#nameCat").hide('slide',200);
  $("#name").hide('slide',200);
  $("#yo").hide('slide',200);
  if (self.navigator.userAgent.match(/MSIE/)){
    $("#yo_video").animate({width:"290px",height:"190px",top:"5px",right:"5px"},200);
    $("#yo_video_object").animate({width:"290px",height:"180px",right:"2px",top:"5px"},200);
    $("#yo_collapse").show('slide',200);
    $("#yo_expand").hide('slide',200);
  } else {
    $("#yo_video").animate({width:"300px",height:"195px",top:"5px",right:"5px"},200);
    $("#yo_video_object").animate({width:"300px",height:"185px",left:"2px",right:"10px"},200);
    $("#yo_collapse").show('slide',200);
    $("#yo_expand").hide('slide',200);
  }
}

mbox.prototype.getBackThumbNail =function (width,height) {
  var divsize= $("#popimage").css("width");
  var integerDivSize= divsize.replace(/px$/, '');
  if (integerDivSize > 80){
   $("#nameCat").show('slide',200);
   $("#name").show('slide',300);
   $("#yo_video").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(width, height);}  
}

mbox.prototype.getBackThumbNailVideo =function () {
  var divsize= $("#yo_video_object").css("width");
  if(divsize=="300px" || divsize =="290px"){
   $("#nameCat").show('slide',200);
   $("#name").show('slide',200);
   $("#yo").show('slide',200);
   $("#yo_video").animate({width:"80px",height:"90px",right:"5px",top:"90px"},200);
   $("#yo_video_object").animate({width:"80px",height:"80px",right:"0px",top:"2px"},200);
   $("#yo_collapse").hide('slide',200);
   $("#yo_expand").show('slide',200);
  } else {mboxObj.enlargeThumbNailVideo();}  
}

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);
    this.map.setCenter(new OpenLayers.LonLat(cfg.centerLon, cfg.centerLat), cfg.topZoom);
  }
  // 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() {
  if(this.routeActive) {
    this.fitCurrentRoute();
  } else {
    //this.map.setCenter(new OpenLayers.LonLat(globalLon, globalLat), globalZoom);
    this.map.setCenter(new OpenLayers.LonLat(cfg.centerLon, cfg.centerLat), cfg.topZoom);
  } 
}

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

mbox.prototype.popoutCenterPlace = function (evt,shortPop) { 
  if (!this.startEndMarkLayer) { return; }
  var f = this.startEndMarkLayer.features;
  for (var i in f) {
    if (!f[i].data.type || f[i].data.type != 'center') { continue; }
    evt = evt || {};
    evt.feature = f[i];
    this.popupLocation(evt,shortPop);
  }
}

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

mbox.prototype.createLandMarkLayer = function (response) {
  if (typeof(response)!='object') response=JSON.parse(response);
  var features= [];
  var featuresPolygon= [];
  for (var i=0 ; i<response.srf[0].results.length; i++){
    var v = new OpenLayers.Geometry.fromWKT(response.srf[0].results[i].geom);
    var pointArray =[];
    pointArray.push(v);
    var pFeature = new OpenLayers.Feature.Vector(v,response.srf[0].results[i]);
    features.push(pFeature);
  }
  for (var i=0 ; i<response.srf[1].results.length; ++i){
    if (typeof(response.srf[1].results[i].geom)!='undefined'){
      var w = new OpenLayers.Geometry.fromWKT(response.srf[1].results[i].geom);
      var x=new OpenLayers.Feature.Vector(w,response.srf[1].results[i]);
      featuresPolygon.push(x);
    }
  }
  this.landmarkLayer.addFeatures(featuresPolygon);
  this.landmarkLayer.addFeatures(features);
  this.gui.changeBackOpacity(1);
}    

mbox.prototype.checkIfLayerExists =function (layerName) {
  var l= this.map.getLayersByName(layerName);
  return l.length;  
}

mbox.prototype.putAllLocatorPoints =function (srf,bound) {
  var features= [];
  if('undefined' != typeof(accountDetails) && accountDetails.q == 'locatestores' && 'locateStores' == srf.srfType){
     $('#collapse').html('<<');
     if('undefined' == typeof(this.catMngr)){
      this.catMngr = new _catMngr(this,'slave',40);
    }
    var params = {
     'categoryIcon':cfg.imageCatgoryLogosLoc+accountDetails.places.categoryDetails.categoryIconName,
     'categoryClusterIcon':cfg.imageCatgoryLogosLoc+accountDetails.places.categoryDetails.categoryClusterIconName,
     'shadowIcon': cfg.imageCatgoryLogosLoc+accountDetails.places.categoryDetails.shadowIconName,
     'shadowClusterIcon': cfg.imageCatgoryLogosLoc+accountDetails.places.categoryDetails.shadowClusterIconName
    };
    this.catMngr.fillCatLayer(params,srf,bound);
    this.locatorPoint = this.catMngr.layer.features;
    return;
  }
  //if(!this.catMngr.layer) { this.catMngr.createCatLayer();}  
     
  for(var i=srf.showSets[srf.curShowSet].from-1;i<srf.showSets[srf.curShowSet].to;i++) {
    if(srf.results[i].geom) {
      var entity=srf.results[i];
      var v = new OpenLayers.Geometry.fromWKT(entity.geom);
      var pFeature = new OpenLayers.Feature.Vector(v,entity);
      var pObj=this.lonLatObjFrmPoint(entity.geom);
      bound.extend(new OpenLayers.LonLat(pObj.lon,pObj.lat));
      this.locatorPoint[entity.lpIndex]=pFeature;
      this.locatorPoint[entity.lpIndex].entity = entity;
      features.push(pFeature);
      //entity.shownLayer = 'locatorPointLayer';
    }
  }
  this.locatorPointLayer.addFeatures(features);
}

mbox.prototype.putAlog =function (str){
  //console.log ("the log is:"+str);
}

mbox.prototype.addToOnSelectControl = function (layer) {
  var matchControl=/SelectFeature/gi;
  var existingControl= this.map.getControlsByClass(matchControl);
  var existingLayers=[];
  if (existingControl[0]){
    if (existingControl[0].layers ){
      for (i=0;i<existingControl[0].layers.length;i++) { 
          existingLayers.push(existingControl[0].layers[i]);
      }
    } else {
      existingLayers.push(existingControl[0].layer);
    }
    existingControl[0].deactivate;
    //existingControl[0].destroy;
    this.map.removeControl(existingControl[0]);
    existingControl[0].destroy;
  } else {
    // Special case when control is not present add dragCar layer
    existingLayers.push(this.textDirLayer);
    existingLayers.push(this.carMarkLayer);
    existingLayers.push(this.busStopsLayer);
  }
  existingLayers.push(layer);
  this.map.setLayerIndex(this.carMarkLayer,13);
  this.universalSelect = new OpenLayers.Control.SelectFeature(
    existingLayers,
    { clickout:true,
      toggle:true,
      hover: false,
      //  opacity:1,
      highlightOnly: false
    }
  );
  this.map.addControl(this.universalSelect);
  this.universalSelect.activate();
  this.universalSelect.handlers.feature.stopDown = false;
}

mbox.prototype.substituteDescriptionVariables = function (data) {
  // TBD currently other than image variables are not substituted
  var d = data.description;
  d = d.replace(/CUSTOM_VIDEO_PATH./gi,cfg.highBwcustomVideoUrl);
  //d = d.replace(/CUSTOM_IMAGE_PATH./gi,cfg.cloneImageUrl);
  if (!d.match(/img.*id.*popupImage.*src.*POIID_P_IMAGE_NAME/)) { return d; }
  d = d.replace(/src.*POIID_P_IMAGE_NAME/,'src='+imagePathsObj.ajaxLoader+' style=\'position:absolute;left:150px;top:125px;\' ');
  this.getPoiData(data.poiid,[{id:'popupImage',src:'image'}]);
  return d;
}

mbox.prototype.getPoiData = function (poiid,commits) {
  var populatePoiDataWrap = function (response) {
    var resp = JSON.parse(response);
    var res = resp.srf[0].results[0];
    for (var i in commits) {
      if (res[commits[i].src]) {
        $('#'+commits[i].id).removeAttr('src');
        $('#'+commits[i].id).attr('src',cfg.cloneImageUrl+res[commits[i].src]);
        $('#'+commits[i].id).css({position:null,left:null,top:null});
      }
    } 
  }
  var data={action:"businessSearch",city:cfg.city,place:"id="+poiid,account:vidteq.account,key:vidteq.key};
  var magicCall = $.ajax({
    url:cfg.magicHappensUrl,
    data:data,
    dataType:'html/JSON',
    success: populatePoiDataWrap,
    error:function(response) {ioAreaObj.handleError(response);}
  });     
}

//mbox.prototype.addLandMarkPopup = function (evt) {
//  var f=evt.feature;
//  //ioAreaObj.displayMessage('&nbsp');
//  //if (!f.data.description || this.utils.trim(f.data.description) == '') { return; }
//  if (!f.data.description) { return; }
//  var htmlContent={};
//  //htmlContent.content= f.data.description;
//  //htmlContent.content= mboxObj.substitutePopupPaths(f.data.description);
//  htmlContent.content= this.substitutePopupPaths(f.data.description);
//  if (!f.data.description || utils.trim(f.data.description) == '') { return; }
//  htmlContent.size=new OpenLayers.Size (50,50);
//  this.openLandMarkPopup=new OpenLayers.Popup.FramedCloud("landMarkPopup",
//    new OpenLayers.LonLat(f.geometry.x,f.geometry.y),
//    htmlContent.size,
//    htmlContent.content,null,false
//  );
//    
//  this.map.addPopup(this.openLandMarkPopup);
//  //var imageSource=cloneImageUrl+"IND_BLR_POI_15_77.627350_12.937683";
//  //if (!$("#popimage").attr('src')) { $("#popimage").attr('src',imageSource); }
//  this.openLandMarkPopup.setOpacity(1);
//  document.getElementById('landMarkPopup').className='optionsdiv';
//  document.getElementById('landMarkPopup_GroupDiv').className='optionsdiv';
//  document.getElementById('landMarkPopup_contentDiv').className='optionsdiv';
//  this.openLandMarkPopup.div.style.zIndex=18000;
//  $('#myid').height($('#landMarkPopup_contentDiv').height()+30);
//  $('#myid').width($('#landMarkPopup_contentDiv').width()+25);
//  $('#landMarkPopup_contentDiv').height($('#landMarkPopup_contentDiv').height()+30);
//  $('#landMarkPopup_contentDiv').width($('#landMarkPopup_contentDiv').width()+25);
//  var boxImage = { url:imagePathsObj.refBox3, cornerW:10, cornerH:10, boxW:510, boxH:378, offsetW:0, offsetH:0 };
//  utils.boxify(boxImage,'landMarkPopup_contentDiv',{lt:1,rt:1,lb:1,rb:1});
//  var newTop = parseInt($('#landMarkPopup_contentDiv').css('top')) > 15 ? 30:0;
//  $('#landMarkPopup_contentDiv').css('left','0px');
//  $('#landMarkPopup_contentDiv').css('top',newTop+'px'); 
//}

mbox.prototype.removeOpenLandMarkPopup = function(evt) {
  if(typeof(this.openLandMarkPopup) != 'undefined' && this.openLandMarkPopup != null) {
    this.map.removePopup(this.openLandMarkPopup);
    this.openLandMarkPopup.destroy();
    this.openLandMarkPopup=null;
    //mboxObj.restoreMapTitle();
    this.restoreMapTitle();
  }
}
     
mbox.prototype.getXOffset = function (gravity) {
  var XOffset = 0;
  //var zoom =mboxObj.getCurrentZoom();
  var zoom =this.getCurrentZoom();
  zoom =zoom+1;
  switch (gravity){
      case "up" : XOffset = 0;
    break;
    case "down": XOffset = 0;
    break;
    case "left": XOffset = -30/zoom;
    break;
    case "right": XOffset = 30/zoom;
    break;
    case "ne" : XOffset = 30/zoom;
    break;
    case "nw" : XOffset = 30/zoom;
    break;
    case "se" : XOffset = 30/zoom;
    break;
    case "sw" : XOffset = 30/zoom;
    break;
    default : XOffset= 0;
    break;
  }
  return XOffset ;
}
mbox.prototype.getYOffset = function (gravity) {
  //var zoom =mboxObj.getCurrentZoom();
  var zoom =this.getCurrentZoom();
  zoom=zoom+1;
  var YOffset = 0;
  switch (gravity){
    case "up" : YOffset = 50/zoom;
    break;
    case "down": YOffset = 50/zoom;
    break;
    case "left": YOffset = 0;
    break;
    case "right": YOffset = 0;
    break;
    case "ne": YOffset = 20/zoom;
    break;
    case "nw": YOffset = 20/zoom;
    break;
    case "se": YOffset = -20/zoom;
    break;
    case "sw": YOffset = -20/zoom;
    break;
    default : YOffset = 0;
    break;
    }
  return YOffset ;
}
mbox.prototype.nearby  = function (point, pointArray) {
  //for (var i in pointArray) {
  //  if (typeof(pointArray[i])!= 'undefined' ){
  //    var cc = pointArray[i].geometry.getBounds().getCenterLonLat();
  //    }  else {
  //     cc= point.geometry.getBounds().getCenterLonLat();  
  //    }
  //      var fc = point.geometry.getBounds().getCenterLonLat();
  //      this.resolution= mboxObj.getResolution ();
  //      var distance = (
  //          Math.sqrt(
  //              Math.pow((cc.lon - fc.lon), 2) + Math.pow((cc.lat - fc.lat), 2)
  //          ) / this.resolution
  //      );
  //    }
  //
  //return 0;  
}

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

//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 pfLayer={};
  // 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;
  //  pfLayer.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: 8
  //  },
  //  { context : {
  //    pointRadius : function(feature) {
  //    	
  //    	
  //      if (typeof (feature.data.style) != 'undefined' && feature.data.style) {
  //      	//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' && feature.data.style ){
  //    	   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' && feature.data.style) {
  //        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' && feature.data.style &&
  //          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' && feature.data.style) {
  //        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;
  //        } 
  //      } 
  //    }
  //  }});   
  pfLayer.layer = new OpenLayers.Layer.Vector(
            "LandMarkLayer",
             {
             styleMap: new OpenLayers.StyleMap({
               //"default" :pfLayer.defaultStyle
               "default" :this.pfLayerStyle
             }), isBaseLayer: false
  });
  pfLayer.layerPolygon = new OpenLayers.Layer.Vector(
            "LandMarkLayerPolygon",
             {
             styleMap: new OpenLayers.StyleMap({
               //"default" :pfLayer.defaultStyle
               "default" :this.pfLayerStyle
             }), 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);
  }
  pfLayer.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);
  }
  pfLayer.layer.addFeatures(featuresClickable);
  pfLayer.layer.addFeatures(featuresPolygon);
  pfLayer.select = new OpenLayers.Control.SelectFeature(
    pfLayer.layer, 
    { clickout:false,
       toggle:false,
       hover: true,
       highlightOnly: true
  });
  this.map.addControl(pfLayer.select);
  this.map.addLayer(pfLayer.layer);
  this.map.addLayer(pfLayer.layerPolygon)
  this.map.setLayerIndex (pfLayer.layer,2);
  this.map.setLayerIndex (pfLayer.layerPolygon,1);
  var entity = this.gui.getEntity.apply(this.gui,['center',1]);
  entity=this.gui.prepareCenterEntity(entity);
  var centerFeature =new OpenLayers.Feature.Vector(new OpenLayers.Geometry.fromWKT(entity.geom));
  var pfLayerExtent=pfLayer.layer.getDataExtent();
  var newExtent=mboxObj.extendDExtentWithFeature(pfLayerExtent,centerFeature);
  mboxObj.zoomToPfLayerExtent(newExtent);
 // mboxObj.clearRouteAndSrf();
  //mboxObj.zoomToPfLayerExtent(pfLayerExtent);
  this.gui.changeBackOpacity(1);
  
}
mbox.prototype.extendDExtentWithFeature =  function(extent,feature) {
	var newExtent= extent;
	if (extent.left > feature.geometry.x) {newExtent.left=feature.geometry.x}
	if (extent.right<feature.geometry.x){newExtent.right=feature.geometry.x}
	if (extent.bottom >feature.geometry.y) {newExtent.bottom=feature.geometry.y}
	if (extent.top<feature.geometry.y) {newExtent.top=feature.geometry.y}
	return newExtent;

}
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++){
    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);
  iconImage= cfg.imageLogosLoc+""+response.icon;
  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 {
//      delete this[which].startOrEnd;
//      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 {
//      this[which].startOrEnd=which; 
//      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);
//    if (this.gui) { this.gui.fillIoForm(which,name); }
//    else {
//      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')) {
//      if (this.gui) { this.gui.fillIoForm(which,this.getName(which)); }
//      else {
//        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 { 
//      this[which].startOrEnd=which; 
//      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);
//    if (this.gui) { this.gui.fillIoForm(which,name); }
//    else {
//      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;
//}

mbox.prototype.changeMapBaseLayer = function (whichCity) {
  var mapOptions = { 
    resolutions: cfg.resolutions.split(','),
    maxExtent:new OpenLayers.Bounds.fromString(cfg.maxExtent),
    fallThrough:true,
    controls: []
  }
  this.map.setOptions(mapOptions);
  this.baseLayer = new OpenLayers.Layer.WMS(cfg.tilecacheBaseLayer,
     cfg.tilecacheBaseUrl,
    { layers: cfg.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="'+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);
  this.map.setBaseLayer(this.baseLayer);
  this.map.removeLayer(this.earlierBaseLayer);
  this.map.setLayerIndex (this.baseLayer,1);
  this.map.zoomToExtent(new OpenLayers.Bounds.fromString(cfg.maxExtent),false);
  this.map.setCenter(new OpenLayers.LonLat(cfg.centerLon,cfg.centerLat),cfg.topZoom);
  
}

mbox.prototype.changeCity= function (whichCity){
 
  clearAll();
  this.earlierBaseLayer = this.baseLayer;
  this.changeMapBaseLayer(whichCity);
}

mbox.prototype.prepareLightpullReqObj =function () {
  mapImageObject={};
  var lastOne = this.carPathArray[this.carPathArray.length-1];
  mapImageObject.route={'startGeom':"POINT("+this.carPathArray[0][0]+")",
                        'endGeom':"POINT("+lastOne[lastOne.length-1]+")"};
  mapImageObject.proximity=[];
  for(var i in this.syncMapPoints) {
    var a={};
    var cur = this.carPathArray[parseInt(this.syncMapPoints[i])][0];
    a.geom="POINT("+cur+")";
    a.icon={"name":(i+1)+".png","size":16};
    mapImageObject.proximity.push(a);
  }
  return mapImageObject;
}

mbox.prototype.getFeatureFromCluster =function (index) {
  var featureArray = this.catMngr.layer.features;
  var len = featureArray.length;
  var cluster,cluster_len,feature;
//loop thorugh to find the feature with same lpindex
  for(var i = 0;i<len;i++){
  	if(featureArray[i].cluster){
	  cluster = featureArray[i].cluster;
	  cluster_len = cluster.length;
	  //loop to look inside every element of the cluster
	  for(var j =0;j<cluster_len;j++){
	    if(cluster[j].data.lpIndex == index){
		  feature = featureArray[i];
		  break;
	    }
	  }
	  if(feature) {break;}
    }else if(featureArray[i].data.lpIndex == index){
	  feature = featureArray[i];
	  break;
    }
  }
  return feature;
}

///// new Popup

mbox.prototype.getMouseOverThumbNail =function () {
  $('#yo').css('opacity','0.4');
  //$('#spanName').css('display','block');
  //$('#spanName').animate({
  //    width:'toggle'
  //  },'slow',function(){
  //    //that.flag = 0;
  //    //$('#spanName').show();
  //    //$('#disDir').show();
      $('#spanName').css('display','block');
  //  });

}

mbox.prototype.getMouseOutThumbNail =function () {
  //$('#spanName').css('display','none');
  //$('#spanName').animate({
  //  width:'toggle'
  //},'slow',function(){
  //  //that.flag = 1;
    $('#spanName').css('display','none');
  //  //$('#spanName').hide();
  //});

  $('#yo').css('opacity','1');
}

mbox.prototype.getNewThumbNail =function () {
  var divsize= $("#spanName").css("width");
  var integerDivSize= divsize.replace(/px$/, '');
  var that = this;
  if(this.flag == 1){
    $('#spanName').css('z-index','1500');
    $('#spanName').animate({
      width:'toggle'
    },'slow',function(){
      that.flag = 0;
      $('#spanName').show();
      $('#disDir').show();
    });
  } else {
    mboxObj.enNewlargeThumbNail();
  }  
}

mbox.prototype.enNewlargeThumbNail =function () {
  var that = this;
  $('#disDir').hide();
  $('#spanName').animate({
    width:'toggle'
  },'slow',function(){
    that.flag = 1;
    $('#spanName').hide();
  });
}

mbox.prototype.addNewLandMarkPopup = function (evt) {
  var f=evt.feature;
  var divsize= f.attributes.description;
  //var width = 320+30;
  //var height = 240+30;
  if (!f.data.description) { return; }
  var htmlContent={};
  htmlContent.content= this.substituteDescriptionVariables(f.data);
var divh = $('#myid').innerHeight();
  if (!f.data.description || utils.trim(f.data.description) == '') { return; }
  //htmlContent.size=new OpenLayers.Size (width+"px",height+"px");
  //htmlContent.size=new OpenLayers.Size ('auto','auto');
  this.openLandMarkPopup=new OpenLayers.Popup.Anchored("landMarkPopupNew",
    new OpenLayers.LonLat(f.geometry.x,f.geometry.y),
    //htmlContent.size,
    null,
    htmlContent.content,null,true
  );
  this.map.addPopup(this.openLandMarkPopup);
  //this.openLandMarkPopup.autoSize = true;
  this.openLandMarkPopup.setOpacity(1);
  this.openLandMarkPopup.setBackgroundColor('transparent');
  $('#landMarkPopupNew_contentDiv').css('overflow','hidden');
  this.openLandMarkPopup.panMapIfOutOfView = true;
  this.openLandMarkPopup.updateSize();
  $('#landMarkPopupNew_close').css('z-index','3000');
  $('#landMarkPopupNew_close').css('top','0px');
  if (self.navigator.userAgent.match(/MSIE/)){
    $('#landMarkPopupNew_close').css('right','18px');
  } else {
    $('#landMarkPopupNew_close').css('right','36px');
  }
  var that = this;
  $('#landMarkPopupNew_close').click(function(){
    var prevFeature = that.map.layers[2].selectedFeatures[0].data;
   
    that.map.layers[2].selectedFeatures[0].destroy();
    that.openLandMarkPopup.destroy();
    var v = new OpenLayers.Geometry.fromWKT(prevFeature.geom);
    var pFeature = new OpenLayers.Feature.Vector(v,prevFeature);
    that.map.layers[2].addFeatures(pFeature);
  });
}

mbox.prototype.toFunction = function () {
  var featureData = this.map.layers[2].selectedFeatures[0].data;
  ioAreaObj.genericEntity = [{},{
    geom:featureData.geom,
    index:1,
    lonlat:this.lonLatObjFrmPoint(featureData.geom),
    address:{
      name:featureData.name
    }
  }];
  ioAreaObj.dirFromTo('end',1,'genericEntity');
  ioAreaObj.goVid();
  //this.swaprouteTo(featureData);
}

mbox.prototype.fromFunction = function () {
  var featureData = this.map.layers[2].selectedFeatures[0].data;
  ioAreaObj.genericEntity = [{},{
    geom:featureData.geom,
    index:1,
    lonlat:this.lonLatObjFrmPoint(featureData.geom),
    address:{
      name:featureData.name
    }
  }];
  ioAreaObj.dirFromTo('start',1,'genericEntity');
  ioAreaObj.goVid();
  //this.swaprouteFrom(featureData);
}  

//mbox.prototype.swaprouteTo = function(featureData) {
//  debugPrint("inside the to ..");
//  featureData.lonlat = this.lonLatObjFrmPoint(featureData.geom);
//  this.addRcmStartOrEndMarker('end',featureData.lonlat);
//  debugPrint("marker placed - now go vid ..");
//  if (ioAreaObj.embed) { ioAreaObj.goVid(); }
//  
//  //if($('#starttextbox').css('font-weight') != 'bold'){ 
//  //  var startAddress = document.GetVal.start.value;
//  //  var endAddress = document.GetVal.end.value;
//  //  
//  //  $('#starttextbox').css('font-weight','normal'); 
//  //  $('#endtextbox').css('font-weight','normal'); 
//  //  document.GetVal.start.value=document.GetVal.end.value;
//  //  document.GetVal.end.value=startAddress;
//  //  $('#starttextbox').css('font-weight','bold'); 
//  //}
//  //routeEndsObj.replaceEntity('end',feature);
//}

//mbox.prototype.swaprouteFrom = function(featureData) {
//  debugPrint("inside the from ..");
//  featureData.lonlat = this.lonLatObjFrmPoint(featureData.geom);
//  this.addRcmStartOrEndMarker('start',featureData.lonlat);
//  debugPrint("marker placed - now go vid ..");
//  if (ioAreaObj.embed) { ioAreaObj.goVid(); }
//  
//  
//  //if($('#endtextbox').css('font-weight') != 'bold'){ 
//  //  var startAddress = document.GetVal.start.value;
//  //  var endAddress = document.GetVal.end.value;
//  // 
//  //  $('#starttextbox').css('font-weight','normal'); 
//  //  $('#endtextbox').css('font-weight','normal'); 
//  //  document.GetVal.end.value = document.GetVal.start.value;
//  //  document.GetVal.start.value = endAddress;
//  //  $('#endtextbox').css('font-weight','bold');
//  //} 
//  //routeEndsObj.replaceEntity('start',feature);
//}

mbox.prototype.getBackThumbNailPopup1 =function (width,height) {
  var divsize= $("#popupImage").css("width");
  
  var integerDivSize= divsize.replace(/px$/, '');
  
  var that = this;
  if (integerDivSize > 80){
   
   $("#yo").animate({width:"80px",height:"80px",left:"0px",right:"10px"},200);
   $("#popupImage").animate({width:"80px",height:"80px",right:"0px",top:"2px"},200,function(){  
     $("#yo").css('margin-right','5px');  
     $("#yo").css('margin-top','5px');  
     $("#yo").css('top','30px'); 
     $("#headerSpan").show();
     $("#spanName").show();
   });
  } else {
    that.enlargeThumbNailPopup1(width, height);
  }  
}
mbox.prototype.enlargeThumbNailPopup1 =function (width,height) {
  
  var myIEWidth= 320;
  var myFFWidth=320;
  var myIEHeight=240;
  var myFFHeight=240;
  $("#headerSpan").hide();
  $("#spanName").hide();
  if (self.navigator.userAgent.match(/MSIE/)){
    $("#yo").animate({width:myIEWidth+"px",height:myIEHeight+"px",top:'0px',left:"0px",right:"10px"},200);
    $("#popupImage").animate({width:myIEWidth+"px",height:myIEHeight+"px",left:"2px",right:"10px"},200,function(){ 
       $("#yo").css('margin-right','0px'); $("#yo").css('margin-top','0px'); $("#yo").css('top','0px'); });
  } else {
    $("#yo").animate({width:myFFWidth+"px",height:myFFHeight+"px",left:"0px",right:"10px"},200);
    $("#popupImage").animate({width:myFFWidth+"px",height:myFFHeight+"px",left:"2px",right:"10px"},200,function(){ 
       $("#yo").css('margin-right','0px'); $("#yo").css('margin-top','0px'); $("#yo").css('top','0px'); });
  }
}

