﻿var CONST_HTTP_SERVER = "http://virtualindia.msresearch.in/";
var CONST_SERVICE_METHOD = "Geocoderwebservice/service.asmx/coder";
var inputQuery;
var SearchResponseResult;
var startTime;
var strDesc = "";
var strName = "";
var polyOnMap;
var pushpinOnMap;
var polygonOnMap;
var regex;
var match;

function search(query) {

/****Uncomment this region when SQL Box is down and Geocoder isn't working***/

	//alert("Sorry, this service is temporarily unavailable."); return;

/***End of region***/

    $('#tabvanilla > ul').tabs("select", 1);
    
   // where = document.getElementById("Where");
    if ( query.value != null && query.value != "") {
        if ((query.value).length >= 200) {
            alert("query is very big, trim the query");
            return;
        }
          
       // alert("Processing request: " + query + "...");
        var xmlhttp = getXmlHttp();
         inputQuery = query.value;
        
        var url = CONST_HTTP_SERVER + CONST_SERVICE_METHOD;
        var arr = null;
        var jsonObj = null;
       
        if (xmlhttp) {
            try {
              
                xmlhttp.open("POST", url, true);
                xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                xmlhttp.onreadystatechange = function() { //anonymous function
                    if (xmlhttp.readyState == 4) {
                        code = xmlhttp.responseText;

                    
                        arr = getJSONPortion('"dllforgeocoder">', '</string>', code, 0);
                     
                        if (arr == "[]") {
                            alert("invalid String");
                            return;
                        }
                        try {
                            jsonObj = eval('(' + arr + ')');
                        }
                        catch (e) {
                        }
                        // alert(jsonObj);
                        if (jsonObj != null && jsonObj[0] == null) {
                            var tempJsonObj = jsonObj;
                            jsonObj = new Array(1);
                            jsonObj[0] = tempJsonObj;
                        }

                        searchResponse(jsonObj);
                    }
                };

              
             if (inputQuery.indexOf(':') != -1) {
                     regex = /{\d{1,3}.\d{1,}\u002C\d{1,3}.\d{1,}\u002C\d{1,3}.\d{1,}\u002C\d{1,3}.\d{1,}}/;
                    match = regex.exec(inputQuery);
                    if (match == null) //If there is no viewpoint information present after a : then add it automatically
                    {
                       
                       var EncodedQuery = encodeURIComponent(inputQuery); //url encoding
                       xmlhttp.send("query=" + EncodedQuery + " {" +
					                    Gmap.GetMapView().TopLeftLatLong.Longitude + ","
					                    + Gmap.GetMapView().BottomRightLatLong.Latitude + ","
					                    + Gmap.GetMapView().BottomRightLatLong.Longitude + ","
					                    + Gmap.GetMapView().TopLeftLatLong.Latitude + "}"
							                    );
                        
                    }
                    else             //Keep it as it is, already viewpoint information is there
                    {

                        var EncodedQuery = encodeURIComponent(inputQuery);
                        xmlhttp.send("query=" + EncodedQuery);
                    }
                }
                else {

                    var EncodedQuery = encodeURIComponent(inputQuery);
                    xmlhttp.send("query=" + EncodedQuery + " : {" +
					                    Gmap.GetMapView().TopLeftLatLong.Longitude + ","
					                    + Gmap.GetMapView().BottomRightLatLong.Latitude + ","
					                    + Gmap.GetMapView().BottomRightLatLong.Longitude + ","
					                    + Gmap.GetMapView().TopLeftLatLong.Latitude + "}"
											);

                  

               }
              
             
          
                startTime = new Date(); 
            }
            catch (e) {
                alert("Sorry, this service is temporarily unavailable.");
            }
        }
    }

}

// Gets an XmlHttp object, if the browser supports it.
function getXmlHttp() {
    var x = null;
    try { x = new ActiveXObject("Msxml2.XMLHTTP") }
    catch (e) {
        try { x = new ActiveXObject("Microsoft.XMLHTTP") }
        catch (e) { x = null }
    }
    if (!x && typeof XMLHttpRequest != "undefined") { x = new XMLHttpRequest() }
    return x;
}

//This function takes the response and separates results array that has been encoded in JSON notation
function getJSONPortion(starttxt, endtxt, whole, startchar) {
    var startPos;
    var endPos;
    var res = "";
    startPos = contains(starttxt, whole, startchar);
    if (startPos[0] == -1)
        alert("Location not found in the database.");
    endPos = contains(endtxt, whole, startPos[1]);
    
    res = whole.substring(startPos[1], endPos[0]);
     return res;
}

function contains(part, whole, startchar) {
    part = part.toLowerCase();
    whole = whole.toLowerCase();
    var starti;
    var ret = -1;
    var parlen = part.length;

    if (startchar == null)
    { starti = 0; }
    else
    { starti = startchar; }

    for (i = starti; i < whole.length; i++) {
        if (whole.substring(i, i + parlen) == part) {
            ret = i;
            break;
        }
    }
    var ArrRet = new Array();
    ArrRet[0] = ret;
    ArrRet[1] = ret + parlen;
    return ArrRet;
}


function searchResponse(response)
 {
   if (response == null)
    {
        alert("No results found.");
    }
   else 
    {
        searchContentPins = null;
        searchContent = "<tr><td style=\"border-bottom: solid 1px gray; width:'22px' height: 18px;\"><p class=\"Panel\" onmouseover=\"onMouseOver(this);\" onclick=\"searchClear();\" onmouseout=\"onMouseOut(this);\">Clear</p></td></tr>";
        searchPin = "";
        displaySearchPanel(searchContent, searchPin);

        var end = new Date();
        var difference = end.getTime() - startTime.getTime();
       
        var errorString = "Geocoder webservice response in " + difference + " milliseconds.";
        showError(errorString);
        searchPin = "<tr><td colspan='2' style=\"color:teal; font-size:14px;\" class=\"panelTextTitle\">" + encodeURIComponent(inputQuery) + "</td></tr>";

        SearchResponseResult = response;

        //+ Miyuru : Modified to suite new where term data structure
        j = 0;

        for (i in response) {
            searchPin += "<tr><td><table><tr><td VALIGN=\"top\" style=\"width: 22px; height: 18px; cursor:hand;\">";
           
            strDesc = "";
 
                
                    strDesc = "" + SearchResponseResult[i].rankedResult.MatchedTerms + " <br> " + (SearchResponseResult[i].rankedResult.Score ? " Score:" + SearchResponseResult[i].rankedResult.Score : " ");
                    strName = "" + SearchResponseResult[i].rankedResult.Name;
                    searchPin += "<img src=\"images/sites/searchPin.gif\" /></td>";
                    searchPin += "<td style=\"border-top: solid 1px #EFEFEF\"><p class=\"Panel\" onmouseover=\"onMouseOver(this);\" onclick=\"displaySearchPins(SearchResponseResult[" + i + "].pushPinArr, SearchResponseResult[" + i + "].rankedResult, '" + strName + "', '" + strDesc + "' );\" onmouseout=\"onMouseOut(this);\">" + (j + 1) + ". " + SearchResponseResult[i].rankedResult.Name + "</p>";
                    searchPin += "</td></tr></table></td></tr>";
               
          j++; //increment counter
      }
        document.getElementById('resultsTab').innerHTML = "Search Results ("+j+")"
        displaySearchPanel(searchContent, searchPin);
       

        
        //Pin the top most result on the map. This is a direct rendering of results, rather than waiting for user click on the
        //link on the scratch pad.
     
        renderResult(SearchResponseResult[0]);
      
     
    }
}

function renderResult(responseResult) {
    
            strDesc = "" + responseResult.rankedResult.MatchedTerms + " <br> " + (responseResult.rankedResult.Score ? " Score:" + responseResult.rankedResult.Score : " ");
            strName = "" + responseResult.rankedResult.Name;
            displaySearchPins(responseResult.pushPinArr, responseResult.rankedResult, strName, strDesc);
    
   
}

//clear the previous results on the next searchclick
function searchClearClick() {
    Gmap.DeleteAllPushpins();
    pushpinOnMap = false;
    Gmap.DeleteAllPolylines();
    polyOnMap = false;
    Gmap.DeleteAllPolygons();
    polygonOnMap = false;
}
// Description : Function used to calculate the center point of a given locality
// Returns : an array of two elements first with x second with y

function findCenter(rankedresult) {
    if (rankedresult.Shapes[0].ShapeType == 0) {
        x = rankedresult.Shapes[0].Points[0].X;
        y = rankedresult.Shapes[0].Points[0].Y;
    } else {
        x = rankedresult.BoundingBox.Left + (rankedresult.BoundingBox.Right - rankedresult.BoundingBox.Left) / 2;
        y = rankedresult.BoundingBox.Top + (rankedresult.BoundingBox.Bottom - rankedresult.BoundingBox.Top) / 2;
    }
    centerPoint = new Array();
    centerPoint[0] = roundNumber(x, 6);
    centerPoint[1] = roundNumber(y, 5);

    return centerPoint;
}
function roundNumber(value, decimalplaces) 
{
    return Math.round(value * Math.pow(10, decimalplaces)) / Math.pow(10, decimalplaces);
}
function onMouseOver(s) 
{
    s.style.textDecoration = 'underline';
}

function onMouseOut(s)
 {
    s.style.textDecoration = 'none';
}
//clear the results in the panel
function searchClear() {
    document.getElementById('resultsTab').innerHTML = "Search Results";
    searchResultsArray = new Array();
    searchResults = new Array();
    searchText = new Array();
    searchContentPins = null;
    searchContent = "<tr><td style=\"border-bottom: solid 1px gray; width:'150px'\"><p class=\"Panel\" onmouseover=\"onMouseOver(this);\" onclick=\"searchClear();\" onmouseout=\"onMouseOut(this);\">Clear</p></td></tr>";
    searchPin = "";
    displaySearchPanel(searchContent, searchPin);

}


