/*

*/
function suggestBox(id,defaultValue,topClearList,topUpKeyList,topDownKeyList) {
  this.name = id;
  this.id = '#'+id;
  this.defaultValue = defaultValue;
  this.currentText = '';
  this.noOfSuggestions = 0;
  $(this.id)[0].value = defaultValue;
  var that = this;
  var clearSuggestDivWrap = function () {that.clearSuggestDiv();}
  topClearList.push(clearSuggestDivWrap);
  var lowerSelectSuggestRowWrap = function() {that.lowerSelectSuggestRow();}
  topUpKeyList.push(lowerSelectSuggestRowWrap);
  var higherSelectSuggestRowWrap = function() {that.higherSelectSuggestRow();}
  topDownKeyList.push(higherSelectSuggestRowWrap);
}

suggestBox.prototype.assignEvents = function() {
  var that = this;
  var suggestMatchesWrap = function () {that.suggestMatches();};
  $(this.id)[0].onkeyup=suggestMatchesWrap;
  // TBD attach a function in body for clearing this suggest checkKeyEvents
  // onkeydown = checkKeyEvents
  // onclick = clearSuggestDiv
  var clickTextboxWrap = function () {that.clickTextbox();};
  $(this.id)[0].onclick=clickTextboxWrap;
  var focusTextboxWrap = function () {that.focusTextbox();};
  $(this.id)[0].onfocus=focusTextboxWrap;
  var blurTextboxWrap = function () {that.blurTextbox();};
  $(this.id)[0].onblur=blurTextboxWrap;
}

suggestBox.prototype.insertPlace = function(e) {
  //console.log("insert place for "+this.id); 
  //console.log(e.data.name); 
  $(this.id)[0].value = e.data.name;
}

suggestBox.prototype.lowerSelectSuggestRow = function() {
  if ($(this.sugDivId)[0].style.visibility != 'visible') {return;}
  //console.log("lowering request "+this.currentSuggestIndex);
  this.sendSuggestRequest=0;
  this.currentSuggestIndex--;
  this.currentSuggestIndex=(this.currentSuggestIndex==-2)?(this.noOfSuggestions-1):this.currentSuggestIndex;
  this.currentSuggestIndex=(this.currentSuggestIndex==-1)?(this.noOfSuggestions-1):this.currentSuggestIndex;
  this.selectSuggestRow(this.currentSuggestIndex);
}

suggestBox.prototype.higherSelectSuggestRow = function() {
  if ($(this.sugDivId)[0].style.visibility != 'visible') {return;}
  //console.log("hghering request "+this.currentSuggestIndex);
  this.sendSuggestRequest=0;
  this.currentSuggestIndex++;
  this.currentSuggestIndex=(this.currentSuggestIndex==this.noOfSuggestions)?0:this.currentSuggestIndex;
  this.selectSuggestRow(this.currentSuggestIndex);
}

suggestBox.prototype.selectSuggestRow = function(rowIndex) {
  //console.log("selectSuggest row on "+rowIndex);
  if ($(this.sugDivId)[0].style.visibility != 'visible') {return;}
  var sugRowId="suggestrow"+rowIndex;
  $('#'+sugRowId)[0].className='sugrowhighlight';
  $(this.id)[0].value = this.currentText = $('#'+sugRowId).data('oneSuggest');
}

suggestBox.prototype.suggestMatches=function () {
  //console.log("suggest Matches for "+this.id); 
  var obj = $(this.id)[0];
  this.userText=obj.value;
  this.userText=this.userText.replace(/^\s+/,"");
  this.userText=this.userText.replace(/\s+$/,"");
  //if(this.userText!=this.defaultValue) 
  if(this.userText!=this.currentText) {
    if(this.userText.length==0) {
      this.clearSuggestDiv();
    } else {
      // TBD remove routend  trigger function
    }
    this.currentText = this.userText;
    this.sendSuggestRequest=1;
    this.theRowSelected=null;
  }
  if(this.userText && this.sendSuggestRequest) {
    var data=(vidteq.scriptBased?{qu:this.userText,callbackFunction:'prepareSuggestDropDown'}:{qu:this.userText});
    var url="vs/suggest.php";
    if(vidteq.scriptBased) url=_serverHostUrl+url;
    if(this.sendSuggestRequest) {this.fetchMatches(url,data);}
  }
  return false;
}

suggestBox.prototype.prepareSuggestDropDown=function (placesList) {
  //console.log("prepare suggest drop down "+ this.id);
  var suggestDiv=$(this.sugDivId)[0];
  var that = this;
  if(placesList.length < 0) {
    if(this.userText.charAt(0) =='' ) {  // TBD where userText in context
      suggestDiv.innerHTML = "<div><a class=plain>Please enter atleast one alphabet</a></div>";
    } else {
      suggestDiv.innerHTML = "<div><a class=plain>No matching places</a></div>";
    }
    return false;
  }
  if(placesList.length == 0) {
    this.clearSuggestDiv();
  }
  var innerHTML=null;
  suggestDiv.innerHTML=null;
  suggestDiv.style.visibility='visible';
  suggestDiv.style.zIndex='90000';
  suggestDiv.style.width='440px';
  innerHTML=suggestDiv.innerHTML;
  innerHTML="<table id='suggesttable' cellspacing=0 cellpadding=2 style='width:100%'><tbody>";
  innerHTML+="</tbody></table>";
  suggestDiv.innerHTML=innerHTML;
  var myTable = $('#suggesttable');
  for(i=0;i<placesList.length;i++) {
    var otherHalf=placesList[i].substring(this.userText.length,placesList[i].length);
    var oneTr ="<tr id=suggestrow"+i+" class=sugrow onmouseover=this.className='sugrowhighlight'; onmouseout=this.className='sugrow'  align='left'><td align='left' style='padding-left:4px;border-bottom:1px inset "+mainColor+";' ><a class=suggest onfocus=this.blur();   href='javascript:void(0);'> <b>"+this.userText+"</b>"+otherHalf+"</a></td></tr>";
    if($('tbody', myTable).length > 0){
      $('tbody', myTable).append(oneTr);
    } else {
      $(myTable).append(myTable);
    }
    //$('#suggestrow'+i)[0].onclick = function () { that.insertPlace(this); };
    $('#suggestrow'+i).data('oneSuggest',placesList[i]);
    $('#suggestrow'+i).bind('click',{name:placesList[i]},function (e) {that.insertPlace(e);});
  }
  //for(i=0;i<placesList.length;i++) {
  //  var otherHalf=placesList[i].substring(this.userText.length,placesList[i].length);
  //  var placeName=placesList[i].replace(/\s+/g,'-');
  //  placeName=placeName.replace(/\'/g,"\\\'");
  //  innerHTML+="<tr id=suggestrow"+i+" class=sugrow onmouseover=this.className='sugrowhighlight'; onclick=insertPlace('"+placeName+"','"+whichBox+"'); onmouseout=this.className='sugrow'  align='left'><td align='left' style='padding-left:4px;border-bottom:1px inset "+mainColor+";' ><a class=suggest onfocus=this.blur();   href='javascript:void(0);'> <b>"+this.userText+"</b>"+otherHalf+"</a></td></tr>";
  //}
  //innerHTML+="</tbody></table>";
  //suggestDiv.innerHTML=innerHTML;
  this.currentSuggestIndex=-1;
  this.noOfSuggestions = placesList.length;
  var that = this;
  setTimeout(function () {that.clearSuggestDiv();},40000);
  return false;
}

suggestBox.prototype.fetchMatches = function(url,data) {
  //console.log("fetch Matches for "+this.id); 
  this.noOfSuggestions = 5;
  var that = this;
  var prepareSuggestDropDownWrap = function (placesList) {
    that.prepareSuggestDropDown(placesList);
  }
  $.ajax({
    url:url,
    type: 'GET',
    data:data,
    dataType:vidteq.dataType,
    success:prepareSuggestDropDownWrap,
    error:function () {}
  });
  return false;    
}

suggestBox.prototype.clickTextbox=function () {
  //console.log("click text box for "+this.id); 
  var obj = $(this.id)[0];
  if(obj.value==this.defaultValue) {
    obj.value="";
    this.currentText="";
    // TBD remove routend  trigger function
  }
  this.clearSuggestDiv();
}

suggestBox.prototype.focusTextbox = function() {
  //console.log("focus text box for "+this.id); 
  var obj = $(this.id)[0];
  obj.value=(obj.value=='')?this.defaultValue:obj.value;
}
suggestBox.prototype.blurTextbox=function () {
  //console.log("blur text box for "+this.id); 
  var obj = $(this.id)[0];
  //obj.value=(obj.value=='')?this.defaultValue:obj.value;
  if (obj.value == '') {
    this.currentText.start=this.defaultValue;
    obj.value=this.defaultValue;
    // TBD remove routend  trigger function
  }
}

suggestBox.prototype.clearSuggestDiv =function () {
  //console.log("clear suggest box for "+this.id); 
  var suggestDiv=$(this.sugDivId)[0];
  suggestDiv.innerHTML='';
  suggestDiv.style.visibility='hidden';
}

/*
 * Constructor of ioArea class, takes care of all input related management
 *
 * */
function ioArea(isEmbed,msgObj){
  
  if(isEmbed && isEmbed.on==true) {
    this.embed={};
    this.embed.fix=isEmbed.fix;
    this.embed.hosting=isEmbed.hosting;  
    this.embed.other=(this.embed.fix=='start')?'end':
                     (this.embed.fix=='end')?'start':'';
    this.initEmbed();
  }
  this.mode="LOCATE"; //which mode the application is in ... LOCATE/ROUTE
  this.locationName=(typeof(msgObj.locationName)!='undefined')?msgObj.locationName:"Business or Address Locator";
  this.startPlaceName="Start Address";
  this.endPlaceName="End Address";
  this.inputValEmail="id@company.com";
  this.inputValSMS="Eg. 9XXXXXYYYYY";
  this.inputMapOrText='TEXT';
  this.helpLocate=(typeof(msgObj.helpLocate)!='undefined')?msgObj.helpLocate:'';
  this.helpRoute=(typeof(msgObj.helpRoute)!='undefined')?msgObj.helpRoute:'';
  this.userText='';
  this.currentText={};
  this.currentText.start='';
  this.currentText.end='';
  this.sendSuggestRequest=1;
  this.theRowSelected=null;
  this.noOfSuggestions=0;
  this.startAddress=null;
  this.endAddress=null;
  this.loadSyncCalled=false;
  this.openLayersLoaded=false;
  this.popup=null;
  this.searchComplete=false;
  this.suggestedPlace=0;
  this.bangaloreCenter={
    address:{name:'Bangalore Center'},
    geom:'POINT('+globalLon+' '+globalLat+')'
  }	  
  this.loadingDivMessage="<table align='center'><tr><td><a class='message'><b>Loading..</b></a></td><td><img src='"+imagePathsObj.load+"' /></td><td><a style='cursor:pointer;' class='message'  href='javascript:void(0);' onclick='javascript:ioAreaObj.cancelRequest();return false;'>Cancel</a></td></tr></table>";
  this.link="http://"+document.location.host+document.location.pathname;
  // TBD need to be moved out to safe haven
  this.getRoadNameStartOrEnd=''; // Not a good idea TBD
  this.response = null;
  this.preReqStart = '';
  this.preReqEnd = '';

  //this.clearAnySuggestFuncList = new Array();
  //this.lowerAnySuggestFuncList = new Array();
  //this.higherAnySuggestFuncList = new Array();
  //$('#newbox')[0].className = "small";
  //this.myIn = new suggestBox('newbox','blah and this',
  //  this.clearAnySuggestFuncList,
  //  this.lowerAnySuggestFuncList,
  //  this.higherAnySuggestFuncList);
  //this.myIn.sugDivId = '#sugnewbox';
  //this.myIn.assignEvents();

  return false;
}  

ioArea.prototype.executeAllFunc = function (funcArray) {
  for (var i in funcArray) {(funcArray[i])();}
}

ioArea.prototype.fixTheEnd = function (which) {
  this.embed.fix=which;
  this.embed.other=(this.embed.fix=='start')?'end':
                   (this.embed.fix=='end')?'start':'';
}

ioArea.prototype.initEmbed = function () {
  if (typeof(accountDetails) == 'undefined') return;
  switch (accountDetails.q) {
    //case "minimap": 
    //  ioAreaObj=new ioArea({on:true,fix:'end',hosting:true},{}); 
    //  captureMinimapParams(); 
    //  break;
    case "wayfinder":
    case "blocate":
      this.fixTheEnd('end'); // TBD need to be programmable
      this.hosting = true; // TBD why duplication with vidteq object
      this.embed[accountDetails.q] = accountDetails.places;
      if (accountDetails.firstTimeRule) {
        this.embed.firstTimeRule = accountDetails.firstTimeRule; 
        // this is not necessary as we can use firstTimeRule 
        // from account detail and dump it TBD
      }
      this.embed.place = accountDetails.places.center.entity;
      this.prepareCenterEntity(this.embed.place);
      // this is present for backward compatibility TBD
      // TBD revise this place entity
      break;
    case "locatestores":
      this.fixTheEnd('end'); // TBD need to be programmable
      this.hosting = true; // TBD why duplication with vidteq object
      this.locationName = 'Enter your address to find a store nearby'; // TBD does not belong to embed object - may get overwritten

      //this.embed[accountDetails.q] = accountDetails.places;
      this.embed.locateStores = accountDetails.places;
      if (accountDetails.firstTimeRule) {
        this.embed.firstTimeRule = accountDetails.firstTimeRule; 
        // this is not necessary as we can use firstTimeRule 
        // from account detail and dump it TBD
      }
      break;
    //default: goToError(); break;
    default:document.location.href='error.html';break;
    // TBD - generic error handler needed - with messaging provision
    // Automatic minimap fall back in case allotted size is small TBD
  }
  switch (parseInt(vidteq.pf)) {
  case 1:
    this.embed.vidHeight='160px';
    this.embed.vidWidth='240px';  
    break;
  case 2:
    this.embed.vidHeight='256px';
    this.embed.vidWidth='384px';  
    break;
  case 3:
  default:
    this.embed.vidHeight='320px';
    this.embed.vidWidth='480px';  
    break;  
  }
  this.embed.cssUrl='css/embedcss.php?q='+accountDetails.q;
  this.embed.cssUrl+='&pf='+accountDetails.config.pf;
  this.embed.cssUrl+=typeof(this.embed.width)!='undefined'?'&w='+this.embed.width:'';
  this.embed.cssUrl+='&topStripColor='+vidteq.topStripColor;
  this.embed.cssUrl+='&fvtColor='+vidteq.fvtColor;   
  this.embed.cssUrl+='&topStripTextColor='+vidteq.topStripTextColor;
  this.embed.cssUrl+='&fvtTextColor='+vidteq.fvtTextColor;   
  this.embed.cssUrl+='&fvtTextHoverColor='+vidteq.fvtTextHoverColor;   
  this.embed.cssUrl = this.embed.cssUrl.replace(/#/g,"");
}

ioArea.prototype.selectMode=function (whichOne) {
  if(whichOne=='ROUTE') {
    if($('#locationtab')[0]) $('#locationtab')[0].className='inactive';
    if($('#routetab')[0]) $('#routetab')[0].className='active';
    if($('#helpdiv')[0]) $('#helpdiv')[0].innerHTML=this.helpRoute;
    $('#swaptd')[0].style.display='block';
    document.GetVal.end.className='small';
    $('#starttextbox')[0].className="small";
    $('#endtextbox')[0].className="small";
    $('#starttextbox')[0].tabIndex=1
    $('#endtextbox')[0].tabIndex=2
    $('#GoVid')[0].tabIndex=3
    document.GetVal.start.value=(document.GetVal.start.value==this.locationName)?this.startPlaceName:document.GetVal.start.value;
    this.mode='ROUTE';
  } else {
    if($('#locationtab')[0]) $('#locationtab')[0].className='active';
    if($('#routetab')[0]) $('#routetab')[0].className='inactive';
    if($('#helpdiv')[0]) $('#helpdiv')[0].innerHTML=this.helpLocate;
    $('#swaptd')[0].style.display='none';
    document.GetVal.end.className='smallhidden';
    $('#starttextbox')[0].className="big";
    $('#endtextbox')[0].className="smallhidden";
    $('#starttextbox')[0].tabIndex=1
    $('#endtextbox')[0].tabIndex=-1
    $('#GoVid')[0].tabIndex=2
   document.GetVal.start.value=(document.GetVal.start.value==this.startPlaceName)?this.locationName:document.GetVal.start.value;
    this.mode='LOCATE';
  }
  return false;
}  

ioArea.prototype.initialiseInputArea=function () {
  var boxValue;
  this.selectMode('LOCATE');
  if(!ioAreaObj.embed)
    boxValue=($('#locationtab')[0].className=='active')?(this.locationName):(this.startPlaceName);
  else { 
    if(this.embed.locateStores) 
      boxValue=this.locationName;
    else 
      boxValue=this.startPlaceName;
  }
  if (! document.GetVal.end.value) {
    document.GetVal.end.value=this.endPlaceName;
  }
  if (! document.GetVal.start.value) {
    document.GetVal.start.value=boxValue;
  }
  return false;
}

ioArea.prototype.swapParentType = function (obj) {
  if (obj.parentType && obj.parentType == 'startAddress') obj.parentType = 'endAddress';
  else if (obj.srfType && obj.srfType == 'startAddress') obj.srfType = 'endAddress';
  else if (obj.parentType && obj.parentType == 'endAddress') obj.parentType = 'startAddress';
  else if (obj.srfType && obj.srfType == 'endAddress') obj.srfType = 'startAddress';
}

ioArea.prototype.swapSrfResponse = function (obj) {
  var trans = {'ss':'ss','ff':'ff','mm':'mm',
               'sf':'fs','mf':'fm','fs':'sf','fm':'mf',
               'sm':'ms','ms':'sm'};
  for (var i in trans) {
    //if (obj.routeFailType == i) {
    //  obj.routeFailType = trans[i];
    if (obj.responseType == i) {
      obj.responseType = trans[i];
      var temp = obj.srf[0];
      obj.srf[0] = obj.srf[1];
      obj.srf[1] = temp;
      obj.srf[0].srfIndex = 0;
      obj.srf[1].srfIndex = 1;
      this.swapParentType(obj.srf[0]);
      this.swapParentType(obj.srf[1]);
      for (var j in obj.srf[0].results) {
        this.swapParentType(obj.srf[0].results[j]);
      } 
      for (j in obj.srf[1].results) {
        this.swapParentType(obj.srf[1].results[j]);
      }
      break;
    }
  }
}

ioArea.prototype.swapRoute=function () {
  var tempVal=document.GetVal.start.value;
  document.GetVal.start.value=document.GetVal.end.value;
  document.GetVal.end.value=tempVal;
  ioAreaObj.displayMessage("");
  mboxObj.killRcmPopup();
  var routeWasActive = false;
  if(mboxObj.routeActive) {  // clean up the route 
    clearRouteAndSrf(); 
    routeWasActive = true;
  }
  if (mboxObj.srfActive) {  // swap the response
    this.swapSrfResponse(this.srfResponse);
  }  
  routeEndsObj.swap();
  if(this.embed) {   // now swap fixed end
    if(ioAreaObj.embed.fix=='start') {
      ioAreaObj.embed.fix='end';
      ioAreaObj.embed.other='start';
      $('#starttextbox')[0].title='Enter your start address';
      if (!routeEndsObj.isNotEmpty('start') && 
          document.GetVal.start.value == ioAreaObj.endPlaceName) {
        $('#starttextbox')[0].value=ioAreaObj.startPlaceName;
      }
      $('#endtextbox')[0].title='';
    } else if(ioAreaObj.embed.fix=='end') {
      ioAreaObj.embed.fix='start';
      ioAreaObj.embed.other='end';
      $('#starttextbox')[0].title='';
      $('#endtextbox')[0].title='Enter your end address';
      if (!routeEndsObj.isNotEmpty('end') &&
          document.GetVal.end.value == ioAreaObj.startPlaceName) {
        $('#endtextbox')[0].value=ioAreaObj.endPlaceName;
      }
    }
    if(ioAreaObj.embed.fix!='') ioAreaObj.showFixedEnd();
    //if (!routeWasActive && ioAreaObj.embed.blocate) blocateCategoryList();
    //if (!routeWasActive && ioAreaObj.embed.blocate) ioAreaObj.locateNearByBiz();
  }
  if (mboxObj.srfActive) {  
    //fvtObj.writeSrfNew.apply(fvtObj,[this.srfResponse]);
    fvtObj.prepareForShowSrf.apply(fvtObj,[this.srfResponse]);
    this.writeSrfToTable();
  }
  return false;
}

ioArea.prototype.suggestMatches=function (obj) {
  //console.log("Original suggestMatches");
  this.inputMapOrText='TEXT';
  var whichBox=obj.name;
  this.userText=obj.value;
  this.userText=this.userText.replace(/^\s+/,"");
  this.userText=this.userText.replace(/\s+$/,"");
  var text=(obj.id=='starttextbox')?(this.currentText.start):(this.currentText.end);
  if(this.userText!=text) {
    if(this.userText.length==0) {
      this.clearSuggestDiv($('#sugdivstart')[0]);
      this.clearSuggestDiv($('#sugdivend')[0]);
    } else {  
      if(obj.id=='starttextbox') {
        if(typeof(routeEndsObj)!='undefined') routeEndsObj.remove.apply(routeEndsObj,['start']); // TBD
      } else if(obj.id=='endtextbox') {
        if(typeof(routeEndsObj)!='undefined') routeEndsObj.remove.apply(routeEndsObj,['end']); // TBD
      }      
    }
    if(obj.id=='starttextbox') {this.currentText.start=this.userText;}
    else {this.currentText.end=this.userText;}
    this.sendSuggestRequest=1;
    this.theRowSelected=null;
  }
  if(this.userText && this.sendSuggestRequest) {
	var data=(vidteq.scriptBased?{qu:this.userText,callbackFunction:'prepareSuggestDropDown'}:{qu:this.userText});
	var url="vs/suggest.php";
	if(vidteq.scriptBased) url=_serverHostUrl+url;
	if(this.sendSuggestRequest) {this.fetchMatches(url,data,whichBox);}
  }
  return false;
}

ioArea.prototype.fetchMatches=function(url,data,whichBox) {
  var localUserText=this.userText;
  classThis=this;
  var localMode=this.mode;
  this.noOfSuggestions=5;
  prepareSuggestDropDown=function(placesList) {
    var suggestDiv=(whichBox=='start')?($('#sugdivstart')[0]):($('#sugdivend')[0]);
    if(placesList.length>=0) {
      var innerHTML=null;
      if(placesList.length>0) {
        suggestDiv.innerHTML=null;
        suggestDiv.style.visibility='visible';
        suggestDiv.style.zIndex='90000';
	    suggestDiv.style.width=(localMode=='LOCATE')?'440px':'200px';
        innerHTML=suggestDiv.innerHTML;
        innerHTML="<table id='suggesttable' cellspacing=0 cellpadding=2 style='width:100%'><tbody>";
        for(i=0;i<placesList.length;i++) {
          var otherHalf=placesList[i].substring(localUserText.length,placesList[i].length);
          var placeName=placesList[i].replace(/\s+/g,'-');
          placeName=placeName.replace(/\'/g,"\\\'");
          innerHTML+="<tr id=suggestrow"+i+" class=sugrow onmouseover=this.className='sugrowhighlight'; onclick=insertPlace('"+placeName+"','"+whichBox+"'); onmouseout=this.className='sugrow'  align='left'><td align='left' style='padding-left:4px;border-bottom:1px inset "+mainColor+";' ><a class=suggest onfocus=this.blur();   href='javascript:void(0);'> <b>"+localUserText+"</b>"+otherHalf+"</a></td></tr>";
        }
        innerHTML+="</tbody></table>";
        suggestDiv.innerHTML=innerHTML;
        currentSuggestIndex=-1;
        setTimeout('classThis.clearSuggestDiv($("#sugdivstart")[0])',40000);
        setTimeout('classThis.clearSuggestDiv($("#sugdivend")[0])',40000);
      } else {
        classThis.clearSuggestDiv($('#sugdivstart')[0]);
        classThis.clearSuggestDiv($('#sugdivend')[0]);
      }
    } else {
      if(localUserText.charAt(0) =='' ) {
        suggestDiv.innerHTML = "<div><a class=plain>Please enter atleast one alphabet</a></div>";
      } else {
        suggestDiv.innerHTML = "<div><a class=plain>No matching places</a></div>";
      }
    }
    return false;
  }
  $.ajax({
    url:url,
    type: 'GET',
    data:data,
    dataType:vidteq.dataType,
    success:prepareSuggestDropDown,
    error:function () {}
  });
  return false;    
}

ioArea.prototype.checkKeyEvents=function (event) {
  var sTable=$("#suggesttable")[0];
  if(sTable) {
    var srows=sTable.getElementsByTagName("tr");
    for(var i=0;i<srows.length;i++) {
      srows[i].className="suggestrow";
    }
  }
  var startsug=$('#sugdivstart')[0].style.visibility;
  var endsug=$('#sugdivend')[0].style.visibility;
  var keyCode=event.keyCode?event.keyCode:(event.which?event.which:event.charCode);
  if(this.theRowSelected!=null) {  
    this.theRowSelected=this.theRowSelected.replace(new RegExp(/<b>/g),"");
    this.theRowSelected=this.theRowSelected.replace(/<\/b>/g,"");
  }
  switch (keyCode) {
  case 9:
    this.captureTabEnterOnAutoSug(startsug,endsug);
    break;
  case 13:
    if(this.theRowSelected!=null) {
      this.captureTabEnterOnAutoSug(startsug,endsug);
    } else {
      this.clearSuggestDiv($('#sugdivstart')[0]);
      this.clearSuggestDiv($('#sugdivend')[0]);
      if($("#comdiv")[0]) {
        if(whichPopup=="EMAIL") {
          send('email');  // TBD
        } else if(whichPopup=="SMS") {
          send('sms');  // TBD
        } 
      } else {
        if(document.getElementById('VideoPlayerDiv')) {
          document.getElementById('GoVid').focus();
          this.invokeTheMode();
        } else {
         document.getElementById('GoVid').onclick.call(ioAreaObj);
         document.getElementById('GoVid').focus();    
        }
      }
    }
    break;
  case 38:
    this.sendSuggestRequest=0;
    if(startsug=='visible' || endsug=='visible') {
      currentSuggestIndex--;
      currentSuggestIndex=(currentSuggestIndex==-2)?(this.noOfSuggestions-1):currentSuggestIndex;
      currentSuggestIndex=(currentSuggestIndex==-1)?(this.noOfSuggestions-1):currentSuggestIndex;
      this.selectSuggestRow(currentSuggestIndex);
    }
    //this.executeAllFunc(this.lowerAnySuggestFuncList);
    break;
  case 40:
    this.sendSuggestRequest=0;
    if(startsug=='visible' || endsug=='visible') {
      currentSuggestIndex++;
      currentSuggestIndex=(currentSuggestIndex==this.noOfSuggestions)?0:currentSuggestIndex;
      this.selectSuggestRow(currentSuggestIndex);
    }
    //this.executeAllFunc(this.higherAnySuggestFuncList);
    break;
  default:break;
  }
}

ioArea.prototype.captureTabEnterOnAutoSug=function (startsug,endsug) {
  if(this.theRowSelected!=null) {
    var whichElem={};  
    whichElem=(startsug=='visible')?($('#sugdivstart')[0]):($('#sugdivend')[0]);
    whichElem.value=this.theRowSelected;
    this.clearSuggestDiv(whichElem);
    this.currentText.start=this.theRowSelected;
    currentSuggestIndex=-1;  
    this.theRowSelected=null;  
  }
}

ioArea.prototype.selectSuggestRow=function(rowIndex) {
  var sugRowId="suggestrow"+rowIndex;
  $('#'+sugRowId)[0].className='sugrowhighlight';
  this.theRowSelected=$('#'+sugRowId)[0].getElementsByTagName("a")[0].innerHTML;
  var x=new RegExp("<b>","gi");
  this.theRowSelected=this.theRowSelected.replace(x,"");
  x=new RegExp("<\/b>","gi");
  this.theRowSelected=this.theRowSelected.replace(x,"");
  this.theRowSelected=trim(this.theRowSelected);
  if($('#sugdivstart')[0].style.visibility=='visible' ) {
    this.theRowSelected=this.theRowSelected.replace(/\s+$/,"");
    this.currentText.start=this.theRowSelected;
    document.GetVal.start.value=this.theRowSelected;
  }
  if($('#sugdivend')[0].style.visibility=='visible' ) {
    this.theRowSelected=this.theRowSelected.replace(/\s+$/,"");
    this.currentText.end=this.theRowSelected;
    document.GetVal.end.value=this.theRowSelected;
  }
}

ioArea.prototype.focusTextbox=function(obj) {
  if(obj.name=='start') {
    var boxValue;
    if(!ioAreaObj.embed)
      boxValue=$('#locationtab')[0].className=='active'?this.locationName:this.startPlaceName;
    else boxValue=this.startPlaceName;
    obj.value=(obj.value=='')?boxValue:obj.value;
  } else {
    obj.value=(obj.value=='')?this.endPlaceName:obj.value;
  }
}

ioArea.prototype.clickTextbox=function (obj) {
  ioAreaObj.suggestedPlace=0;
  if(obj.name=="start") {
    var boxValue;
    if(!ioAreaObj.embed)
      boxValue=$('#locationtab')[0].className=='active'?this.locationName:this.startPlaceName;
    else { 
      if(this.embed.locateStores) boxValue=this.locationName;
      else boxValue=this.startPlaceName;
    }	
    if(obj.value==boxValue) {
      obj.value="";
      this.currentText.start="";
      if(typeof(routeEndsObj)!='undefined') routeEndsObj.remove.apply(routeEndsObj,['start']); 
    }
    this.clearSuggestDiv($('#sugdivend')[0]);
  } else if(obj.name=="end") {
    this.clearSuggestDiv($('#sugdivstart')[0]);
    if(obj.value==this.endPlaceName) {
      obj.value="";
      this.currentText.end="";
      if(typeof(routeEndsObj)!='undefined') routeEndsObj.remove.apply(routeEndsObj,['end']);
    }
  } else if(obj.name=="emailbox") {
    obj.value=(obj.value==this.inputValEmail)?'':obj.value;
  } else if(obj.name=="smsbox") {
    obj.value=(obj.value==this.inputValSMS)?'':obj.value;
  }
}

ioArea.prototype.blurTextbox=function (obj) {
  if(obj.name=="emailbox") {
    obj.value=(obj.value=='')?this.inputValEmail:obj.value;  
  }
  else if(obj.name=="smsbox") {
    obj.value=(obj.value=='')?this.inputValSMS:obj.value;  
  } else {  
    var boxValue;
    if(!ioAreaObj)
      boxValue=$('#locationtab')[0].className=='active'?this.locationName:this.startPlaceName;
    else {
      if(this.embed && this.embed.locateStores) boxValue=this.locationName;
      else boxValue=this.startPlaceName;
    }  
    if(document.GetVal.start.value=='') {      
      this.currentText.start=document.GetVal.start.value=boxValue;
      if(typeof(routeEndsObj)!='undefined') routeEndsObj.remove.apply(routeEndsObj,['start']); 
    }
    if(document.GetVal.end.value=='') {      
      this.currentText.end=document.GetVal.end.value=this.endPlaceName;
      if(typeof(routeEndsObj)!='undefined') routeEndsObj.remove.apply(routeEndsObj,['end']);
    }  
  }
}

ioArea.prototype.checkDefaults=function () {
  var startValue = trim(document.GetVal.start.value);
  var endValue = trim(document.GetVal.end.value);
  if (this.mode == 'LOCATE' && 
    startValue.match(new RegExp("^"+this.locationName+"$"))) {
    this.displayMessage("Please select a location to search");
    return false;
  }
  if (this.mode == 'ROUTE' && 
     (startValue.match(new RegExp("^"+this.startPlaceName+"$")) || 
      endValue.match(new RegExp("^"+this.endPlaceName+"$")))) {
    this.displayMessage("Please select a start and end place to begin");
    return false;
  }
  return true;
}  

ioArea.prototype.clearSuggestDiv =function (whichDiv) {
  whichDiv.innerHTML='';
  whichDiv.style.visibility='hidden';
}

ioArea.prototype.getBusRoute = function(busId) {
  ioAreaObj.displayMessage(ioAreaObj.loadingDivMessage);
  ioAreaObj.changeBackOpacity(0.2);
  if(ioAreaObj.embed) shrinkMap();
  var data={action:"getBusRoute",
    busId: busId,
    account:vidteq.account,key:vidteq.key};
  if(vidteq.scriptBased) {data.callbackFunction='ioAreaObj.handleGetRoute';}
  this.link='';
  this.globalAjaxObj=$.ajax({
      	url:magicHappensUrl,
      	data:data,
      	dataType:vidteq.dataType,
      success:ioAreaObj.handleGetRoute,
      error:ioAreaObj.handleError
      }); 
}

ioArea.prototype.goVid = function (start,end) {
  if(!this.checkDefaults()) return false;
  userDetailsPopup();
  this.captureStartAndEnd();
  ioAreaObj.displayMessage(ioAreaObj.loadingDivMessage);
  ioAreaObj.changeBackOpacity(0.2);
  if(ioAreaObj.embed) shrinkMap();
  if (ioAreaObj.embed && ioAreaObj.embed.fix && ioAreaObj.embed.fix != '' &&
      (routeEndsObj.isNotEmpty(ioAreaObj.embed.fix) && routeEndsObj[ioAreaObj.embed.fix].parentType=='locateStores')) {
    ioAreaObj.prepareCenterEntity(ioAreaObj.embed.place)
    routeEndsObj.remove(ioAreaObj.embed.fix,true);
    routeEndsObj.addByIndex(ioAreaObj.embed.fix,1,'center');
    ioAreaObj.showFixedEnd();
  }
  this.preReqStart = document.GetVal.start.value;
  if ((this.startStr = routeEndsObj.get.apply(routeEndsObj,['start'])) == null) {
    this.startStr=this.preReqStart
    this.startStr=this.startStr.replace(/^\s+/,"");
    this.startStr=this.startStr.replace(/\s+$/,"");
    this.startEntity = {address : {name : this.preReqStart}};
  } else this.startEntity = routeEndsObj['start']; 
  if (!this.startEntity.type || this.startEntity.type != 'center') {
    //this.startEntity.icon = startIcon;
    this.startEntity.icon = mboxObj.startIcon;
    this.startEntity.index = -1;
    this.startEntity.type = 'rcm';
    routeEndsObj.remove('start');
  }
  if (this.mode == 'LOCATE') {
    var data={action:"businessSearch",place:this.startStr,account:vidteq.account,key:vidteq.key};
    if(vidteq.scriptBased) {
      data.callbackFunction='ioAreaObj.handleLocateCall';
    }
    if (typeof(qSrfResponse) != 'undefined') {
      ioAreaObj.handleLocateCall(qSrfResponse);
      delete qSrfResponse;
    } else {
      this.globalAjaxObj=$.ajax({
            	url:magicHappensUrl,
            	data:data,
                    suggestedplace:this.suggestedPlace,
            	dataType:vidteq.dataType,
            success:ioAreaObj.handleLocateCall,
            error:function(response) {ioAreaObj.handleError.apply(ioAreaObj,[response]);}}); 
    }
  } else { // if (mode == 'route') is default
    this.preReqEnd = document.GetVal.end.value;
    if ((this.endStr = routeEndsObj.get.apply(routeEndsObj,['end'])) == null) {
      this.endStr = this.preReqEnd
      this.endStr=this.endStr.replace(/^\s+/,"");
      this.endStr=this.endStr.replace(/\s+$/,"");
      this.endEntity = {address : {name : this.preReqEnd}};
    } else this.endEntity = routeEndsObj['end']; 
    if (!this.endEntity.type || this.endEntity.type != 'center') {
      this.endEntity.index = -1;
      this.endEntity.type = 'rcm';
      //this.endEntity.icon = endIcon;
      this.endEntity.icon = mboxObj.endIcon;
      routeEndsObj.remove('end');
    }
      data={
      action:"viaRoute",
      startaddress:this.startStr,
      endaddress:this.endStr,
      account:vidteq.account,
      key:vidteq.key,
      searchStartString:this.preReqStart,
      searchEndString:this.preReqEnd
           };
  if(ioAreaObj.embed) {
      data.mygid=accountDetails.mygid;
      if(accountDetails.config.sortby) data.sortby=accountDetails.config.sortby;
  }
  var viaString
  if ((viaString = mboxObj.getViaString()) != null) {data.via = viaString;}
  if(vidteq.scriptBased) {data.callbackFunction='ioAreaObj.handleGetRoute';}
    this.link=encodeURI("?q=route&start="+this.startStr+"&end="+this.endStr);  
    this.globalAjaxObj=$.ajax({
		url:magicHappensUrl,
		data:data,
		dataType:vidteq.dataType,
        success:ioAreaObj.handleGetRoute,
        error:ioAreaObj.handleError
        }); 
  }
  return 0;
}

ioArea.prototype.handleLocateCall = function (response) {
  ioAreaObj.handleLocate.apply(ioAreaObj,[response]);
}

ioArea.prototype.placeViaRequest = function () {
  var data={
    action:"viaRoute",
    //startaddress:routeEndsObj.start.lonlat.lon+' '+routeEndsObj.start.lonlat.lat,
    //endaddress:routeEndsObj.end.lonlat.lon+' '+routeEndsObj.end.lonlat.lat,
    startaddress:routeEndsObj.get('start'),
    endaddress:routeEndsObj.get('end'),
    account:vidteq.account,
    key:vidteq.key
  };
  var viaString;
  if ((viaString = mboxObj.getViaString()) != null) {data.via = viaString;}
  if(vidteq.scriptBased) {data.callbackFunction='ioAreaObj.handleGetRoute';} 
  this.globalAjaxObj=$.ajax({
    url:magicHappensUrl,
    data:data,
    dataType:vidteq.dataType,
    success:ioAreaObj.handleGetRoute,
    error:ioAreaObj.handleError
  });
}

ioArea.prototype.handleError = function(reqObj,textStatus,errorThrown) {
  clearRouteAndSrf();
  ioAreaObj.changeBackOpacity(1);
  ioAreaObj.displayMessage ("Something wrong happened, please try again ");
}

ioArea.prototype.handleLocate = function (srfResponse,type) {
  try {
    pageTracker._trackPageview("/locate_"+vidteq.account);
  } catch(err) {};
  //if(type==undefined) type={'name':'','source':''};
  clearRouteAndSrf();
  ioAreaObj.changeBackOpacity(1);
  if(typeof(srfResponse)!='object') srfResponse=JSON.parse(srfResponse);
  if (typeof(srfResponse.error) != 'undefined') {
    ioAreaObj.displayMessage("Could not locate the place. Try again later ("+srfResponse.error+")");
    return false;
  }
  ioAreaObj.reviseSrf(srfResponse);
  //if (isObjectEmpty(srfResponse[0])) srfResponse = [];  
  //reviseSrfWithParentTypeAndIndex(srfResponse);
  ioAreaObj.response = srfResponse;  // context clarify
  if(ioAreaObj.embed && ioAreaObj.embed.locateStores &&
     srfResponse.responseType!='locateStores') {
    // special requests of locateStores
    ioAreaObj.showHelpMessage("Please select one of the addresses");
    if (srfResponse.srf[0].length == 1) {
      //special case in store locator where result is unique
      ioAreaObj.srfResponse = srfResponse;
      ioAreaObj.locateNearByStoresByIndex(0,'start'); 
      return;
    }
  }
  //if(srfResponse.responseType!='locateStores' && ioAreaObj.embed && ioAreaObj.embed.locateStores) 
  //  ioAreaObj.showHelpMessage("Please select one of the addresses");
  //ioAreaObj.response = srfResponse;  // context clarify
  //if(ioAreaObj.embed && ioAreaObj.embed.locateStores &&
  //  srfResponse.responseType!='locateStores' && srfResponse.srf[0].length == 1) {
  //  //special case in store locator where result is unique
  //  ioAreaObj.srfResponse = srfResponse;
  //  ioAreaObj.locateNearByStoresByIndex(0,'start'); 
  //  return;
  //}
  //if(ioAreaObj.embed && ioAreaObj.embed.locateStores &&
  //   type.name!='locateStores' && srfResponse.length == 1) {
  //  //special case in store locator where result is unique
  //  ioAreaObj.srfResponse = reviseSrfToNewOne(srfResponse,'location');
  //  ioAreaObj.locateNearByStoresByIndex(0,'start'); 
  //  return;
  //}
  ioAreaObj.toggleButtons({'clearroutetab' : true});
  //if(isMapXpanded) { undoExpandMapPopVideo(); }  
  ioAreaObj.displayMessage("");
  document.title="Vidteq - Navigation made easy | Search results for "+ ioAreaObj.startStr;
  //var pass=type.name!=''?type.name:'location';
  //ioAreaObj.displayResults.apply(ioAreaObj,[pass,srfResponse]);
  ioAreaObj.showSrf.apply(ioAreaObj,[srfResponse,'location']);
  return 0;
}

ioArea.prototype.prepareCenterEntity= function (entity,startOrEnd) {
  entity.type='center';
  delete entity.distance;
  if(typeof(startOrEnd)!='undefined') {
    ioAreaObj.embed.fix=startOrEnd;
    ioAreaObj.embed.other=(startOrEnd=='start')?'end':'start';
  }
  populateIconContent(entity);
  if(!entity.lonlat) entity.lonlat=lonLatObjFrmPoint(entity.geom);        	  
  if(!entity.popup) entity.popup={open:1};
  return entity;
}

ioArea.prototype.locateNearByStoresByIndex =function (entityIndex,sORe) {
  var entity;
  var tempGeom;
  if(entityIndex==-1) {
    ioAreaObj.dirFromTo('start',-1,mboxObj.rcmLonlat,true);
    tempGeom = "POINT("+mboxObj.rcmLonlat.lon+" "+mboxObj.rcmLonlat.lat+")";
    tempGeom=(tempGeom.replace(/\s+/,"+"));
  } else {
    //entity=ioAreaObj.response[entityIndex];
    entity=ioAreaObj.srfResponse.srf[0].results[entityIndex];
    ioAreaObj.dirFromTo('start',entityIndex,entity.parentType,true);
    routeEndsObj.detach('start');
    tempGeom=(entity.geom.replace(/\s+/,"+"));
  }
  ioAreaObj.embed.locateStores.myLocStr = 'your location';
  ioAreaObj.locateNearByStores(tempGeom);
  routeEndsObj.refresh('start');
}

ioArea.prototype.dirFromTo = function (which,entityIndex,entityParentType,noAutoGoVid) {
  var notWhich=(which=='start')?'end':'start';
  if(entityParentType=='locateStores' && ioAreaObj.mode=='ROUTE') {
    if(routeEndsObj.isNotEmpty(notWhich) && routeEndsObj[notWhich].parentType=='locateStores') { 
      ioAreaObj.swapRoute();
    } else if(routeEndsObj.isNotEmpty(which) &&routeEndsObj[which].parentType!='locateStores' ) {
      ioAreaObj.swapRoute();
    }	 
  }
  routeEndsObj.replace.apply(routeEndsObj,[which,entityIndex,entityParentType]);	
  if(entityParentType=='locateStores') {
    ioAreaObj.embed.place=routeEndsObj[which];
    ioAreaObj.embed.fix=which;
    ioAreaObj.embed.other=notWhich;
    ioAreaObj.showFixedEnd();
    if(typeof(noAutoGoVid) == 'undefined' || !noAutoGoVid ) {
      if (routeEndsObj.isNotEmpty(which) &&  
          routeEndsObj.isNotEmpty(notWhich) && 
          routeEndsObj[which].parentType!=routeEndsObj[notWhich].parentType)
          ioAreaObj.goVid();
    }
  }
  return 0;
}

ioArea.prototype.locateNearByBiz = function (geom, noCenter) {
  //var categoryNameIds = ioAreaObj.embed.blocate.allowedCategoryList.split(","); 
  var categoryNameIds = ioAreaObj.embed.blocate.allowedCategoryList;
  if(ioAreaObj.embed.blocate) {
    $('#bizdisplay')[0].style.display='block';
    $('#locality')[0].style.display='block';
    if(ioAreaObj.embed.hosting) shrinkMap(); 
    fvtObj.writeCategory(categoryNameIds); 
  }
  var toSearch = {categoryList:document.getElementById('bizCatDropDown').options[0].id};
  if(ioAreaObj.embed.firstTimeRule)  {
    //FirstTime Rule is not supposed to contain the CATEGORY LIST anymore.
    //toSearch = ioAreaObj.embed.firstTimeRule;
  }
  var id=toSearch.categoryList.replace(/\s+/g,"_");
  
  id=id.toString();
  document.getElementById(id).selected=true;
  var a={}
  a.categoryList = document.getElementById('bizCatDropDown').options[document.getElementById('bizCatDropDown').selectedIndex].value;
  
  ioAreaObj.invokeBizSearch(geom,a);
  fvtObj.showLorR('L');
}

ioArea.prototype.invokeBizSearch = function(inGeom,inSearch) {
  var geom = inGeom;
  if (typeof(inGeom) == 'undefined' || inGeom == null) geom = ioAreaObj.embed.place.lonlat;
  var toSearch = inSearch;
  if (!toSearch.categoryList) toSearch.categoryList = document.getElementById('bizCatDropDown').options[0].value;
  if (!toSearch.distanceLimit) toSearch.distanceLimit = ioAreaObj.embed.blocate.allowedDistanceLimit;
  if (!toSearch.itemLimit) toSearch.itemLimit = ioAreaObj.embed.blocate.allowedItemLimit;
  var data2Send={"action":"businessLocate",
                 "account":vidteq.account,"key":vidteq.key,
                 "center":ioAreaObj.embed.place.lonlat.lon+","+ioAreaObj.embed.place.lonlat.lat,
                 "category":toSearch.categoryList,
                 "distance":toSearch.distanceLimit,"limit":toSearch.itemLimit
                };
  if(ioAreaObj.embed) {
      data2Send.mygid=accountDetails.mygid;
      if(accountDetails.config.sortby) data2Send.sortby=accountDetails.config.sortby;
   }
  $.ajax({
    url:magicHappensUrl,
    data:data2Send,
    dataType:'text/plain',
    success:function (response) {
      ioAreaObj.handleLocate.apply(ioAreaObj,[response,{name:'blocate'}]);
      if(ioAreaObj.embed.place.popup.open==1) mboxObj.popoutCenterPlace();
      ioAreaObj.toggleButtons({locality:false});  
    }
  });
}

ioArea.prototype.handleLocateStores = function (jsonResponse) {
  //try {
  //  pageTracker._trackPageview("/locate_"+vidteq.account);
  //} catch(err) {};
  // will be counted in handleLocate
  shrinkMap();
  ioAreaObj.changeBackOpacity(1);
  if(typeof jsonResponse=='string') jsonResponse=JSON.parse(jsonResponse);
  if(jsonResponse.error) { 
    ioAreaObj.displayMessage(jsonResponse.error); 
    return false; 
  }

  ioAreaObj.showHelpMessage('Enter your address to find a Store nearby');
  // TBD check why is it needed
  //if(typeof(ioAreaObj.embed.locateStores.results)=='undefined') {
  //  ioAreaObj.embed.locateStores.results=jsonResponse.results;
  //  ioAreaObj.embed.locateStores.type=jsonResponse.type;	
  //}
  //if(typeof(ioAreaObj.embed.locateStores.results)=='undefined') {
  //  ioAreaObj.embed.locateStores.results=jsonResponse.srf[0].results;
  //  ioAreaObj.embed.locateStores.type=jsonResponse.srf[0].srfType;	
  //}
  if(typeof(ioAreaObj.embed.locateStores.seedSrf)=='undefined') {
    ioAreaObj.embed.locateStores.seedSrf = jsonResponse;
  }
  //ioAreaObj.handleLocate(JSON.stringify(jsonResponse.results),jsonResponse.type);
  // TBD
  ioAreaObj.handleLocate(JSON.stringify(jsonResponse));
  if(ioAreaObj.mode=='ROUTE') ioAreaObj.dirFromTo('end',0,'locateStores',true);
}

ioArea.prototype.locateNearByStores = function (geom, noCenter) {
  ioAreaObj.embed.fix=ioAreaObj.embed.other='';
  ioAreaObj.changeBackOpacity(0.2);
  var data={
    action:"locateStores",
    storeid:ioAreaObj.embed.locateStores.storeId,
    //geom:(typeof(geom)!='undefined')?geom:"POINT("+globalLon+" "+globalLat+")",
    geom:geom,
    limit:(typeof(ioAreaObj.embed.locateStores.limit)!='undefined')?ioAreaObj.embed.locateStores.limit:'',
    account:vidteq.account,
    key:vidteq.key
  };
  if(vidteq.scriptBased) data.callbackFunction='ioAreaObj.handleLocateStoresCall';    
  //if(typeof(ioAreaObj.embed.locateStores.type)=='undefined' || typeof(geom)!='undefined' ) {
  if(typeof(ioAreaObj.embed.locateStores.seedSrf)=='undefined' || typeof(geom)!='undefined' ) {
    if(typeof(geom)!='undefined') geom=geom.replace(/\+/," ");
    ioAreaObj.globalAjaxObj=$.ajax({
      url:magicHappensUrl,
      dataType:vidteq.dataType,
      data:data,
      success:ioAreaObj.handleLocateStoresCall,
      error:function(response) {ioAreaObj.handleError.apply(ioAreaObj,[response]);}
    });
  } else {
    ioAreaObj.selectMode('LOCATE');
    ioAreaObj.searchComplete=true;
    $('#starttextbox')[0].value=ioAreaObj.locationName;
    $('#endtextbox')[0].value=ioAreaObj.endPlaceName;
    ioAreaObj.enableField({a:'starttextbox',b:'endtextbox'});
    ioAreaObj.showHelpMessage('Enter your address to find a store nearby');
    //ioAreaObj.handleLocate(JSON.stringify(ioAreaObj.embed.locateStores.results),{'name':'locateStores','source':'virtual'});
    ioAreaObj.handleLocate(JSON.stringify(ioAreaObj.embed.locateStores.seedSrf));
  }
}

ioArea.prototype.handleLocateStoresCall = function (response) {
  ioAreaObj.searchComplete=true;	
  ioAreaObj.handleLocateStores.apply(ioAreaObj,[response]);
}

ioArea.prototype.showSrf = function(srfResponse,which) {
  mboxObj.clearAll.apply(mboxObj,[]);
  this.srfResponse = srfResponse;
  // TBD which use - this function may be called from fvt objects
  fvtObj.prepareForShowSrf.apply(fvtObj,[this.srfResponse]);
  this.writeSrfToTable();
  this.toggleButtons({'clearroutetab' : true});
}

//ioArea.prototype.displayResults = function(which,srfResponse) {
//  mboxObj.clearAll.apply(mboxObj,[]);
//  this.srfResponse = reviseSrfToNewOne(srfResponse,which);
//  reviseStartEndInSrfResponse(this.srfResponse);
//  fvtObj.writeSrfNew.apply(fvtObj,[this.srfResponse]);
//  this.toggleButtons({'clearroutetab' : true});
//}

ioArea.prototype.writeSrfToTable = function() {
  mboxObj.cleanSrf();
  var from = 0;
  for (var i in this.srfResponse.srf) {
    from = populateMarkers(this.srfResponse.srf[i],from);
    fvtObj.writeSrfToTable(this.srfResponse.srf[i]);
    mboxObj.writeSrfToTable(this.srfResponse.srf[i]);
  } 
}

ioArea.prototype.attachLandmarkRoutes = function () {
    var opt="<select id='lr_select' class='landmarkroutes'><option>Route From..</option>";
    $('#newsticker').html('<img src='+imagePathsObj.newSticker+' />');
    for(var i in accountDetails.landmarkRoutes) {
        opt+='<option>'; //+ ioAreaObj.embed.place.address.name;
        opt+=accountDetails.landmarkRoutes[i].address.name;
        opt+='</option>';
    }
    $('#landmarkroutes').html(opt+"</select>");
    $('#lr_select')[0].onchange=function () {
    var index=$('#lr_select')[0].selectedIndex-1;
    if(index==-1) return;
    var strRep=JSON.stringify(accountDetails.landmarkRoutes[index]);
    strRep = "{\""+ioAreaObj.embed.other+"\":"+strRep+"}";
    document.location.href=prepareFtrLink(strRep);
    };
    return;
}

// this function need to be context independent as it is called by ajax
ioArea.prototype.handleGetRoute = function(routeResponse) {
  try {
    pageTracker._trackPageview("/route_"+vidteq.account);
  } catch(err) {};
  clearRouteAndSrf();
  ioAreaObj.displayMessage("");
  if(typeof(routeResponse)==String) routeResponse=JSON.parse(routeResponse);
  if (typeof(routeResponse.error) != 'undefined') {
    ioAreaObj.changeBackOpacity(1);  
    alert("Path not routable - "+routeResponse.error);
    ioAreaObj.displayMessage(routeResponse.error);
    return false;
  }	 	
  ioAreaObj.response = routeResponse;
  ioAreaObj.toggleButtons({'clearroutetab' : true});
  var jobList = {
    mm: {divContent:"We found multiple matches for <b>start</b> and <b>end</b> places you entered",
         sOrE:"startAddress"},
    sm: {divContent:"We found multiple matches for <b>end</b> place you entered",
          sOrE:"endAddress"},
    ms: {divContent:"We found multiple matches for <b>start</b> place you entered",
          sOrE:"startAddress"},
    fm: {divContent:"No match for <b>start</b> place and multiple matches for <b>end</b> place you entered",
          sOrE:"endAddress"},
    mf: {divContent:"No match for <b>end</b> place and multiple matches for <b>start</b> place you entered",
          sOrE:"startAddress"},
    fs: {divContent:"No match for <b>start</b> and one match for <b>end</b> place you entered",
          sOrE:"endAddress"},
    sf: {divContent:"No match for <b>end</b> place and one match for <b>start</b> place you entered",
          sOrE:"startAddress"},
    ff: {divContent:"We found no matches for <b>start</b> and <b>end</b> places you entered",
          sOrE:"startAddress"}
  };
  ioAreaObj.changeBackOpacity(1);
  //if (typeof(routeResponse.routeFailType) == 'undefined') {
  if (typeof(routeResponse.vid) != 'undefined') {
    
     ioAreaObj.displayRoute.apply(ioAreaObj,[routeResponse]);
  } else {
    // Following seciton is TBD
    //if(response.startAddress.length>0) {
    //  routeEndsObj.add('start',0,'startAddress');
    //  if(typeof(response.startAddress[0].name)!='undefined') { // TBD variants  
    //    document.GetVal.start.value=response.startAddress[0].name;
    //  }
    //}
    //if(response.endAddress.length>0) {
    //  routeEndsObj.add('end',0,'endAddress');
    //  if(typeof(response.endAddress[0].name)!='undefined') { // TBD variants  
    //    document.GetVal.end.value=response.endAddress[0].name;
    //  }
    //}
    //ioAreaObj.displayMessage(jobList[routeResponse.routeFailType].divContent);
    //var sOrE = jobList[routeResponse.routeFailType].sOrE;
    //reviseSrfWithParentTypeAndIndex(routeResponse);
    //ioAreaObj.displayResults.apply(ioAreaObj,[sOrE,routeResponse]);
    ioAreaObj.displayMessage(jobList[routeResponse.responseType].divContent);
    var sOrE = jobList[routeResponse.responseType].sOrE;
    ioAreaObj.reviseSrf(routeResponse);
    ioAreaObj.showSrf.apply(ioAreaObj,[routeResponse,sOrE]);
    if ( routeResponse.responseType == 'sf' ||
         routeResponse.responseType == 'sm' ||
         routeResponse.responseType == 'ss' ) {
      var entity = routeResponse.srf[0].results[0];
      if (entity.type != 'center') this.dirFromTo('start',entity.index,entity.parentType);
    }
    if ( routeResponse.responseType == 'fs' ||
         routeResponse.responseType == 'ms' ||
         routeResponse.responseType == 'ss' ) {
      var entity = routeResponse.srf[1].results[0];
      if (entity.type != 'center') this.dirFromTo('end',entity.index,entity.parentType);
    }
  }
}

function alertswf(str){
  //alert(str);
}

ioArea.prototype.displayRoute = function(routeResponse) {
  routeResponse.highBwUrl = videoUrl;
 
   routeResponse.lowBwUrl = (typeof(videoUrlLb) != 'undefined')?videoUrlLb:'';
  reviseStartEndInResponse(routeResponse);
  reviseImageInResponse(routeResponse);
  reviseVideoInResponse(routeResponse);
  reviseCaptionInResponse(routeResponse);
  ioAreaObj.toggleButtons({'smstab' : true,
                           'emailtab' : true,
                           'mapexpand' : true,
                           'mapexpand' : true,
                           'printtab' : true,
                           'clearroutetab' : true,
                           'downloadtab' : true});
  mboxObj.displayRoute.apply(mboxObj,[routeResponse]);
  fvtObj.displayRoute.apply(fvtObj,[routeResponse]);
  this.displayMessage(this.prepareRouteSummary(routeResponse.summary));
}

ioArea.prototype.prepareRouteSummary = function(summary) {
  var tempSplit=summary.split("|");
  var summaryHTML="Total Distance = <b>"+tempSplit[0]+" Kms</b>&nbsp&nbsp&nbsp&nbsp&nbsp;Travel Time ~ <b>"+tempSplit[1]+"</b>";
  return summaryHTML;
}

ioArea.prototype.fillIoForm = function(which,what) {
  this.inputMapOrText='TEXT';
  this.selectMode('ROUTE');
  var whatBetter = what.toString();
  whatBetter = whatBetter.replace(/^\s+/,"");
  whatBetter = whatBetter.replace(/\s+$/,"");
  if(which=='start'){
    document.GetVal.start.value=whatBetter;
    document.GetVal.start.style.backgroundColor=mainColor;
    document.GetVal.start.style.color='white';
    setTimeout("document.GetVal.start.style.backgroundColor='white'",2000);
    setTimeout("document.GetVal.start.style.color='black'",2000);
  } else if(which=='end'){
    document.GetVal.end.value=whatBetter;
    document.GetVal.end.style.backgroundColor=mainColor;
    document.GetVal.end.style.color='white';
    setTimeout("document.GetVal.end.style.backgroundColor='white'",2000);
    setTimeout("document.GetVal.end.style.color='black'",2000);
  }
}

ioArea.prototype.showFixedEnd = function () {
  if(!this.embed) return;
  if(this.embed.fix=='start') {
    this.alterDisabledField({'starttextbox':'disabled',
                             'endtextbox':''});
  } else if(this.embed.fix=='end') {
    this.alterDisabledField({'starttextbox':'',
                             'endtextbox':'disabled'});
  }
  if(this.embed.place.popup && this.embed.place.popup.open==1) mboxObj.popoutCenterPlace(); 
}

ioArea.prototype.alterDisabledField = function(which) {
  for(dom in which) $('#'+dom)[0].disabled=which[dom];
}

ioArea.prototype.disableField = function (which)  {
	for(prop in which)
	$('#'+which[prop])[0].disabled='disabled';
}

ioArea.prototype.enableField = function (which)  {
	for(prop in which)
	$('#'+which[prop])[0].disabled='';
}

ioArea.prototype.toggleButtons = function(buttonValuePairs) {
  var onClickFunctions = { 
    'mapexpand' : function () {changeLayout();return false;},
    'clearroutetab' : function () {clearAll();return false;},
    'smstab' : function () { 
      ioAreaObj.popup=(new PopUpWindow(2));
      ioAreaObj.popup.showContents(ioAreaObj.prepareSMS(ioAreaObj.response)); 
    },
    'emailtab' : function () { 
      ioAreaObj.popup=(new PopUpWindow(2));
      ioAreaObj.popup.showContents(ioAreaObj.prepareEmail(ioAreaObj.response)); 
    },
    'minvideo' : clearVideoTd,
    'downloadtab' : function () { 
      ioAreaObj.popup=(new PopUpWindow(2));
      ioAreaObj.popup.showContents(ioAreaObj.prepareDownload()); 
    },
    'printtab' : function () { 
      ioAreaObj.popup=(new PopUpWindow(2));
      ioAreaObj.popup.showContents(ioAreaObj.preparePrintOptions()); 
    },
    'localinkhref' : function () { 
      ioAreaObj.popup=(new PopUpWindow(2));
      ioAreaObj.popup.showContents(ioAreaObj.prepareLink()); 
     },
     'locality' : function () {ioAreaObj.locateNearByBiz();},
     'stores' : function () { 
       routeEndsObj.remove.apply(routeEndsObj,['start',true]);	
       routeEndsObj.remove.apply(routeEndsObj,['end',true]);	
       ioAreaObj.embed.locateStores.myLocStr = 'center of city';
       ioAreaObj.locateNearByStores('POINT('+globalLon+' '+globalLat+')',true);
       //ioAreaObj.locateNearByStores();
     }    
  };
  var onTitles = {
    'mapexpand' : 'Expand the Map and float the video',
    'clearroutetab' : 'Clear the Map',
    'smstab' : 'Send text directions as SMS',
    'emailtab' : 'Email the current  route with/without images',
    'minvideo' : 'Hide the Video container',
    'downloadtab' : 'Download the complete route',
    'printtab' : 'Print the text directions for complete route',
    'localinkhref' : 'Link to this search/route',
    'locality' : 'Show businesses around '+((typeof(ioAreaObj.embed)!='undefined' && typeof(ioAreaObj.embed.place)!='undefined')?ioAreaObj.embed.place.address.name:''),
    'stores' : 'Show all stores around Center of Bangalore'
  };
  var offTitles = {
    'mapexpand' : 'This is not available for a empty route',
    'clearroutetab' : 'Map is already cleared',
    'smstab' : 'Select a route to enable this feature',
    'emailtab' : 'Select a route to enable this feature',
    'minvideo' : 'Select a route to enable this feature',
    'downloadtab' : 'Select a route to enable this feature',
    'printtab' : 'Select a route to enable this feature',
    'stores' : 'Already in Stores mode',
    'locality' : 'Already in Locality mode'
  };
  var imageSrcEnabled = {
    'locality' : imagePathsObj.localityEnabled,
    'stores' : imagePathsObj.storesEnabled
  }   
  var imageSrcDisabled = {
    'locality' : imagePathsObj.localityDisabled,
    'stores' : imagePathsObj.storesDisabled
  }
  var displayOnOff = {
    'minvideo' : 'yes',
    'stores':'yes'
  }	     
  for (i in buttonValuePairs) {
    if(document.getElementById(i)==null ) continue;
    if (buttonValuePairs[i] && document.getElementById(i)) {
      document.getElementById(i).className="maptab";
      if(imageSrcEnabled[i]) document.getElementById(i).src=imageSrcEnabled[i];
      if(displayOnOff[i]) document.getElementById(i).style.display='block';
      document.getElementById(i).onclick=onClickFunctions[i];
      document.getElementById(i).title=onTitles[i];
      if(i=='locality') ioAreaObj.customHelpTextBelowButton(onTitles[i]);
    } else {
      document.getElementById(i).className="maptabdisabled";
      if(imageSrcDisabled[i]) document.getElementById(i).src=imageSrcDisabled[i];
      if(displayOnOff[i]) document.getElementById(i).style.display='none';
      if(i=='locality') {
			if(ioAreaObj.textFlashInterval) {
				clearInterval(ioAreaObj.textFlashInterval);
				$('#localityhelpmesg').html('');
			}
	  }
      document.getElementById(i).onclick='';
      document.getElementById(i).title=offTitles[i];
    }
  }
}

ioArea.prototype.customHelpTextBelowButton = function(title) {
	$('#localityhelpmesg').html('Click to explore surroundings');
	ioAreaObj.textFlashInterval=setInterval(function () {ioAreaObj.colorChanger('localityhelpmesg');},2000);
}

ioArea.prototype.colorChanger = function (id) {
	var color=($('#'+id)[0].style.color)=='black'?'white':'black';
	$('#'+id)[0].style.color=color;
}

ioArea.prototype.loadMapStandAlone=function(latlon,srfResponse) {
    mboxObj = new mbox('map','map_OpenLayers_ViewPort','javascript:ioAreaObj.invokeTheMode.apply(ioAreaObj,[])');
    routeEndsObj = new routeEnds();
    document.getElementById('GoVid').onclick=function () {ioAreaObj.invokeTheMode.apply(ioAreaObj,[]);return false;};
    if(!latlon) ioAreaObj.invokeTheMode.apply(ioAreaObj,[]);
    else {fvtObj.showLorR('L');ioAreaObj.showSrf(srfResponse,'location');}
    //else {fvtObj.showLorR('L');ioAreaObj.displayResults('location',srfResponse);}
}

ioArea.prototype.loadSync=function (mode) {
  this.loadSyncCalled=true;
  fvtObj = new fvt();
  fvtObj.clearFvtContent=vidteq.clearFvtContent;
  vidteq.clearFvtContent='';
  if(!this.checkDefaults()) return false;
  $('#rightcolumn')[0].style.backgroundImage='';
  if (typeof(mode) == 'undefined' || mode != 'q') {
    if($('#routedetails_primitive')[0]) $('#routedetails_primitive')[0].innerHTML='';
    //createLoadingDiv ();
    ioAreaObj.displayMessage(ioAreaObj.loadingDivMessage);
    ioAreaObj.changeBackOpacity(0.2);
    var syncPageUrl=(ioAreaObj.newUi)?"vc/base_newui.php":"vc/base.php";
    var data=(this.mode=='LOCATE')?{q:"locate"}:{q:"route"};
    showSyncPage=function (response) {
      var syncDiv=$('#dynamicDiv')[0];
      syncDiv.innerHTML=response;
      page2Process();
      ioAreaObj.toggleButtons({'localinkhref':true,
                   'clearroutetab' : false,
                   'smstab' : false,
                   'printtab' : false,
                   'emailtab' : false,
                   'downloadtab' : false});
      if(ioAreaObj.openLayersLoaded) {
        ioAreaObj.loadMapStandAlone.call(ioAreaObj);
      }
    }
    $.ajax({url:syncPageUrl, type: 'GET', data:data, dataType:"html",
      success:showSyncPage,
      error:function () {}
      });
  } else {
    page2Process();
    ioAreaObj.toggleButtons({'localinkhref':true,
                 'clearroutetab' : false,
                 'smstab' : false,
                 'printtab' : false,
                 'emailtab' : false,
                 'downloadtab' : false});
    if(ioAreaObj.openLayersLoaded) {
      ioAreaObj.loadMapStandAlone.call(ioAreaObj);
    }
  }
  return 0;
}

ioArea.prototype.invokeTheMode=function () {
  if($('#routedetails_primitive')[0]) $('#routedetails_primitive')[0].innerHTML='';
  ioAreaObj.cancelLocate=false
  ioAreaObj.flink={}
  //if(!this.checkDefaults()) return false;
  if(ioAreaObj.flink) ioAreaObj.flink.ll=0;
  //createLoadingDiv();
  ioAreaObj.displayMessage(ioAreaObj.loadingDivMessage);
  ioAreaObj.changeBackOpacity(0.2);
  //document.getElementById('VideoPlayerDiv').innerHTML='';
  this.clearSuggestDiv($('#sugdivstart')[0]);
  this.clearSuggestDiv($('#sugdivend')[0]);
  document.getElementById('GoVid').focus();
  this.captureStartAndEnd();
  //killQuestionPopup();
  mboxObj.killRcmPopup.apply(mboxObj,[]);
  if(this.mode == 'LOCATE') {
    var c=encodeURI("?q=locate&place="+(this.startAddress));
    this.link=c;
    this.goVid(this.startAddress);
  } else {
    this.toggleButtons({"downloadtab":false});
    allVideoLinks = [];
    mapnDpVideoLinks = [];
    vidDuration = 0;
    vVidDuration = 0;
    fvtObj.showLorR('R');
    this.link=encodeURI("?q=route&start="+this.startAddress+"&end="+this.endAddress);
    this.goVid(this.startAddress,this.endAddress);
  }
  return 0;
}

ioArea.prototype.captureStartAndEnd=function () {
  this.startAddress=document.GetVal.start.value
  this.startAddress=this.startAddress.replace(/^\s+/,"");
  this.startAddress=this.startAddress.replace(/\s+$/,"");
  this.endAddress=document.GetVal.end.value
  this.endAddress=this.endAddress.replace(/^\s+/,"");
  this.endAddress=this.endAddress.replace(/\s+$/,"");
}  

ioArea.prototype.prepareSMS=function (response) {
  var smsHtml="";
  if(response.name) {
      smsHtml+="<p style='font-size:13px;padding:5px;'>"+response.name+"</p>";
      for(i in addressSubsArray) {
      if(response[addressSubsArray[i].field]) smsHtml+="<p style='font-size:13px;padding:5px;'>"+response[addressSubsArray[i].field]+"</p>";
      }
  }
  else {
  smsHtml+="<p style='font-size:14px;padding:5px;'>Start Address - "+response.startAddress+"</p><p style='padding:5px;font-size:14px'>End Address - "+response.endAddress+"</p><p style='font-size:14px'>Total Distance : "+response.routeSummary.distance+" Kms Video Duration : "+response.routeSummary.videoDuration+"</p>";
  for(i in response.vid) {
    smsHtml+="<p style='font-size:13px'>"+(parseInt(i)+1)+". "+response.vid[i].direction+"</p>";
  }
  }
  var headerHtml="Please enter your Mobile Number";
  var lowerHtml="<table align=center width=75% cellspacing=0 cellpadding=0><tr><td><a onfocus='this.blur();' style='font-size:14px'></a></td><td><a onfocus='this.blur();' style='font-size:14px'>+91</a><input type='text' maxlength=10 size=10 style='width:80%;' name='smsbox' onclick='ioAreaObj.clickTextbox(this)' id='mobinput' value='"+this.inputValSMS+"' /></td><td><img src='"+imagePathsObj.sms+"' tabindex=0 style='cursor:pointer' height=25 href='javascript:void(0);' onclick= 'javascript:ioAreaObj.sendSMS.apply(ioAreaObj,[])'/></td></tr></table>";
  return ({headerHtml:headerHtml,innerDivHtml:smsHtml,lowerHtml:lowerHtml});
}  

ioArea.prototype.prepareEmail = function (response,place) {
  var emailHtml;
  if(place!==undefined && place == 1) {
      emailHtml = this.preparePlaceHtml(response);
  }
  else emailHtml=this.prepareRouteDirectionsPreview();
  var headerHtml="Please enter your Email Id <br><a onfocus='this.blur();' style='text-align:center;'>(Multiple Email Ids separated by a comma)</a>";
  var lowerHtml="<table align=center width=75% cellspacing=0 cellpadding=0><tr><td><a onfocus='this.blur();' style='font-size:14px'></a></td><td><input type='text'  style='width:95%;' id='emailinput' name='emailbox' value='"+this.inputValEmail+"' onclick='ioAreaObj.clickTextbox(this)' />&nbsp</td><td><img src='"+imagePathsObj.email+"' tabindex=0 style='cursor:pointer' height=25 href='javascript:void(0);' onclick='javascript:ioAreaObj.sendEmail.apply(ioAreaObj,[])' /></td></tr></table>";
  return ({headerHtml:headerHtml,innerDivHtml:emailHtml,lowerHtml:lowerHtml});
}  

ioArea.prototype.preparePlaceHtml = function (placeObj) {
    var emailHtml="<p style='font-size:18px;padding:5px;'>"+placeObj['name']+"</p><br/>";
    for(i in addressSubsArray) {
      if(placeObj[addressSubsArray[i].field]) emailHtml+="<p style='padding:5px;font-size:13px'>"+placeObj[addressSubsArray[i].field]+"</p>";
    }
    this.email={};
    this.email.files='';
    if(placeObj.lightPullImg) {
        this.email.files+=placeObj.lightPullImg+";";
        emailHtml+='<br/><img src=http://'+document.location.host+placeObj.lightPullImg+' />';
    }
    if(placeObj.image) {
        this.email.files+=placeObj.image;
        emailHtml+='<br/><img src='+cloneImageUrl+placeObj.image+' />';
    }
    emailHtml+='<br/><br/>Please visit ';
    emailHtml+='<a href=http://'+document.location.hostname+'>vidteq.com</a>';
    emailHtml+=' for richer experience';
    return emailHtml;
}

ioArea.prototype.prepareLink = function () {
  var headerHtml="Direct Link";
  var linkString="http://"+document.location.host+document.location.pathname+(decodeURIComponent(this.link)).toString();
  if(ioAreaObj.embed && !ioAreaObj.embed.locateStores)
  linkString=this.link;
  
  var innerHTML="<a style='font-size:12px;color:black;font-family:Terbuchet MS, Arial;' href='"+(linkString).toString()+"' target='_blank' class=click>"+linkString+"</a>";
  return ({headerHtml:headerHtml,innerDivHtml:innerHTML});
}

ioArea.prototype.prepareRouteDirectionsPreview = function (print,noImages) {
  this.email={};   
  var emailHTML="<html><head><style>body{background-color:#FFF;margin-left:10px;}p{ font-size:14px;font-family:'Trebuchet MS', Arial; }h{ font-size:80%;font:Tahoma; } </style></head><body>";
  emailHTML+="<h3>Routing directions between "+this.startAddress+" and "+this.endAddress+"</h3>";
  this.email.files="";
  for(var i=0;i<this.response.vid.length;i++) {
    hostname=document.location.host;
    var classPNG=(MSIE6==true)?"class='pngfixclass'":"''";  
    emailHTML+="<p><img src="+this.response.vid[i].arrowSrc+" "+classPNG+" /> &nbsp;&nbsp;"+(i+1)+". "+this.response.vid[i].direction+"</p>";
    if(typeof(noImages)=='undefined') { // TBD
      for(j=0;j<this.response.vid[i].passBy.length;j++) {
        var curPoi=this.response.imgData[this.response.vid[i].passBy[j].id];
        this.email.files+=curPoi.imgName+";";    
        if(print=='true') {
          emailHTML+="<a class=simple style='text-align:center;padding-left:5px;'>"+curPoi.poiName+"</a><br><div id=imgdivpoi"+j+" style='margin-left:10px;z-index:12000;height:240px;width:320px;'><div style='display:block;' ><img alt='"+curPoi.poiname+"' src="+cloneImageUrl+curPoi.imgName +" /></div><div id='arrowoverlay' style='padding-top:180px;text-align:center'></div></div>";
        } else {
          emailHTML+="<a class=simple style='text-align:center;'>"+curPoi.poiName+"</a><br><div id=imgdivpoi"+j+" style='margin-left:10px;z-index:12000;height:240px;width:320px;background-image:url("+cloneImageUrl+curPoi.imgName+");'><div id='arrowoverlay' style='padding-top:180px;text-align:center'></div></div>";
        }  
      }
    }
  }
  try {
    if(typeof(noImages)=='undefined') {
      emailHTML+="<p id='routeimgsnap'>Loading the image of route .....</p>";
      this.addMapImage(this.prepareLightpullReqObj());
    }
  } catch (e) { }  
  emailHTML+="<p>Have a nice trip. Please do visit us back at www.vidteq.com</p>";
  emailHTML+="</body></head></html>";
  return emailHTML;
}

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

ioArea.prototype.addMapImage = function (mapData) {
  var s=JSON.stringify(mapData);
  var paramsToSend={'w':320,'h':320,'onlyPath':1,'places':s};
  var img=$.ajax({
    url:lightPullUrl,
    type:"POST",
    dataType:'json',
    data:paramsToSend,
    success:function (response) {
      var imgName=response.path;
      var toPut = "<img src=http://"+document.location.host+"/tmp/"+imgName+" />";
      if(imgName && imgName!='undefined') {
        if(ioAreaObj.printWindow && ioAreaObj.printWindow!=null && ioAreaObj.printWindow.document!=null && ioAreaObj.printWindow.document.getElementById('routeimgsnap')) {  
          ioAreaObj.printWindow.document.getElementById('routeimgsnap').innerHTML= toPut;
        }
        if(document.getElementById('routeimgsnap')) {
          document.getElementById('routeimgsnap').innerHTML= toPut;  
        }
      } else { 
        if(ioAreaObj.printWindow && ioAreaObj.printWindow!=null && ioAreaObj.printWindow.document!=null && ioAreaObj.printWindow.document.getElementById('routeimgsnap')) {  
          ioAreaObj.printWindow.document.getElementById('routeimgsnap').innerHTML= "";
        }
        if(document.getElementById('routeimgsnap')) {
          document.getElementById('routeimgsnap').innerHTML= "";  
        }
      }
    },
    error: function () {
      if(document.getElementById('routeimgsnap') || (ioAreaObj.printWindow && ioAreaObj.printWindow.document.getElementById('routeimgsnap'))) {
        document.getElementById('routeimgsnap').innerHTML= "";  
      }
    }
  });
}  

ioArea.prototype.sendSMS= function () {
  /* if(isMapXpanded){
  setTimeout('getBackVideoTd()',4000);
  }*/
  var mobileNumber=$('#mobinput')[0].value;
  mobileNumber.replace(/\s+/g,'');
  if(mobileNumber.length==10 && mobileNumber.match(/^9\d{9}/)) {
    var totalRoute=$('#innerDiv')[0].innerHTML;
    totalRoute=totalRoute.replace(/\<p[^\>]*\>/ig,"")
    totalRoute=totalRoute.replace(/\<\/p\>/ig,"\n")
    var sendSMSAjaxData = {action:"sendSms", to:mobileNumber, text:totalRoute};
    globalAjaxObj=$.ajax({type: 'GET', url: magicHappensUrl,  data: sendSMSAjaxData,  error:function () {return true;}, dataType: vidteq.dataType});
  } else {
    alert("Please check the number you have entered");
    return false;
  }
  this.showSendingPrompt();
}

ioArea.prototype.sendEmail= function () { 
  var emailId=new Array();
  if($('#emailinput')[0].value.match(/\,/))  {
    emailId=$('#emailinput')[0].value.split(/\,/);
  } else {
    emailId[0]=$('#emailinput')[0].value;
  }
  var chiller=0;
  for(var i=0;i<$('#innerDiv')[0].getElementsByTagName('div').length;i++) {
    if(($('#innerDiv')[0].getElementsByTagName('div')[i].id).match(/imgdiv/)) {
      chiller++;
      $('#innerDiv')[0].getElementsByTagName('div')[i].style.backgroundImage='';
      $('#innerDiv')[0].getElementsByTagName('div')[i].innerHTML="<img src='cid:image"+chiller+"@vidteq.com' style='height:240px;width:320px;' \/>";
    }
  }    
  var totalRoute="<html><head><style>p{ font-size:14px;font-family:'Trebuchet MS', Arial; }h{ font-size:100%;font-family:'Trebuchet MS', Arial; }</style></head><body>";
  totalRoute+=$('#innerDiv')[0].innerHTML;
  totalRoute+="</body></html>";
  var fileName=this.email.files;
  for(var i=0;i<emailId.length;i++) {
    if(checkEmailId(emailId[i])==true) {
      emailData = {action:'email', to:emailId[i], content: totalRoute, start:this.startAddress,end:this.endAddress, attach:'yes', filename:fileName};
      globalAjaxObj=$.ajax({type: 'POST', url:emailUrl, data:emailData, dataType: "text"});
    }
  }
  this.showSendingPrompt();
}

ioArea.prototype.showSendingPrompt=function () {
  var a=$('#comdiv')[0];
  a.innerHTML='';
  a.style.width='250px';
  a.style.height='50px';
  var wLeft=(document.body.offsetWidth/2)-100;
  wLeft=wLeft>0?wLeft:0;
  a.style.left=wLeft+"px";
  var wHeight=(document.body.offsetHeight/2)-105;
  wHeight=wHeight>0?wHeight:0;
  a.style.top=wHeight+"px";
  timedComDivClose(3);
  for(i=2;i>0;i--) {
    setTimeout('timedComDivClose('+i+')',(3-i)*1000);
  }
  setTimeout('ioAreaObj.popup.close()',3000);
}

ioArea.prototype.preparePrintOptions = function() {
  var headerHtml="Print Directions";
  var innerHTML="<table align='center'; vertical-align='middle'; width=100% height=100%><tr height=100%; valign='middle;' align='center;'><td><div style='text-align:center'><a class='maptab' style='cursor:pointer' onclick='ioAreaObj.invokePrint(ioAreaObj.prepareRouteDirectionsPreview(true))'>With Images</a><br/>";
  innerHTML+="<a class='maptab' style='cursor:pointer' onclick='ioAreaObj.invokePrint(ioAreaObj.prepareRouteDirectionsPreview(true,true))'>Without Images</a><br/></div></td></tr></table>";
  return ({headerHtml:headerHtml,innerDivHtml:innerHTML});
}

ioArea.prototype.prepareDownload = function() {
  var headerHtml="Download Video";
  var messageDiv = createElem("div"); 
  $('#comdiv')[0].appendChild(messageDiv);
  messageDiv.id = "download";
  var vVidDuration=ioAreaObj.response.vVidDuration;
  var vidDuration=ioAreaObj.response.vidDuration;
  var mainDpDuration = Math.round((vVidDuration / 60) * 100) / 100;
  var allVideoDuration = Math.round(((vidDuration + vVidDuration) / 60) * 100) / 100;
  var innerHtml="<table align='center'; vertical-align='middle'; width=100% height=100%><tr height=100%; valign='middle;' align='center;'><td><div style='text-align:center'>";
  innerHtml+=createDownloadLink("Main decision points only", ioAreaObj.response.mainDpVideoLinks);  
  innerHtml+=" - ~" + mainDpDuration + " minutes (Video Duration)" + " - ~" + (mainDpDuration * 4) + "Mbs (Video Size)";
  innerHtml+="<br/><br/>";
  innerHtml+=createDownloadLink("Complete Video Map", ioAreaObj.response.allVideoLinks);
  innerHtml+=" - ~" + allVideoDuration + " minutes (Video Duration)" + " - ~" + (allVideoDuration * 4) + "Mbs (Video Size)";
  innerHtml+="</div></td></tr></table>";
  function createDownloadLink(text, files) {
    var hrefString='<a href="javascript:void(0)" className="style8" onclick=clickFunc("'+files+'"); >'+text+'</a>';
    var hrefString="<a class='maptab' style='cursor:pointer' onclick=clickFunc(\""+files+"\"); >"+text+"</a><br/>";
    return hrefString;
  }
  return ({headerHtml:headerHtml,innerDivHtml:innerHtml});
}

var clickFunc = function(files) {
  files=files.split(",");
  messageDiv=$('#messageDiv')[0];
  //messageDiv.innerHTML = "<p style='text-align:center;font-size:16px;padding:5px;'>The file you requested for is being prepared.</p>";
  //messageDiv.innerHTML = "<a onfocus='this.blur();' style='font-size:18px;color:black;' class='style8'>The file you requested for is being prepared.</a>";
  messageDiv.innerHTML = "<table align='center'><tr><td><a onfocus='this.blur();' style='font-size:18px;color:black;' class='style8'>The file you requested for is being prepared.</a></td><td><img src='"+imagePathsObj.load+"' /></td><td><a style='cursor:pointer;' class='message'  href='javascript:void(0);' onclick='javascript:ioAreaObj.cancelRequest();return false;'>Cancel</a></td></tr></table>";
  $.post(magicHappensUrl + "?action=download", 
    {action:'download', videoFile : files},
    function foo(data) {
      var doc = getIFrameDocument('downloadIFrame');
      var href = document.location.href;
      var lastIndex = href.lastIndexOf("/");
      href = href.substring(0, lastIndex);
      href = href + "/" + magicHappensUrl + "?action=getFile";
      formObj = attachForm(href, doc.body, doc, "POST")
      attachHiddenInputField(formObj, "start", doc, $("#starttextbox").val());
      attachHiddenInputField(formObj, "end", doc, $("#endtextbox").val());
      attachHiddenInputField(formObj, "fileName", doc, data.fileName);
      attachHiddenInputField(formObj, "action", doc, "getFile");
      formObj.submit();
      //messageDiv.innerHTML = "<p>File download will start now.</p>";
      messageDiv.innerHTML = "<a onfocus='this.blur();' style='font-size:18px;color:black;' class='style8'>File download will start now.</a>";
    },
    'json'
  );
}

ioArea.prototype.invokePrint = function (toPrint) {
  var l=(screen.width-300)/2;
  var t=(screen.height-300)/2;
  ioAreaObj.printWindow=window.open('','','width=300,height=300,left='+l+',top='+t+',scrollbars=yes,resizable=yes');
  ioAreaObj.printWindow.document.open('text/html');
  ioAreaObj.printWindow.document.write("<head><style type='text/css'>a.poi   {font-size:11px;text-decoration:none;color:black;font-family:'Trebuchet MS', Arial;text-align:left;}a.textdir {text-decoration:none;cursor:pointer;font-family:'Trebuchet MS', Arial;font-size:13px;color:black;background-color:white;text-align:left;}p,a,b{font-size:12px;text-decoration:none;color:black;font-family:'Trebuchet MS', Arial;text-align:left;}h3{font-size:14px;text-decoration:none;color:black;font-family:'Trebuchet MS', Arial;text-align:left;}</style><title>Route between "+this.startAddress+" and "+this.endAddress+"</title></head><body><div id='printdom' style='text-align:left'>"+toPrint+"</div></body>");
  var divCount=ioAreaObj.printWindow.document.body.getElementsByTagName("div").length;
  ioAreaObj.printWindow.document.body.getElementsByTagName("div")[divCount-1].onload=ioAreaObj.printWindow.print();
  ioAreaObj.printWindow.document.close();
}  

function insertPlace(place,whichBox) {
  ioAreaObj.suggestedPlace=1;
  place=place.replace(/\-/g," ");
  if(whichBox=='start') {
    document.GetVal.start.value=place;
    ioAreaObj.clearSuggestDiv($('#sugdivstart')[0]);
  } else {
    document.GetVal.end.value=place;
    ioAreaObj.clearSuggestDiv($('#sugdivend')[0]);
  }
}

ioArea.prototype.getRoadName = function(lonlat,startOrEnd) {
  this.getRoadNameStartOrEnd = startOrEnd; // Not a good idea TBD
  this.selectMode('ROUTE');
  if ( startOrEnd == 'start' ) {
    this.currentText.start=document.GetVal.start.value="Your Source";
    document.GetVal.start.style.backgroundImage='url('+imagePathsObj.ajaxLoader+')';
    document.GetVal.start.style.backgroundRepeat='no-repeat';
    document.GetVal.start.style.backgroundPosition='center';
  } else {
    this.currentText.end=document.GetVal.end.value="Your Destination";
    document.GetVal.end.style.backgroundImage='url('+imagePathsObj.ajaxLoader+')';
    document.GetVal.end.style.backgroundRepeat='no-repeat';
    document.GetVal.end.style.backgroundPosition='center';
  }
  var data=(vidteq.scriptBased?{action:"findhood",point: lonlat.lon + ' ' + lonlat.lat,callbackFunction:'ioAreaObj.roadNameSuccessCall'}:{action:"findhood",point: lonlat.lon + ' ' + lonlat.lat})
  this.globalAjaxObj=$.ajax({
	url:magicHappensUrl,
	data:data,
    dataType: vidteq.dataType,
    success:ioAreaObj.roadNameSuccessCall,
    error:ioAreaObj.handleError
  });
}

ioArea.prototype.roadNameSuccessCall = function (response) {
	ioAreaObj.applyGetRoadNameResponse.apply(ioAreaObj,[response]);
}

ioArea.prototype.applyGetRoadNameResponse = function(response) {
  if(typeof(response)=='string') response=JSON.parse(response);
  document.GetVal.start.style.backgroundImage="";
  document.GetVal.end.style.backgroundImage="";
  if (response.error) {
    ioAreaObj.displayMessage(response.error);
    return false;
  }
  //runAll=0; TBD
  //features = []; TBD
  if(this.getRoadNameStartOrEnd =='start') {  // not accessible TBD 
    this.startAddress=this.gStart=this.currentText.start=document.GetVal.start.value= (!response.roadname)?'Your Start':response.roadname;
    if (routeEndsObj['start'].address && 
        routeEndsObj['start'].address.name) 
      routeEndsObj['start'].address.name = this.startAddress;
    if (this.startEntity &&
        this.startEntity.address && this.startEntity.address.name)
      this.startEntity.address.name = this.startAddress;
  } else if(this.getRoadNameStartOrEnd =='end') {
    this.endAddress=this.gEnd=this.currentText.end=document.GetVal.end.value= (!response.roadname)?'Your End':response.roadname;
    if (routeEndsObj['end'].address &&
        routeEndsObj['end'].address.name) {
      routeEndsObj['end'].address.name = this.endAddress;
    }
    if (this.endEntity &&
        this.endEntity.address && this.endEntity.address.name) {
      this.endEntity.address.name = this.endAddress;
    }
   }
   /*if(ioAreaObj.embed) {
      if(ioAreaObj.embed.firstTimeRule) {
          if(ioAreaObj.embed.firstTimeRule.address.name) {
          document.GetVal[this.getRoadNameStartOrEnd].value=ioAreaObj.embed.firstTimeRule.address.name;
          }
      }
  }*/
}

function clearAll () {
  //Why a global function here in ioArea ?
  mboxObj.clearCatLayer();
  mboxObj.clearAll();
  fvtObj.clearRouteAndSrf();
  ioAreaObj.clearRouteAndSrf();
  if(ioAreaObj.embed) {
    var w=(ioAreaObj.embed.fix=='start')?'end':'start';
    routeEndsObj.remove.apply(routeEndsObj,[w]);
  } else {       
    routeEndsObj.remove.apply(routeEndsObj,['start']);
    routeEndsObj.remove.apply(routeEndsObj,['end']);
  }
}

function clearRouteAndSrf () {
  mboxObj.clearRouteAndSrf();
  fvtObj.clearRouteAndSrf();
  ioAreaObj.clearRouteAndSrf();
}
  
ioArea.prototype.clearRouteAndSrf = function () {
  this.toggleButtons({'clearroutetab' : false,
                 'smstab' : false,
                 'printtab' : false,
                 'emailtab' : false,
                 'downloadtab' : false});
  this.clearSuggestDiv($('#sugdivstart')[0]);
  this.clearSuggestDiv($('#sugdivend')[0]);
  if(this.mode=='ROUTE') ioAreaObj.displayMessage('Route is Cleared');
  if(this.mode=='LOCATE' && document.getElementById("locadiv").innerHTML!='') {
    ioAreaObj.displayMessage('Location search is cleared');
  }
}
 
ioArea.prototype.realBoldify = function(me,pat,who) {
  if(me.match(/\(|\)/gi)) {
    me=me.replace(/\(/gi," ")
    me=me.replace(/\)/gi," ")
  }
  var a=me.split(pat);
  var l=a.length;
  var n="";
  var s=who.substring(0,1);
  var t=who.substring(1);
  who=s.toUpperCase()+t.toLowerCase();
  for(var i=0;i<l;i++) {
    n+=a[i];
    if(i!=(l-1)) {
      if(a[i].match(/[^\s+]$/)) {
        who=who.toLowerCase();
      }  
      n+="<b style='color:red;'>"+who+"</b>";
      //n+=a[i+1];
    }  
  }
  return n;    
}

ioArea.prototype.boldify = function(who,name) {
  var pat,useVal;
  if(who=='location' || who=='locateStores') {
    //this.preReqStart = '';
    pat=new RegExp(this.preReqStart,"ig");
    useVal=this.preReqStart;
  } else if(who=='startAddress') {
    pat=new RegExp(this.preReqStart,"ig");  
    useVal=this.preReqStart;
  } else if(who=='endAddress') {
    pat=new RegExp(this.preReqEnd,"ig");  
    useVal=this.preReqEnd;
  } else {return name;}
  if (useVal.match(/^ *$/)) {return name;}
  var tmpname;
  if(self.navigator.appName.match(/Microsoft/i)) {
    tmpname=name;
  } else {
    tmpname=(name.match(pat))?this.realBoldify(name,pat,useVal):name;
  }
  return tmpname;
}

ioArea.prototype.displayMessage = function (message) {
  if($('#routedetails')[0]) {
    $('#routedetails')[0].style.display='block';  
    if($('#routedetails_primitive')[0]) $('#routedetails_primitive')[0].innerHTML='';
        $('#routedetails')[0].innerHTML="<a class=helptooltip>"+message+"</a>";
    }
    else if($('#routedetails_primitive')[0]) {
        $('#routedetails_primitive')[0].innerHTML="<a style='font-size:16px;' class=helptooltip>"+message+"</a>";
    }
}

ioArea.prototype.showHelpMessage = function (message) {
        // There should be just one display message container. 
        ioAreaObj.displayMessage(message);
        return 0;
	try  {$('#helpmesg')[0].innerHTML="<b>"+message+"</b>";}
	catch (e) { }
}
ioArea.prototype.putCurtainCall =function () {
   var curtaindivWidth=$("#dynamicDiv").css("width");
   var curtaindivHeight=$("#dynamicDiv").css("height");
   $("#curtainDiv").css('height','666px');
   $("#curtainDiv").css('width',curtaindivWidth);
   $("#curtainDiv").addClass('semiOpac');
      
}
ioArea.prototype.removeCurtain =function (){
  $("#curtainDiv").removeClass('semiOpac');
  $("#curtainDiv").css('height','opx');
  $("#curtainDiv").css('width','0px');
  $("#curtainDiv").css('visible','none');
}
ioArea.prototype.changeBackOpacity = function (value) {
  var whichDiv=$('#dynamicDiv')[0];
  if(ioAreaObj.embed) whichDiv=$('#maintable')[0];	
  if(self.navigator.appName.match(/Microsoft/i)) {
    if(!MSIE6) {
    var s=whichDiv;  
    s.style.zoom=1;
    s.style.opacity=value;
    s.style.filter="alpha(opacity="+value*100+")";
	}
  } else {  
    whichDiv.style.opacity=value;
  }    
}

function PopUpWindow(factor, newOne, force) {
  if(newOne!==undefined) {
     PopUpWindow2.apply(this,[factor]);
     return 0;
  }
  try {
    $('#body')[0].removeChild($("#comdiv")[0]);
    $('#body')[0].removeChild($("#combg")[0]);
  } catch(e) {
  }
  var mainBody=$('#body')[0] || document.body;
  var vidteqDiv=$('#vidteq')[0] || '';
  var comWindow=createElem('div');
  var comWindowBg=createElem('div');
  this.popUp = comWindow;
  this.bg = comWindowBg;
  var left=$('#main')[0].offsetLeft;
  var top=(typeof(ioAreaObj.embed)!='undefined')?mainBody.offsetTop:parseInt($('#dynamicDiv')[0].offsetTop)+120;
  if(top==0) top=$('#map')[0].style.top;
  var a=returnBrowserHeightWidth();
  height=a.height;
  var height=(typeof(ioAreaObj.embed)!='undefined')?a.height:$('#dynamicDiv')[0].offsetHeight; 
  var width=(typeof(ioAreaObj.embed)!='undefined')?mainBody.offsetWidth:$('#dynamicDiv')[0].offsetWidth;
  if(vidteq.scriptBased) {
	height=parseInt(vidteqDiv.style.height);
	width=parseInt(vidteqDiv.style.width);
  } 	
  comWindowBg.style.width=a.width+"px";
  comWindowBg.style.height=a.height+"px";
  comWindowBg.id="combg";
  comWindowBg.style.left="0px";
  comWindowBg.style.top="0px";
  comWindowBg.style.opacity="0.4";
  comWindowBg.style.filter="alpha(opacity=40)";
  comWindowBg.style.backgroundColor=mainColor;
  comWindowBg.style.zIndex=80000;
  comWindowBg.style.position='absolute';  
  comWindow.id="comdiv";
  mainBody.appendChild(comWindow);
  mainBody.appendChild(comWindowBg);
  comWindow.className='popupclass';
  comWindow.style.width=(width/factor)+"px";
  comWindow.style.height=(height/factor)+"px";
  if(typeof(accountDetails) != 'undefined' && (accountDetails.q == 'blocate' || accountDetails.q == 'locatestores')) {
    comWindow.style.width="650px";
    comWindow.style.height="450px";
  }
  comWindow.style.left=left+parseInt((width-parseInt(comWindow.style.width))/2)+"px";
  comWindow.style.top=(typeof(ioAreaObj.embed)!='undefined')?((height-height/factor)/2+"px"):320+"px";
  if(vidteq.scriptBased) comWindow.style.top=parseInt(comWindow.style.top)+vidteqDiv.offsetTop+'px';
  comWindow.style.width=parseInt(comWindow.style.width)-4+"px";
  var border="10px solid #FFFFFF";
  comWindow.style.border=border;
  var closeDiv = createElem("div");
  comWindow.appendChild(closeDiv);
  var that = this;
  function closeMe() {that.close();}
  closeDiv.className = 'close';
  var image = createElem("img");
  image.src = imagePathsObj.cross;
  image.alt = "Close";
  image.className = "close";
  image.onclick = function() {closeMe();}
  if(force===undefined || force == 0) {
      closeDiv.appendChild(image);
  }
  return 0;
}

function PopUpWindow2 (factor) {
        var __VIDTEQ_H=($(window).height());
        var __VIDTEQ_TOP=parseInt((__VIDTEQ_H-(__VIDTEQ_H/factor))/2);
        __VIDTEQ_H=parseInt(__VIDTEQ_H/factor);
        var __VIDTEQ_W=parseInt(($(window).width())/factor);
        var floatDiv=document.createElement('div');
        var bgDiv=document.createElement('div');
        floatDiv.id='comDivFixed';
        var style={
            'position':'fixed',
            'top':__VIDTEQ_TOP+'px',
            'left':'0px',
            'width':'100%',
            'height':'100%',
            'textAlign':'center',
            'zIndex':'10000'
        }
        for(var prop in style) {
            floatDiv.style[prop]=style[prop];
        }
        var innerHTML=['<center style="height: '+__VIDTEQ_H+'px;">'];
        innerHTML.push('<div id="comdiv" style="width: '+__VIDTEQ_W+'px;background-color:#ACC488;border:10px solid white;height: '+__VIDTEQ_H+'px;"></div>');
        innerHTML.push('</center>');
        innerHTML=innerHTML.join('');
        floatDiv.innerHTML=innerHTML;
        bgDiv.id='vidteqBgDiv';
        style = {
            'width':'100%',
            'height':'100%',
            'overflow':'visible',
            'left':'0',
            'top':'0',
            'opacity':'0.4',
            'filter':'alpha(opacity=40)',
            'backgroundColor':'#000',
            'zIndex':8000,
            'position':'fixed'
        }
        for(var prop in style) {
            bgDiv.style[prop]=style[prop];
        }

        this.popUp = floatDiv;
        this.bg = bgDiv;
        document.body.appendChild(floatDiv);
        document.body.appendChild(bgDiv);
        var closeDiv = createElem("div");
        $('#comdiv')[0].appendChild(closeDiv);
        var that = this;
        function closeMe() {that.close();}
        closeDiv.className = 'close';
        var image = createElem("img");
        image.src = imagePathsObj.cross;
        image.alt = "Close";
        image.className = "close";
        image.onclick = function() {closeMe();}
        closeDiv.appendChild(image);
}

PopUpWindow.prototype.close = function() {
  try {
	if($('#body')[0]) {  
        $('#body')[0].removeChild(this.popUp);
        $('#body')[0].removeChild(this.bg);
	}
	document.body.removeChild(this.bg);
	document.body.removeChild(this.popUp);
    ioAreaObj.changeBackOpacity(1);
  } catch(e) {
  }
}

PopUpWindow.prototype.showContents=function (htmlInfo) {
  mainColor = '#376092';
  var comParam,comFunc,comValue,inputVal,dynamicRows,dynamicColumns;
  /*if(isMapXpanded){
  clearVideoTd();
  }*/
  var h=parseInt($('#comdiv')[0].style.height)-125+"px";
  var w=parseInt($('#comdiv')[0].style.width)-20+"px";
  var innerTextDiv = document.createElement("div");
  $('#comdiv')[0].appendChild(innerTextDiv);
  var innerHTML="";
  innerHTML+="<div id='headerDiv' style='text-align:center;padding:10px;height:40px;'><a onfocus='this.blur();' class='popupheader'>"+htmlInfo.headerHtml+"</a><br><div style='text-align:center;padding:10px;height:40px;' id='messageDiv'></div></div>";
  if(typeof(accountDetails)!=='undefined')  {
      if(accountDetails.q == 'blocate' || accountDetails.q == 'locatestores') {
          innerHTML="<div id='headerDiv' style='text-align:center;padding:10px;height:40px;'><a onfocus='this.blur();' class='popupheader_yellow'>"+htmlInfo.headerHtml+"</a><br><div style='text-align:center;padding:10px;height:40px;' id='messageDiv'></div></div>";
      }
          
  }
  innerHTML+="<div style='text-align:center; padding:4px;'><div id='innerDiv' style='position:relative;border: 1px solid #7fbee3; vertical-align:middle;background-color:#fff;overflow:auto;margin-left:10px;margin-right:10px;height:"+h+";border:1px solid "+mainColor+"'>"+htmlInfo.innerDivHtml+"</div></div>";
  if(typeof htmlInfo.lowerHtml!='undefined') {
    innerHTML+="<div style='text-align:center;padding:10px;'>"+htmlInfo.lowerHtml+"</div>"
  }
  //$('#comdiv')[0].innerHTML=innerHTML;
  innerTextDiv.innerHTML=innerHTML;
  try {
    // Jquery round corners fails in IE. So don' don't do it.
    if(!self.navigator.userAgent.match(/MSIE/)) $('#comdiv').corner("round");
  }
  catch(e) {}
}

ioArea.prototype.getEntity = function (source,index) {
  if (index == -1) return null;
  //if (source == 'location' || source == 'locateStores') return this.response[index];
  if (source == 'location' || 
      source == 'locateStores' || 
      source == 'startAddress' ||
      source == 'blocate') return this.srfResponse.srf[0].results[index];
  if (source == 'endAddress' ) return this.srfResponse.srf[1].results[index];
  if (source == 'center') return this.embed.place;
  if (source == 'ftrStart') return this.embed.firstTimeRule.start;
  if (source == 'ftrEnd') return this.embed.firstTimeRule.end;
  return null;
}

ioArea.prototype.cancelRequest = function () {
  // TBD and it does not work for now
  globalAjaxObj.abort();
  ioAreaObj.displayMessage("User cancelled the last request ");
}

ioArea.prototype.toggleEntityShowOnFvtMoreOrLess = function (idNo,flag) {
	$('#showMoreOrLess'+idNo)[0].innerHTML=(flag==0)?'Less <<':'More >>';
	if(flag)
	$('#showMoreDiv'+idNo).hide();
	else 
	$('#showMoreDiv'+idNo).show();
	flag=(flag==0)?1:0;
	$('#showMoreOrLess'+idNo)[0].onclick=function () {ioAreaObj.toggleEntityShowOnFvtMoreOrLess(idNo,flag);}
}	

ioArea.prototype.categorySearchInvoke = function () {
    ioAreaObj.srfResponse.srf[0].categoryMatches = 0;
    var localResults=[];
    for(var i in ioAreaObj.srfResponse.srf[0].results) {
        if(ioAreaObj.srfResponse.srf[0].results[i].matchSource == "category") {
            ioAreaObj.srfResponse.srf[0].results[i].matchSource = "misc";
            localResults.push(ioAreaObj.srfResponse.srf[0].results[i]);
        }
    }
    ioAreaObj.srfResponse.srf[0].results=[];
    ioAreaObj.srfResponse.srf[0].results=localResults;
    ioAreaObj.handleLocate.apply(ioAreaObj,[ioAreaObj.srfResponse]);
}

ioArea.prototype.reviseSrf = function (srfResponse) {
  if (typeof(srfResponse.vid) != 'undefined') return;
  for (var i = 0; i < srfResponse.srf.length; i++) {
    srfResponse.srf[i].srfIndex = i;
    if (isObjectEmpty(srfResponse.srf[i].results[0])) srfResponse.srf[i].results = [];
    reviseOneSrfArrayWithParentTypeAndIndex(srfResponse.srf[i].results,srfResponse.srf[i].srfType);
    if(srfResponse.srf[i].results[srfResponse.srf[i].results.length-1].matchSource == "category") {
        // Category match results are always pushed in the end.
        srfResponse.srf[i].categoryMatches = 1;
    }
    reviseIcons(srfResponse.srf[i]);
  }
  var putReqSeed = {'ss':1,'ff':1,'mm':1,
                    'sf':1,'mf':1,'fs':1,'fm':1,
                    'sm':1,'ms':1,'location':1};
  if (typeof(putReqSeed[srfResponse.responseType]) != 'undefined') {
    srfResponse.srf[0].reqSeed = this.preReqStart;
  }
  if (srfResponse.srf.length == 2) {
    srfResponse.srf[1].reqSeed = this.preReqEnd;
  }
  if ( srfResponse.responseType == 'sf' ||
       srfResponse.responseType == 'sm' ||
       srfResponse.responseType == 'ss' ) {
    var entity = srfResponse.srf[0].results[0];
    if (! entity.address.name) {
      entity.address.name = this.startEntity.address.name;
    }  // TBD assignment should be done according to source of startEntity
    // if startEntity is from earlier srf, use that, other wise use incoming
    // TBD center need to be fixed back
    if (this.embed && this.embed.fix=='start') {
      srfResponse.srf[0].results[0] = this.embed.place;
    }
  }
  if ( srfResponse.responseType == 'fs' ||
       srfResponse.responseType == 'ms' ||
       srfResponse.responseType == 'ss' ) {
    var entity = srfResponse.srf[1].results[0];
    if (! entity.address.name) {
      entity.address.name = this.endEntity.address.name;
    }
    // TBD center need to be fixed back
    if (this.embed && this.embed.fix=='end') {
      srfResponse.srf[1].results[0] = this.embed.place;
    }
  }
  if ( srfResponse.responseType == 'location' &&
       srfResponse.srf[0].results.length == 1) {
    var entity = srfResponse.srf[0].results[0];
    if (! entity.address.name) {
      entity.address.name = this.startEntity.address.name;
    }
  }
}


