var MapSearch = {
     
   REQUEST_TYPE : "map",
 
    clearAll : function(){
        if(routeDrawer != null){
            routeDrawer.Destroy();
        }
        printFactory.clear();
        map.MireoMap("hideInfoWindow");
    },
   
    validate : function(loc){
        //alert("MapSearch");
        if(loc == "eg:Greater Kailash 2,New Delhi" || loc.length < 1){
            alert("Please enter a valid 'Location' name to continue.....");
            return false;
        }

        $("#mapForm").html("<img alt=\"loading...\"  src=\"images/ajax-loader.gif\"  />");
              
        Overlays.removeAllMarker();
        var tooltip = document.getElementById("tooltip");
        if(tooltip.value == "true" && ToolTip.type == "map"){
            var addr = printFactory.getGeoPoint()._street + " " + printFactory.getGeoPoint()._city + " " + printFactory.getGeoPoint()._area;
            if(loc == addr) {
                geo.SetGeoAddress(printFactory.getGeoPoint());
                geo.Draw(true);
                var elem = $(HTMLHelper.mapMarker(Poi.mImg, Poi.marker_Width, Poi.marker_height));
                Overlays.addMarker(map.MireoMap("addMarker", elem, printFactory.getGeoPoint().pt));
                elem.click(function(){
                    map.MireoMap("showInfoWindow",printFactory.getGeoPoint().pt, {inner:addr});
                });
            } else {
                tooltip.value = "";
                ToolTip.type  = null;
                MapSearch.validate(loc);
            }
        } else {

            this.clearAll();
            var ga = map.MireoMap("search", $.trim(loc));
            this.reqObj = ga;
            $("#alternate_text").html("");            
            $("<ul>").attr({id:"alternate"}).append("<li><br /><b>Choose the closest match from the list below :</b></li>").appendTo('#alternate_text');
            $("#mapForm").html("");
            if(ga.length > 0) {
                for(var i = 0; i < ga.length; i++) {
                    var txt = '';

			if (ga[i]._POI.length > 0) {
                        txt = ga[i]._POI + ", ";
			}
                    if (ga[i]._street.length > 0) {
                        txt += ga[i]._street + ", ";
                    }
		      txt += ga[i]._city + ", " + ga[i]._area;
                 	if (ga[i]._phone.length > 0) {
                        txt += ", " + ga[i]._phone;
			}


                    var t = $("<li>").attr({id:"geo"+i});
                    $("#alternate_text").append(t);

                    var countArr = [];
                    countArr.push("<table><tr><td valign='top' class='table_index'>");
                    countArr.push((i + 1));                    
                    countArr.push(")</td>");
                    countArr.push("<td valign='top'>");
                    countArr.push(txt);
                    //countArr.push(ga[i]._city);
                    countArr.push("</td></tr></table>");
                    //-------

                    var t2 = $("<span style='cursor:pointer;'>" + countArr.join("") +"</span>").appendTo("#geo"+i);
                    delete(countArr);

                    t2.click(function() {   
                       var geoId = $(this).parent().attr("id").split("geo");
                       printFactory.setIndex(geoId[1]);
                       MapSearch.showMarker('click');
                    });
                }              
              gotoBox('find_location_results_box', 'find_location_box');
              printFactory.setIndex(0);
              this.showMarker('default');
            } else {
                $("#alternate_text").html("");
               // $("#alternate_text").append("<br><br><span align=center'>No Match found : '"+loc+"'.</span><br>");
               // $("#alternate_text").append($("#example").html());
var sorryDiv = '<div class="eg"><div class="eg_htext_main">We could not find any match for your search <b>'+loc+ '</b></div><div class="eg_htext_main"><b>We suggest you to </b></div><div class="eg_htext"> - Try different keyword search </div><div class="eg_htext">  - Make sure the spelling is correct</div> <div class="eg_htext"> - Try without comma separation </div><div class="eg_htext">  - Enter in one of the following forms</div><ul class="eg_loc" style="margin-left:20px;"><li>Street, Locality</li><li>Street, City</li><li>Locality and/or City</li></ul><div class="eg_htext"> - For landmark search go to <b> \'Search <br/> &nbsp; Local POI section\'</b> </div></div>';
                $("#alternate_text").append(sorryDiv);

                gotoBox('find_location_results_box', 'find_location_box');
            }
        }
        return false;
    },

    showMarker : function(showtype){
        Overlays.removeAllMarker();

        printFactory.setQ(MapSearch.REQUEST_TYPE);
        printFactory.setGeoPoint(this.reqObj[printFactory.getIndex()]);

        var locArr = [];
        locArr.push(printFactory.getGeoPoint()._POI);
        locArr.push(printFactory.getGeoPoint()._street);
        locArr.push(printFactory.getGeoPoint()._city);
        locArr.push(printFactory.getGeoPoint()._area);
        locArr.push(printFactory.getGeoPoint()._phone);

        var addr = $.trim(locArr.join(" "));       
        locArr = null;
        printFactory.setLocation(addr);
        geo.SetGeoAddress(printFactory.getGeoPoint());
        geo.Draw(true);

        $("#final_location_text").html("");
        $("#final_location_text").append(addr);
        if(showtype == 'click')
        gotoBox('final_location_results_box','find_location_results_box');

        var elem = HTMLHelper.mapMarker("images/mark.png", 26, 45);
        var tempDiv = "<div id=map"+printFactory.getIndex()+">"+elem+"</div>";
        Overlays.addMarker(map.MireoMap("addMarker", tempDiv, printFactory.getGeoPoint().pt));

        var innerTxt = "<div id='infoOption'>" + addr + "</div><div class='your_location_setstart'><span onclick='mmiEvents.finalAddrSetSart();'>Set as Start</span> &nbsp;|&nbsp; <span onclick='mmiEvents.finalAddrSetEnd();'>Set as End</span> &nbsp;|&nbsp; <span onclick='mmiEvents.finalAddrSetVia();'>Set as Via Point</span> &nbsp;|&nbsp; <span onclick='mmiEvents.finalAddrNearBy();'>Find Nearby</span></div>";
        $('#map' + printFactory.getIndex()).click(function() {
        map.MireoMap("showInfoWindow", printFactory.getGeoPoint().pt, {inner:innerTxt});
        });

        mmiEvents.printObj = printFactory;
    }
}

var Poi = {    
    q : null,
    divId : null,
    resultObj : null,
    mImg : "images/green_bg.png",
    marker_Width  : 26,
    marker_height : 37,
    requestUrl : null,
    passGeoObj : null,
    sort : null,

    clear : function() {
        this.q = null;
        this.requestUrl = null;
        this.resultObj = null;
        this.passGeoObj = null;
        this.sort = 'distance';  
        routeDrawer.Destroy();
        map.MireoMap("hideInfoWindow");
        $("#pagination").html("");
        $("#poi_result_text").html("<span color='background-color:yellow;align:center;'>Loading Data Wait......</span>");
    },
    
    validate : function(){
       
        var loc  = $.trim(document.getElementById('poi_where_input').value);
        var mapView = document.getElementById("mapView");
        var cat  = document.forms.poiform.catOpt;
        var catName = null;
        for(var i=0; i < cat.length; i++) {
            if(cat[i].checked == true){
                catName = cat[i].value;
            }
        }
        
        var what = null;      
        if(catName == "cat")
          what = $.trim(document.getElementById('localWhat').value);
        else if (catName == "biz")
          what = $.trim(document.getElementById('find_poi_what_input').value);

        if(catName == null) {
            alert("Please select the type of search you want.") ;
            return false;
        } else if((what == null || what == "" || what == "eg:Pizza Hut") && catName == "biz" ){
            alert("Please enter valid 'What' field input");
            return false;
        } else if(mapView.checked == false && (loc == "eg:Greater Kailash 2,New Delhi" || loc.length < 1)) {
            alert("Please enter a valid 'Where' Location to continue with the search..");
            return false;
        } else if(what == "" || what.length < 1) {
            alert("Please enter a valid input in the 'Category' field to continue with the search..");
            return false;
        } else {
            $("#poiLoading").show();
            Poi.clear();
            if(mapView.checked){
              var bound = map.MireoMap("getBounds");
              var pt =  map.MireoMap("getCenter");
              printFactory.setQ(catName);
              map.MireoMap("findClosestStreet", pt, function(result){
                  ToolTip.clearToolTipRequest();
                  //GeoCodeDirection.clear();
                 // alert(GeoCodeDirection.start + "        " +GeoCodeDirection.end);
                  ToolTip.setType('poi');
                  $("#tooltip").val('true');
                  printFactory.setGeoPoint(result);
                  printFactory.setSort(Poi.sort);
                  printFactory.setCategory(what+"|"+bound.x1+","+bound.y1+","+bound.x2+","+bound.y2);
//                  printFactory.setCategory(what);
		  var addr = printFactory.getGeoPoint()._street + " " + printFactory.getGeoPoint()._city + " " + printFactory.getGeoPoint()._area;
                  printFactory.setLocation(addr);
                  if(catName == 'biz'){
                     Poi.businessSearch(0);
                  } else {
                     Poi.callToServer(0);
                  }
                  gotoBox('find_poi_results_box','find_poi_box');
              });
             
            } else {
              this.showWhereAlternates(loc,catName,what);
            }
        }
       return false;
    },

    showWhereAlternates : function(where,catName,what) {
        Overlays.removeAllMarker();
        var tooltip = document.getElementById("tooltip");
        if(tooltip.value == "true" && ToolTip.type == "poi"){
            var addr = $.trim(printFactory.getLocation());
            if(addr != where){
               tooltip.value = "";
               ToolTip.type = null;
               this.showWhereAlternates(where,catName,what);
            } else {
               $("#find_poi_box").hide();
               printFactory.setQ(catName);
               printFactory.setCategory(what);
               if(printFactory.getQ() == "cat"){
                 Poi.callToServer(0);
               } else {
                 Poi.businessSearch(0);
               }
               gotoBox('find_poi_results_box','find_poi_box');
            }            
        } else {
            printFactory.clear();
            printFactory.setQ(catName);
            printFactory.setCategory(what);

            var ga = map.MireoMap("search", where);
            $("#poiAlternate").html("");
            $("#poiAlternate").css({ overflowY: "scroll" });

            $("<ul>").attr({id:"alternatepoi"}).append("<li><b>Choose the closest match from the list below :</b></li>").appendTo('#poiAlternate');
//            $("<ul>").attr({id:"alternatepoi"}).append("<li><br /><b>Choose the closest match from the list below :</b></li>").appendTo('#poiAlternate');
            $("#poiLoading").hide(); //Hidding loading div
            if(ga.length > 0 ){                
                for(var i = 0; i < ga.length; i++) {
                    var txt = '';
                    if (ga[i]._street.length > 0) {
                        txt = ga[i]._street + ", ";
                    }

                    var t = $("<li>").attr({id:"poi"+i});
                    $("#alternatepoi").append(t);

                    //ashu
                    var countArr = [];
                    countArr.push("<table width='100%'><tr><td valign='top' class='table_index'>");
                    countArr.push((i + 1));
                    countArr.push(")</td>");
                    countArr.push("<td valign='top'>");
                    countArr.push(txt);
                    countArr.push(ga[i]._city);
                    countArr.push("</td></tr></table>");
                    //-------

                    var t2 = $("<span style='cursor:pointer;'>" + countArr.join("") +"</span>").appendTo("#poi"+i);
                    delete(countArr);

                    t2.click(function() {
                        var geoId = $(this).parent().attr("id").split("poi");
                        printFactory.setIndex(geoId[1]);
                        printFactory.setGeoPoint(ga[printFactory.getIndex()]);
                        var addr = printFactory.getGeoPoint()._street + " " + printFactory.getGeoPoint()._city + " " + printFactory.getGeoPoint()._area;
                        printFactory.setLocation(addr);
                        if(printFactory.getQ() == "cat"){
                            Poi.callToServer(0);
                        } else {
                            Poi.businessSearch(0);
                        }
                    });
                }

            } else {
                $("#poiAlternate").html("");
var sorryDiv = '<div class="eg"><div class="eg_htext_main">We could not find any match for your search <b>'+where+ '</b></div><div class="eg_htext_main"><b>We suggest you to </b></div><div class="eg_htext"> - Try different keyword search </div><div class="eg_htext">  - Make sure the spelling is correct</div> <div class="eg_htext"> - Try without comma separation</div><div class="eg_htext">  - Enter in one of the following forms</div><ul class="eg_loc" style="margin-left:20px;"><li>Street, Locality</li><li>Street, City</li><li>Locality and/or City</li></ul><div class="eg_htext"> - For landmark search go to <b> \'Search <br/> &nbsp; Local POI section\'</b> </div></div>';
$("#poiAlternate").append(sorryDiv);
            //    $("#poiAlternate").append("<span style='padding-left:10px;'><br/>Sorry! We could not find any results this time. Please try a different search.</span>");
            }
            gotoBox('find_poi_where_results_box', 'find_poi_box');
        }
        return false;
    },
   
    businessSearch : function(start) {
        printFactory.setStart(start);
        var pt = printFactory.getGeoPoint().pt.x+","+printFactory.getGeoPoint().pt.y;
        Poi.requestUrl = "php/business.php?q=business&localWhat="+$.trim(printFactory.getCategory())+"&localWhere="+pt+"&st="+start+"&by="+printFactory.getSort();
//        Poi.requestUrl = "php/business.php?q=business&localWhat="+$.trim(printFactory.getCategory())+"&localWhere="+pt+"&st="+start;
        mRequestXHTTP(Poi.requestUrl,Poi.businessResponse,"text",false,this);
    },
    
    businessResponse : function(response) {
       
        var xmlObject = null;
        if (typeof DOMParser != "undefined") {    // Mozilla, Firefox, and related browsers
            xmlObject = (new DOMParser()).parseFromString(response, "application/xml");
	} else if (typeof ActiveXObject != "undefined") { // Internet Explorer
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";           
            xmlDoc.loadXML(response);
            xmlObject = xmlDoc;
	}

        $("#pagination").html("");
        $("#poiLoading").hide();
        var resultSetTag = null;
        try {
            resultSetTag = xmlObject.childNodes[0];
        } catch(e) { }

       
        Overlays.removeAllMarker();
       
        var num = resultSetTag.getAttribute("num");       
        var start   = parseInt(resultSetTag.getAttribute("start"));
        var perPage = parseInt(resultSetTag.getAttribute("perPage"));
     
        if(printFactory.getQ() == "biz"){
            $("#poi_result_text").html("");
            $("<ul>").attr({id:"poiList"}).appendTo('#poi_result_text');
            gotoBox('find_poi_results_box','find_poi_where_results_box');
        } else {
            $("#print_POI_result_text").html("");
            $("<ul>").attr({id:"poiList"}).appendTo('#print_POI_result_text');
        }

        Overlays.addMarker(map.MireoMap("addMarker", $(HTMLHelper.mapMarker("images/mark.png", 26, 45)).click(function(){
                map.MireoMap("showInfoWindow", printFactory.getGeoPoint().pt, {inner:printFactory.getLocation()});
        }), printFactory.getGeoPoint().pt));

        if(num > 0 && printFactory.getQ() != "MapDivPrint") {
           
            var quotient  = parseInt(num/10);
            var remainder = parseInt(num % 10);
            var totalPage = quotient;
            if(remainder > 0){
               totalPage++;
            }

            if(totalPage > 1) {
               var paginationArr = [];
               var mapView = document.getElementById("mapView");
               paginationArr.push("<b>")
               paginationArr.push($.trim(document.getElementById("find_poi_what_input").value));
               if(mapView.checked){
                  paginationArr.push("(s) in Current Map View");
               } else {
                  //var selected = document.getElementById('localWhat');
                  //var id = selected.selectedIndex;
                  // paginationArr.push($.trim(selected[id].text));
                  paginationArr.push("(s)</b> Near <b>");
                  var loc = $.trim(document.getElementById('poi_where_input').value);                                   
                  paginationArr.push(loc);                  
                  loc = null;
               }

               paginationArr.push("</b><br><br>Sort By :<select onchange='Poi.chooseCat();' id='sort'>");
               if(this.sort == "name"){
                    paginationArr.push("<option value='distance' >Distance</option><option value='name' selected>Name</option></select><br<br>Page: ");
               } else {
                    paginationArr.push("<option value='distance' selected>Distance</option>)<option value='name' >Name</option></select><br<br>Page: ");
               }

               var t=0;
               for(;t<totalPage-1;t++){
                    paginationArr.push("<span onclick=\"Poi.getNextPage('"+t+"');\">")
                    if(start == t){
                       paginationArr.push("<b>");
                       paginationArr.push((t+1));
                       paginationArr.push("</b>");
                    } else {
                       paginationArr.push((t+1));
                    }
                    paginationArr.push("</span>");
                    paginationArr.push("&nbsp | &nbsp;");
               }
               paginationArr.push("<span onclick=\"Poi.getNextPage('"+t+"');\">");
               if(start == t){
                     paginationArr.push("<b>");
                     paginationArr.push((t+1));
                     paginationArr.push("</b>");
               } else {
                     paginationArr.push((t+1));
               }
               paginationArr.push("</span>");           
               $("#pagination").append(paginationArr.join(""));        
            }
        }

        if(printFactory.getQ() == "biz")
            $("#poiLoading").hide();

        var latArr = new Array();
        var lonArr = new Array();

        var pt = null;
        this.resultObj = resultSetTag;
        if(num > 0) {
            for(var i = 0; i < perPage; i++) {
                var resultTag = resultSetTag.childNodes[i];             
                var lat = resultTag.getAttribute("x");
                var lon = resultTag.getAttribute("y");
                var city = resultTag.getAttribute("city");
                var state = resultTag.getAttribute("state");
                var name = resultTag.getAttribute("name");
                var locality = resultTag.getAttribute("locality");
                var phone = resultTag.getAttribute("phone");
                var distance = resultTag.getAttribute("distance");

                var newAdd = [];
                newAdd.push(locality);
                newAdd.push(city);
                newAdd.push(state);
                var address = newAdd.join(" ");
                delete(newAdd);
                latArr.push(lat);
                lonArr.push(lon);
                pt = new Point(lat, lon);

                var id = start*10;
                var leftMar = -5;
                if((id+(i+1)) > 9){
                  leftMar = -9;
                }
                var inner_html="<div style='left:"+leftMar+"px;position:absolute;top:-12px;color:white;font-weight:bold;'>"+ (id+(i+1)) +"</div>";
                elem = HTMLHelper.mapMarker(Poi.mImg, Poi.marker_Width, Poi.marker_height, null, null, false, inner_html);

                elem = $(elem);
                elem.attr('info', i);
                elem.click(function(e){
                   Poi.showCat($(e.currentTarget).attr('info'));
                });

                Overlays.addMarker(map.MireoMap("addMarker", elem, pt));              
              
                var result = [];
                result.push("<li><div class='POI_result_icon'><b>" + (id+(i+1)) + "</b></div><div class='POI_result_text'><span style='cursor:pointer;text-decoration:underline;' onclick=\"Poi.showCat("+i+");\">"+ name + "</span><br /><b>Address : </b>"+address +"<br />");
                result.push("<b>Distance</b> : ");
                if(parseInt(distance/1000) < 1){
                    result.push(parseInt(distance));
                    result.push(" meters.");
                } else {
                    result.push((distance/1000).toFixed(1));
                    result.push(" Km.");
                }

                if(phone != null && phone.length > 0 && phone != "null"){
                    result.push("<br><b>Ph </b>:");
                    result.push(phone);
                } 
                result.push("</div><div class='cls'/></li>");
                $('#poiList').append(result.join(""));
                result = null;
                // alert(mXMLSerializer.toString(resultTag));
            }
           
   	    if(printFactory.getCategory().indexOf("|") == -1) {         
               var maxlat = Array.max(latArr);
               var maxlon = Array.max(lonArr);
               var minlat = Array.min(latArr);
               var minlon = Array.min(lonArr);          
              map.MireoMap("setBounds", {x1: minlat, x2: maxlat, y1: maxlon, y2:minlon}); //Setting bounds
            }
            if(printFactory.getQ() == "biz")
                mmiEvents.printObj = printFactory;
        } else {
            $("#poi_result_text").html("Sorry. We could not find any results this time. Please try a different search.");
        }

        if(printFactory.printObj == "MapDivPrint")
          map.MireoMap("freeze");
      
    },

    selCategory : function(index){
        var element = document.getElementById("categoryContents");
        if(element.childNodes.length > 0){
            var key = element.childNodes[index].firstChild.nodeValue;
            var value = element.childNodes[index].getAttribute("value");
            document.getElementById("find_poi_what_input").value=key;
            this.what = value;
            $("#categoryHolder").hide();
        }
    },

    hideCategories : function() {
       $("#categoryHolder").fadeOut('slow');
    },

    getNextPage : function(index){
        if(printFactory.getQ()=="cat")
            Poi.callToServer(index);
        else if(printFactory.getQ()=="biz")
            Poi.businessSearch(index);

    },

    callToServer : function(start) {
        var pt = printFactory.getGeoPoint().pt.x+","+printFactory.getGeoPoint().pt.y;
        printFactory.setStart(start);
        Poi.requestUrl = "php/localSearch.php?localWhat="+printFactory.getCategory()+"&st="+start+"&localWhere="+pt+"&by="+printFactory.getSort();
//        Poi.requestUrl = "php/localSearch.php?localWhat="+printFactory.getCategory()+"&st="+start+"&localWhere="+pt;
        /*For Print*/
        if(printFactory.getQ()== "cat"){
            mRequestXHTTP(Poi.requestUrl,Poi.onResponse,"xml",false,Poi);
        } else {
            mRequestXHTTP(Poi.requestUrl,Poi.onOtherResponse,"xml",false,Poi);
        }
    },

  chooseCat : function(){
      var sortBy = document.getElementById("sort");
      this.sort = sortBy.value;
      printFactory.setSort(sortBy.value);
      if(printFactory.getQ()=="cat"){
         Poi.callToServer(0);
      } else {
         Poi.businessSearch(0);
      }
    },

    
    onResponse : function(resultset) {
        
        var resultSetTag = resultset;        
        if(document.all)
            resultSetTag = resultset.childNodes[1];
        else
            resultSetTag = resultset.childNodes[0];

        var num = resultSetTag.getAttribute("num");
        var start = parseInt(resultSetTag.getAttribute("start"));        
        var perPage = 10;
        Overlays.removeAllMarker();
        gotoBox('find_poi_results_box','find_poi_where_results_box');        
        $("#poiLoading").hide();
        if(num > 0) {          
            var quotient  = parseInt(num/perPage);
            var remainder = parseInt(num % perPage);
            var totalPage = quotient;
            if(remainder > 0){
               totalPage += 1;
            }

            if(totalPage > 1) {
                var paginationArr = [];
                var mapView = document.getElementById("mapView");
                var selected = document.getElementById('localWhat');
                var id = selected.selectedIndex;
                paginationArr.push("<b>")
                paginationArr.push($.trim(selected[id].text));
                if(mapView.checked){
                  paginationArr.push("(s)</b> Within Current Map View");
                } else {                  
                  var loc = $.trim(document.getElementById('poi_where_input').value);
                  paginationArr.push("(s)</b> Near <b>");
                  paginationArr.push(loc);
                  paginationArr.push("</b>");
                }
                paginationArr.push("<br><br>Sort By :<select onchange='Poi.chooseCat();' id='sort'>");
                if(this.sort == "name"){
                    paginationArr.push("<option value='distance' >Distance</option><option value='name' selected>Name</option></select><br<br>Page: ");
                } else {
                    paginationArr.push("<option value='distance' selected>Distance</option>)<option value='name' >Name</option></select><br<br>Page: ");
                }

                var t=0;
                for(;t<totalPage-1;t++){
                    paginationArr.push("<span onclick=\"Poi.getNextPage('"+t+"');\">")
                    if((start/10) == t){
                       paginationArr.push("<b>"); 
                       paginationArr.push((t+1));
                       paginationArr.push("</b>");
                    } else {                        
                       paginationArr.push((t+1));
                    }
                    paginationArr.push("</span>");
                    paginationArr.push("&nbsp | &nbsp;");
                }
                paginationArr.push("<span onclick=\"Poi.getNextPage('"+t+"');\">");
                if(start/10 == t){
                 paginationArr.push("<b>");
                 paginationArr.push((t+1));
                 paginationArr.push("</b>");
                } else {
                 paginationArr.push((t+1));
                }
                paginationArr.push("</span>");
                $("#pagination").html("");
                $("#pagination").append(paginationArr.join(""));
            }

            var latArr = new Array();
            var lonArr = new Array();

            $("#poi_result_text").html("");
            $("<ul>").attr({id:"poiList"}).appendTo('#poi_result_text');
            
            var pt  = null;
            this.resultObj = resultSetTag;

            
            var display = 10;
            if(start == quotient && remainder > 0){
               display = remainder;
            }

            
            Overlays.addMarker(map.MireoMap("addMarker", $(HTMLHelper.mapMarker("images/mark.png", 26, 45)).click(function(){
                map.MireoMap("showInfoWindow", printFactory.getGeoPoint().pt, {inner:printFactory.getLocation()});
            }), printFactory.getGeoPoint().pt));

            for(var i = 0; i < display; i++) {
                var resultTag = resultSetTag.childNodes[i];
                var point = resultTag.getAttribute("point");
                var name = resultTag.getAttribute("name");
                var locality = resultTag.getAttribute("locality");
                var city = resultTag.getAttribute("city");
                var state = resultTag.getAttribute("state");
                var phone = resultTag.getAttribute("phone");
                var distance = resultTag.getAttribute("distance");
                var newAdd = [];
                newAdd.push(locality);
                newAdd.push(city);
                newAdd.push(state);
                var address = newAdd.join(" ");
                delete(newAdd);

                var ll = point.split(" ");
                
                pt = new Point(ll[0], ll[1]);
                latArr.push(ll[0]);
                lonArr.push(ll[1]);
              
                var leftMar = -5;
                if((start+(i+1)) > 9){
                    leftMar = -9;
                }

                var inner_html="<div style='position:absolute;top:-10px;left:" + leftMar + "px;color:white;font-weight:bold;'>"+ (start+(i+1)) +"</div>";
                var elem = HTMLHelper.mapMarker(Poi.mImg, Poi.marker_Width, Poi.marker_height, null, null, false, inner_html);
                
                elem = $(elem);
                elem.attr('info', i);
                elem.click(function(e){
                    Poi.showCat($(e.currentTarget).attr('info'));
                });

                Overlays.addMarker(map.MireoMap("addMarker", elem, pt));              
                var result = [];
                result.push("<li><div class='POI_result_icon'>" + (start+(i+1)) + "</div><div class='POI_result_text'><span style='cursor:pointer;text-decoration:underline;' onclick=\"Poi.showCat("+i+");\">"+ name + "</span><br /><b>Address : </b>"+address +"<br />");

                if(phone != null && phone.length > 0){
                    result.push("<b>Ph </b>:");
                    result.push(phone);
                    result.push("<br />");
                } 

                result.push("<b>Distance</b> : ");
                if(parseInt(distance/1000) < 1){
                    result.push(parseInt(distance));
                    result.push(" meters.");
                } else {
                    result.push((distance/1000).toFixed(1));
                    result.push(" Km.");
                }
                
                result.push("</div><div class='cls'/></li>");
                $('#poiList').append(result.join(""));
                result = null;
            }


            if(printFactory.getCategory().indexOf("|") == -1) {            
              var maxlat = Array.max(latArr);
              var maxlon = Array.max(lonArr);
              var minlat= Array.min(latArr);
              var minlon = Array.min(lonArr);
              map.MireoMap("setBounds", {x1: minlat, x2: maxlat, y1: maxlon, y2:minlon}); //Setting bounds            
	    }	
            mmiEvents.printObj = printFactory;
        } else {
            $("#poi_result_text").html("<span style='padding-left:10px;color:red'>Sorry. We could not find any results this time. Please try a different search.</span>");
        }      
    },

    showCat : function(index){
        
        var resultTag = Poi.resultObj.childNodes[index];
        var pointElem = null;
        if(printFactory.getQ() == "cat"){
            pointElem = resultTag.getAttribute("point");
        } else {          
            pointElem = resultTag.getAttribute("x");
            pointElem = pointElem + " " + resultTag.getAttribute("y");
        }
        
        var nameElem = resultTag.getAttribute("name");
        var localityElem = resultTag.getAttribute("locality");
        var cityElem = resultTag.getAttribute("city");
        var stateElem = resultTag.getAttribute("state");
        var phoneElem = resultTag.getAttribute("phone");

        var geoAdd = new GeoAddress();
        var dis = [];
        dis.push("<b>Name</b> : ");
        dis.push(nameElem);
        dis.push("<br><b>Address</b> : ");
        geoAdd._POI=nameElem;
        if(localityElem != "" && localityElem.length > 0){
            dis.push(localityElem);
            geoAdd._street=localityElem;
            dis.push(', ');
        }

        if(cityElem != "" && cityElem.length > 0){
            dis.push(cityElem);
            geoAdd._city=cityElem;
            dis.push(', ');
        }
        
        dis.push(stateElem);
        geoAdd._area=stateElem;
        
        if( phoneElem != "" && phoneElem != null && phoneElem != "null" ){
            dis.push("<br><b>Phone No</b> : ");
            dis.push(phoneElem);
            geoAdd._phone=phoneElem;         
        }

        var newPt = pointElem.split(" ");
        var showPt = new Point(newPt[0],newPt[1]);
        geoAdd.pt=showPt;
       
        var selectedObjText = jQuery.toJSON(geoAdd);
        this.passGeoObj = geoAdd;
        dis.push("<div class='your_location_setstart'><span onclick='Poi.setPoiAsMy_Start("+ selectedObjText+",\"start\");'>Set as Start</span> &nbsp;|&nbsp; <span onclick='Poi.setPoiAsMy_Start("+ selectedObjText+",\"end\");'>Set as End</span>&nbsp;|&nbsp; <span onclick='Poi.setPoiAsMy_Start("+ selectedObjText+",\"via\");'>Set as Via Point</span>&nbsp;|&nbsp; <span onclick='Poi.setPoiAsMy_Start("+ selectedObjText+",\"nearby\");'>Find Nearby</span></div>");
        map.MireoMap("showInfoWindow", showPt , {inner:dis.join("")});
    },

    setPoiAsMy_Start : function(geoAdd, type) {

        if(DynamicMap.isFullMap){
            DynamicMap.moveMap();
        }
        
        var newAdd = [];
        newAdd.push(geoAdd._POI);
        newAdd.push("(");
        newAdd.push(geoAdd._street);
        newAdd.push(geoAdd._city);
        newAdd.push(geoAdd._area);
        newAdd.push(")");
        var location = newAdd.join(" ");
        delete(newAdd);
        geoAdd = null;
      
        printFactory.setGeoPoint(this.passGeoObj);
        printFactory.setLocation(location);


        if(type == "nearby"){
            mmiEvents.finalAddrNearBy();
        } else {           
            printFactory.setQ("dir");        
            if(type == "start") {
                GeoCodeDirection.start = this.passGeoObj;
                mmiEvents.finalAddrSetSart();
            } else if(type == "end"){
                GeoCodeDirection.end = this.passGeoObj;
                mmiEvents.finalAddrSetEnd();
            } else if(type == "via"){
                GeoCodeDirection.via = this.passGeoObj;
                mmiEvents.finalAddrSetVia();
            }
        }
        this.passGeoObj = null;
        
    },

    onOtherResponse : function(resultset) {
      
        var resultSetTag = null;
        if(document.all)
            resultSetTag = resultset.childNodes[1];
        else
            resultSetTag = resultset.childNodes[0];

        var num = resultSetTag.getAttribute("num");
        var start = parseInt(resultSetTag.getAttribute("start"));
        var perPage = 10;
        
        if(num > 0) {

            var quotient  = parseInt(num/perPage);
            var remainder = parseInt(num % perPage);
            var totalPage = quotient;
            if(remainder > 0){
               totalPage += 1;
            }

            var display = 10;
            if(start == quotient && remainder > 0){
              display = remainder;
            }

            Overlays.removeAllMarker();
            var latArr = new Array();
            var lonArr = new Array();
            $("#print_POI_result_text").html("");
            
            $("<ul>").attr({id:"poiList"}).appendTo('#print_POI_result_text');
            for(var i = 0; i < display; i++) {
                var resultTag = resultSetTag.childNodes[i];
                var point = resultTag.getAttribute("point");
                var name = resultTag.getAttribute("name");
                var locality = resultTag.getAttribute("locality");
                var city = resultTag.getAttribute("city");
                var state = resultTag.getAttribute("state");
                var phone = resultTag.getAttribute("phone");
                var distance = resultTag.getAttribute("distance");
                var newAdd = [];
                newAdd.push(locality);
                newAdd.push(city);
                newAdd.push(state);
                var address = newAdd.join(" ");
                delete(newAdd);

                var ll = point.split(" ");
                var pt = new Point(ll[0], ll[1]);
                latArr.push(ll[0]); lonArr.push(ll[1]);
                var map = $("#"+printFactory.getQ());
                var leftMar = -10;
                if (i < 11) {
                    leftMar = -5;
                }
                var inner_html="<div style='position:absolute;top:-10px;left:" + leftMar + "px;color:white;font-weight:bold;'>"+ (i+1) +"</div>";
                var elem = HTMLHelper.mapMarker(Poi.mImg, Poi.marker_Width, Poi.marker_height, null, null, false, inner_html);
                Overlays.addMarker(map.MireoMap("addMarker",elem, pt));
                var result = [];
                result.push("<li><div style='color:white;font-weight:bold;'  class='print_POI_result_icon'>" + (i+1) + "</div><div class='print_text_POI_result_text'><span style='cursor:pointer;text-decoration:underline;'><b>"+ name + "</b></span><br /><b>Address : </b>"+address +"<br/>");

                if(phone != null && phone.length > 0){
                    result.push("<b>Ph </b>:");
                    result.push(phone);
                    result.push("<br />");
                }

                result.push("<b>Distance</b> : ");
                if(parseInt(distance/1000) < 1){
                    result.push(parseInt(distance));
                    result.push(" meters.");
                } else {
                    result.push((distance/1000).toFixed(1));
                    result.push(" Km.");
                }
                

                result.push("</div><div class='cls'/></li>");
                $('#poiList').append(result.join(""));
                result = null;
            }
          
          if(printFactory.getCategory().indexOf("|") == -1) {  
	    var maxlat = Array.max(latArr);
            var maxlon = Array.max(lonArr);
            var minlat= Array.min(latArr);
            var minlon = Array.min(lonArr);        

            map.MireoMap("setBounds", {x1: minlat, x2: maxlat, y1: maxlon, y2:minlon}); //Setting bounds
          }
            map.MireoMap("freeze");
          
        } else {
            alert("Sorry. We could not find any results this time. Please try a different search.");
        }
    }

}

var Direction = {
    from  : null,
    to    : null,
    via   : null,
    dirObj : null,

    clear : function() {
        this.from = null;
        this.to = null;
        this.via = [];
        this.dirObj = null;
        map.MireoMap("hideInfoWindow");
    },

    validate : function(){
        var from = document.getElementById("from_direction_input");
        var to = document.getElementById("to_direction_input");
        var via = document.getElementById("via_direction_input");//via
        var tooltip = document.getElementById("tooltip");

        $("#direction_txt").html("");
        //from.value = from.value.replace(),);
        //to.value   = to.value.toLowerCase();
      
        if((from.value == "eg:Greater Kailash 2,New Delhi" && to.value == "eg:Okhla Phase 3,New Delhi")) {
            alert("Please enter valid 'Start' & 'End' locations to continue with the search..");
            return false;
        } else if(from.value == "eg:Greater Kailash 2,New Delhi" ) {
            alert("Please enter a valid 'Start' location to continue with the search..");
            from.focus();
            return false;
        } else if(to.value == "eg:Okhla Phase 3,New Delhi" ) {
            alert("Please enter a valid 'End' location to continue with the search..");
            to.focus();
            return false ;
        } else if(from.value == to.value && ToolTip.type != "points" ) {
            alert("Please enter different 'Start' & 'End' locations to continue with the search..");
            from.focus();
            return false;
        } else {
            this.clear();
            $("#timeDistance").html("<img src='images/loader.gif' style='margin-top:2px' />");
            $("#direction_txt").html("");
            currentStatus.setQ("dir");
            Overlays.removeAllMarker();


         //   alert(ToolTip.type);
            if(via.value != "" && via.value.length > 0 && ToolTip.type != "dirVia"){
                this.via.push($.trim(via.value)); //via
            }
            //alert("Validation Else" + tooltip.value);
            if(tooltip.value == "true" ) {
                if(ToolTip.type == "points") {
                    GeoCodeDirection.showMeDirection();
                } else {
                    GeoCodeDirection.clear();
                    var newAddr = [];
                    if(ToolTip.rObj._POI != ""){
                      newAddr.push(ToolTip.rObj._POI);
                      newAddr.push("(");
                    }
                    newAddr.push(ToolTip.rObj._street);
                    newAddr.push(ToolTip.rObj._city);
                    newAddr.push(ToolTip.rObj._area);
                    if(ToolTip.rObj._POI != ""){
                     newAddr.push(")");
                    }
                    var addr = newAddr.join(" ");

                    delete(newAddr);
                    var status = false;
                    this.from = $.trim(from.value);
                    this.to = $.trim(to.value);
                    //alert("ToolTip : " +ToolTip.type);
                    switch(ToolTip.type) {
                         case "dirStart" :  status = (addr == from.value) ? true : false;
                                            //alert(status +  "           " +this.via.length);
                                            if(status) {
                                                this.from = ToolTip.rObj;

                                                if(this.via.length>0){
                                                   currentStatus.setQ('dirv');
                                                   this.onResponseSelect('via');
                                                } else {
                                                    this.onResponseSelect('to');
                                                }
                                            }
                                            break;
                        case "dirEnd"   :   status = (addr == to.value) ? true : false;
                                            if(status) {
                                                this.to = ToolTip.rObj;
                                                if(this.via.length>0)
                                                  currentStatus.setQ('dirv');

                                                this.onResponseSelect('from');
                                            }
                                            break;

                        case "dirVia"    : status = (addr == via.value) ? true : false;
                                           if(status){
                                              this.via[0] = ToolTip.rObj;
                                              //alert(this.via);
                                              this.onResponseSelect('from');
                                           }
                                           break;
                      }

                    if(!status) {
                        ToolTip.type = null;
                        tooltip.value = "";
                        this.validate();
                    }
                 }
            } else {
                //alert("Validation Else");
                GeoCodeDirection.clear();
                this.from = $.trim(from.value);
                this.to = $.trim(to.value);
                this.onResponseSelect('from');

            }
       }
       return false;
    },

    onResponseSelect : function(type) {

        var showDiv = null;
        var divAlt = null;
        var hideDiv = null;
        var parameter = null;
        var divAltContainer = null;
        var nextDiv = null;
        var display = null;

        if(type == "via") {
            showDiv = "get_directions_via_results_box";
            divAltContainer = showDiv + "_" + type;
            divAlt = "viaAlt";
            if(ToolTip.type=="dirStart"){
                hideDiv = "get_directions_box"; //hide main div
                nextDiv = "get_directions_end_results_box";
            } else if(ToolTip.type == "dirEnd"){
                hideDiv = "get_directions_via_results_box";
                nextDiv = "direction_result_panel";
            } else if(ToolTip.type == "points"){
                hideDiv = "get_directions_box";
                nextDiv = "direction_result_panel";
            } else {
                hideDiv = "get_directions_via_results_box";
                nextDiv = "get_directions_end_results_box";
            }

            parameter = this.via[0];
            currentStatus.setViaAddr(this.via[0]);
            display = "'Via' Location";
        } else if(type == "from" ) {
            showDiv = "get_directions_start_results_box"; //content main holder
            divAltContainer = showDiv + "_" + type; //content holder div
            divAlt = "fromAlt";
            hideDiv = "get_directions_box"; //hide main div
            parameter = this.from;
            currentStatus.setFromAddr(this.from);
            
            if(this.via.length > 0 && ToolTip.type != "dirVia" && ToolTip.type != "pointStart"){
               nextDiv = "get_directions_via_results_box"; //on click show this div
            } else if(ToolTip.type == "dirEnd" || ToolTip.type == "pointStart"){
                nextDiv = "direction_result_panel";
            } else {
                nextDiv = "get_directions_end_results_box";
            }
          //  alert(this.from);
            display = "'Start' Location";
        } else if(type == "to") {
            showDiv = "get_directions_end_results_box";
            divAltContainer = showDiv + "_" + type;
            divAlt = "toAlt";
            if(Direction.via.length < 1){
                hideDiv = "get_directions_box";
            } else {
               if(ToolTip.type == "dirVia"){
                  hideDiv = "get_directions_via_results_box";
               } else {
                 hideDiv = "get_directions_search_end_box";
               }
            }          
            nextDiv = "direction_result_panel";
            parameter = this.to;
            currentStatus.setToAddr(this.to);
            display = "'End' Location";
        } else if(ToolTip.type == "dirEnd") {
            showDiv = "get_directions_start_results_box";
            divAltContainer = showDiv + "_" + type;
            hideDiv = "get_directions_box";
            divAlt = "fromAlt";
            display = "'Start' Location";
            nextDiv = "direction_result_panel";
            currentStatus.setFromAddr(this.from);
            parameter = this.from;
        } else if(ToolTip.type == "dirStart") {
            showDiv = "get_directions_end_results_box";
            divAltContainer = showDiv + "_" + type;
            hideDiv = "get_directions_box";
            divAlt = "toAlt";
            display = "'End' Location";
            nextDiv = "direction_result_panel";
            currentStatus.setFromAddr(this.to);
            parameter = this.to;
        }

        var tempDiv = "#" + divAltContainer;
        var ga = map.MireoMap("search", parameter);
        $(tempDiv).html("");
        $("<ul>").attr({id:divAlt}).append("<li><br/><b>Search Results : " + display + "</b></li>").appendTo(tempDiv);

        gotoBox(showDiv, hideDiv);
        if(ToolTip.type == "pointEnd" || ToolTip.type == "pointStart"){
           Overlays.removeAllMarker();
           ToolTip.type ="points";
        }

        if(ga.length > 0) {
            $("#dirLoading").hide();
            tempDiv = null;
            tempDiv = "#" + divAlt;
            for(var i = 0; i < ga.length; i++) {
                var txt = '';
                if (ga[i]._street.length > 0) {
                    txt = ga[i]._street + ", ";
                }

                var t = $("<li>").attr({id:"geo" + type + i});
                $(tempDiv).append(t);
                //var inx = (i + 1) + ") " + txt + ga[i]._city;
                //ashu
                var countArr = [];
                countArr.push("<table><tr><td valign='top' class='table_index'>");
                countArr.push((i + 1));
                countArr.push(")</td>");
                countArr.push("<td valign='top'>");
                countArr.push(txt);
                countArr.push(ga[i]._city);
                countArr.push("</td></tr></table>");
                //-------
                var t2 = $("<span style='cursor:pointer;'>"+ countArr.join("") +"</span>").appendTo("#geo"+type+i);
                t2.click(function() {
                    var geoId = $(this).parent().attr("id").split("geo"+type);
                    $("#tool_tip_search_info").fadeOut();
                    switch(type) {
                        case "from" :   Direction.from = ga[geoId[1]];
                                        currentStatus.dirArr.push(geoId[1]);
                                        if(Direction.via.length >0) {
                                            if(ToolTip.type == "dirVia"){
                                              Direction.onResponseSelect('to');
                                            }else if(ToolTip.type == "points"){
                                              //alert("Inside POINT START");
                                              Direction.getDirectionNow();
                                            }else {
                                              //alert("ELSE PART");
                                              Direction.onResponseSelect('via');
                                            }
                                        } else if(Direction.via.length < 1 && ToolTip.type != "dirEnd") {
                                            Direction.onResponseSelect('to');
                                        } else {
                                            Direction.getDirectionNow();
                                        }
                                        gotoBox(nextDiv, showDiv);
                                        break;

                        case "via" :    Direction.via[0] = ga[geoId[1]];
                                        currentStatus.dirArr.push(geoId[1]);
                                        if(ToolTip.type == "dirEnd") {
                                            Direction.to = ToolTip.rObj;
                                            currentStatus.dirArr.push(0);
                                            $("#dirLoading").show();
                                            Direction.getDirectionNow();
                                        } else if(ToolTip.type == "points"){
                                            currentStatus.setViaAddr(Direction.via[0].pt.x+","+Direction.via[0].pt.y);
                                            currentStatus.setQ('dirv');
                                            Direction.getDirectionNow();
                                        } else {
                                            Direction.onResponseSelect('to');
                                        }
                                        gotoBox(nextDiv, showDiv);
                                        break;

                        case "to"   :   Direction.to = ga[geoId[1]];
                                        currentStatus.dirArr.push(geoId[1]);
                                        $("#dirLoading").show();
                                        Direction.getDirectionNow();
                                      //  alert(nextDiv + "           " +showDiv);
                                        gotoBox(nextDiv, showDiv);
                                        break;
                    }
                });
            }
        } else {
 	  /* var tmpTyp = null;
            if (type == 'from') {
                tmpTyp = 'Start';
            } else if (type == 'to') {
                tmpTyp = 'End';
            }
            var msgTxt = [];
            msgTxt.push("<ul><li>Sorry! We could not find any result for <b>'");
            msgTxt.push(tmpTyp);
            msgTxt.push("</b>' location.<br/><br/>Please go back and try a different search for <b>'");
            msgTxt.push(tmpTyp);
            msgTxt.push("' </b> location. </li></ul>");

            $("<div>").css({fontSize:"12px"}).append(msgTxt.join("")).appendTo(tempDiv);
            delete(msgTxt);
*/


var sorryDiv = '<div class="eg"><div class="eg_htext_main">We could not find any match for your search <b>'+parameter+ '</b></div><div class="eg_htext_main"><b>We suggest you to </b></div><div class="eg_htext"> - Try different keyword search </div><div class="eg_htext">  - Make sure the spelling is correct</div> <div class="eg_htext"> - Try without comma separation</div><div class="eg_htext">  - Enter in one of the following forms</div><ul class="eg_loc" style="margin-left:20px;"><li>Street, Locality</li><li>Street, City</li><li>Locality and/or City</li></ul><div class="eg_htext"> - For landmark search go to <b> \'Search <br/> &nbsp; Local POI section\'</b> </div></div>';
         $(tempDiv).append(sorryDiv);
        }
        
    },

    addVia : function() {
        $("#add_via").hide();
        $("#via_direction_input_div").show();
    },

    getDirectionNow : function(){
       // alert("Inside geTdIRECTION "+currentStatus.getQ());
        mmiEvents.printObj = null;
        $("#direction_txt").html("");
        var argument = [];
        argument.push(this.from);
        var via = null;

        if(this.via.length > 0){
            argument.push(this.via[0]);           
            var viaArr = [];
            if(this.via[0]._POI != ""){
             viaArr.push(this.via[0]._POI);
             viaArr.push("(");
            }
            viaArr.push(this.via[0]._street+",");
            viaArr.push(this.via[0]._city+",");
            viaArr.push(this.via[0]._area);
            if(this.via[0]._POI != ""){
              viaArr.push(")");
            }
          
            via = viaArr.join(" ");
            viaArr = null;
        }
        argument.push(this.to);

        var fromArr = [];
        if(this.from._POI != ""){
          fromArr.push(this.from._POI);
          fromArr.push("(");
        }
        fromArr.push(this.from._street+",");
        fromArr.push(this.from._city+",");
        fromArr.push(this.from._area);
        if(this.from._POI != ""){
         fromArr.push(")");
        }

        var from = fromArr.join(" ");
        fromArr = null;

        var toArr = [];
        if(this.to._POI != ""){
          toArr.push(this.to._POI);
          toArr.push("(");
        }
        toArr.push(this.to._street+",");
        toArr.push(this.to._city+",");
        toArr.push(this.to._area+",");
        if(this.to._POI != ""){
         toArr.push(")");
        }

        var to = toArr.join(" ");
        toArr = null;

        $("#dirLoading").hide();
        map.MireoMap("calculateRouteWithAdvices", argument, function(route) {
            var totalMinutes = route.time_length/60;
            var hour = parseInt(totalMinutes/60);
            var min = parseInt(totalMinutes % 60);
            Direction.dirObj = route;
            if(hour > 0 && min > 0){
                $("#timeDistance").html("Trip Info: " + (parseInt(route.length)/1000) + " Km, " + hour + " Hour "+ min +" min (estimated)");
            }  else {
                $("#timeDistance").html("Trip Info: " + (parseInt(route.length)/1000) + " Km, " + min + " min (estimated)");
            }
           
            Overlays.removeAllMarker();
            if(route.length == 0){
               $("#direction_txt").html("Route cannot be proccessed for given location.");
            } else{
                routeDrawer.Destroy();
                routeDrawer = new RouteDrawer(map);
                routeDrawer.SetRoute(route);
                routeDrawer.Draw(true);
            }

             $("#direction_txt").append("<div class='direction_result_from_flag' align='right'><img src='images/RouteStart.png' width='39' height='30'  /> </div><div class='direction_result_from_text' style='padding-left:20px;' onclick='Direction.fromShow();'>"+from+"</div><div class='cls'> </div>");
             for(var idx in route.advices) {
                var txt = $.trim(EnglishAdvisor.advice_to_text(route.advices[idx]));
                

                if(idx < route.advices.length-1) {
                  //  alert(Direction.via.length + "              " + txt)
                    if(Direction.via.length > 0 && (txt == "Destination reached.")){
                         $("#direction_txt").append("<div class='direction_result_from_flag' align='right'><img src='images/RoutePoint.png' width='39' height='30' /> </div><div class='direction_result_from_text' style='padding-left:20px;' onclick='Direction.showLocation("+idx+");'>"+via+"</div><div class='cls'></div><div class=\"direction_result_cont\"></div>");
                    } else {
                         $("#direction_txt").append("<div class='direction_result_cont'><div class='direction_result_no'>"+(parseInt(idx)+1) +"</div><div class='direction_result_text' onclick='Direction.showLocation("+idx+");'>"+EnglishAdvisor.advice_to_text(route.advices[idx]).ReplaceAll(',', '')+"</div><div class='direction_result_time'>"+(route.advices[idx].meters_to_next_advice/1000).toFixed(1) +" km </div></div>");
                    }
                } else {
                     $("#direction_txt").append("<div class='cls'></div><br /><div class='direction_result_from_flag' align='right'><img src='images/RouteEnd.png' width='39' height='30' /> </div><div class='direction_result_from_text' style='padding-left:20px;' onclick='Direction.showLocation("+idx+");'>Reached Destination "+ to +"</div><div class='cls'></div>");
                }
            }
        });        
        delete(argument);
      //  GeoCodeDirection.clear();
    },


/*
    getDirectionNow : function(){
        var argument = [];
        argument.push(this.from);
        var via = null;
        if(this.via.length > 0){
            argument.push(this.via[0]);
            via = this.via[0]._street + " " + this.via[0]._city + ", " + this.via[0]._area;
        }
        argument.push(this.to);

        var from = this.from._street + " " + this.from._city + ", " + this.from._area;
        var to = this.to._street + " " + this.to._city + ", " + this.to._area;

        map.MireoMap("calculateRouteWithAdvices", argument, function(route) {
            var totalMinutes = route.time_length/60;
            var hour = parseInt(totalMinutes/60);
            var min = parseInt(totalMinutes % 60);
            Direction.dirObj = route;
            if(hour > 0 && min > 0){
                $("#timeDistance").html("Trip Info: " + (parseInt(route.length)/1000) + " Km, " + hour + " Hour "+ min +" min (estimated)");
            }  else {
                $("#timeDistance").html("Trip Info: " + (parseInt(route.length)/1000) + " Km, " + min + " min (estimated)");
            }

            Overlays.removeAllMarker();
            if(route.length == 0){
                alert("Route cannot be found");
            } else{
                routeDrawer.Destroy();
                routeDrawer = new RouteDrawer(map);
                routeDrawer.SetRoute(route);
                routeDrawer.Draw(true);
            }

            var formatted_advices = "<div class='direction_result_from_flag' align='right'><img src='images/RouteStart.png' width='39' height='30' /> </div><div class='direction_result_from_text' onclick='Direction.fromShow();'>"+from+"</div><div class='cls'> </div>";
            for(var idx in route.advices) {
                if(idx < route.advices.length-1){
                    if(Direction.via.length > 0 && EnglishAdvisor.advice_to_text(route.advices[idx]) == "Destination reached"){
                        formatted_advices += "<div class='direction_result_from_flag' align='right'><img src='images/RoutePoint.png' width='39' height='30' /> </div><div class='direction_result_from_text' onclick='Direction.showLocation("+idx+");'>"+via+"</div><div class='cls'> </div>"
                    } else {
                        formatted_advices += "<div class='direction_result_cont'><div class='direction_result_no'>"+(parseInt(idx)+1) +"</div><div class='direction_result_text' onclick='Direction.showLocation("+idx+");'>"+EnglishAdvisor.advice_to_text(route.advices[idx])+"</div>";
                        formatted_advices += "<div class='direction_result_time'>"+(route.advices[idx].meters_to_next_advice/1000).toFixed(1) +" km </div>";
                    }
                } else {
                    formatted_advices += "<div class='cls'></div><br /><div class='direction_result_from_flag' align='right'><img src='images/RouteEnd.png' width='39' height='30' /> </div><div class='direction_result_from_text' onclick='Direction.showLocation("+idx+");'>Reached Destination "+ to +"</div><div class='cls'>";
                }
               formatted_advices += "</div>";
            }
            $("#direction_txt").html(formatted_advices);
        });
        delete(argument);
    },*/

    fromShow : function(){
       var ptObj = Direction.dirObj.advices[0].advice_location;
       var fromArr = [];
       fromArr.push("<dir>Reached Destination ");
       fromArr.push(Direction.from._street);
       fromArr.push(" ");
       fromArr.push(Direction.from._city);
       fromArr.push(" ");
       fromArr.push(Direction.from._area);
       fromArr.push("</div>");

       map.MireoMap("showInfoWindow",ptObj, {inner: $(fromArr.join(""))});
       delete(fromArr);
    },

    showLocation : function(index){
        var content = EnglishAdvisor.advice_to_text(Direction.dirObj.advices[index]);
        var ptObj = Direction.dirObj.advices[index].advice_location;
        var total = Direction.dirObj.advices.length;
        var param = [];
        param.push("<div>");
        if(index == total-1) {
            
           var toArr = [];
           toArr.push("Reached Destination");
           if(Direction.to._POI != ""){
            toArr.push(Direction.to._POI);
            toArr.push("(");
           }
           toArr.push(Direction.to._street+",");
           toArr.push(Direction.to._city+",");
           toArr.push(Direction.to._area+",");
           if(Direction.to._POI != ""){
            toArr.push(")");
           }
           var to = toArr.join(" ");
           toArr = null;

           param.push(to);
        } else if(Direction.via.length > 0 && content == "Destination reached."){

            var viaArr = [];
            viaArr.push("Reached Via Destination");

            if(Direction.via[0]._POI != ""){
             viaArr.push(Direction.via[0]._POI);
             viaArr.push("(");
            }
            viaArr.push(Direction.via[0]._street+",");
            viaArr.push(Direction.via[0]._city+",");
            viaArr.push(Direction.via[0]._area);
            if(this.via[0]._POI != ""){
              viaArr.push(")");
            }

           var via = viaArr.join(" ");
           viaArr = null;          
           param.push(via);
        } else {
           param.push("Step - ");
           param.push((parseInt(index)+1));
           param.push("<b>: </b> ");
           param.push(content);
           param.push("<br><b>&nbsp;Go : </b> ")
           param.push((Direction.dirObj.advices[index].meters_to_next_advice/1000).toFixed(1));
           param.push(" Km.");
        }
        param.push("<br><br>");

        if(index<total && index == 0) {
           param.push("<span class='dirInfoPage' style=\"cursor:pointer;\" onclick=\"Direction.showLocation("+(parseInt(index)+1)+");\">Next</span>")
        } else if(index < total && index < total-1) {
           param.push("<span class='dirInfoPage'  style=\"cursor:pointer;\" onclick=\"Direction.showLocation("+(parseInt(index)-1)+");\">Previous</span>");
           param.push("&nbsp; |&nbsp; ");
           param.push("<span class='dirInfoPage'  style=\"cursor:pointer;\" onclick=\"Direction.showLocation("+(parseInt(index)+1)+");\">Next</span>")
        } else if(index == total-1) {
           param.push("<span class='dirInfoPage'  style=\"cursor:pointer;\" onclick=\"Direction.showLocation("+(parseInt(index)-1)+")\">Previous</span>");
        }
        param.push("</div>");
        var resultHTML= param.join("");
        map.MireoMap("showInfoWindow", ptObj, {inner: $(resultHTML)});
        delete(param);
        delete(content);
        delete(ptObj);
    }
}

var ToolTip = {
    
    type : null,
    rObj : null,

    clearToolTipRequest : function() {
        this.value = null;
        this.type  = null;
    },

    setType : function(type) {
        this.type = type;
    },

    hideDivs : function() {
        $("#main_menu_box").hide();
        $("#final_location_results_box").hide();
        $("#find_location_box").hide();
        $("#find_location_results_box").hide();

        $("#find_location_see_on_map_box").hide();
        $("#find_poi_box").hide();
        $("#categoryHolder").hide();
        $("#find_poi_where_results_box").hide();
        $("#find_poi_search_what_box").hide();
        $("#find_poi_results_box").hide();

        $("#get_directions_box").hide();
        $("#get_directions_start_results_box").hide();
        $("#get_directions_search_end_box").hide();
        $("#get_directions_end_results_box").hide();
        $("#get_directions_see_route_box").hide();
        $("#get_directions_via_results_box").hide();
        $("#direction_result_panel").hide();	
    },
    
    requestType : function(requestObj) {
         this.rObj = requestObj;        
    }
}

function onLocationFocus(id){
       var element = document.getElementById(id);
       var tempElem = $.trim(element.value);
       element.value = ((tempElem == "eg:Greater Kailash 2,New Delhi") || (tempElem == "eg:Okhla Phase 3,New Delhi") || tempElem == "eg:Pizza Hut")? "" : element.value;
     }

function onLocationBlur(id){
       var element  = document.getElementById(id);
       var tempElem = $.trim(element.value);
       var defaultV = "eg:Greater Kailash 2,New Delhi";

       switch(id){
           case "find_poi_what_input" : defaultV = "eg:Pizza Hut";break;
           case "to_direction_input"  : defaultV = "eg:Okhla Phase 3,New Delhi";break;
       }
       element.value = (tempElem == "")? defaultV : element.value;
    }
