﻿/*
Name: dealerSearch.js
*/

// instantiate populate Exec objects (Geocoding, Spatial, Map)
var m_GeoExec = null;
var m_SearchExec = null;
var m_MapExec = null;

var m_dbLayerQuery = null;
var m_Map = null;
var m_ResultPoint = null;
var m_Mapoo = null;


/**********************************/
/* Global Dealer Search Functions */
/**********************************/

/*Function: startUp()

Assigns the MapQuest server and Proxy server variables and calls the startMap() function

Parameters:
   p_ProxyServerName : proxy server name
   p_ProxyServerPath : proxy server path
   p_ProxyServerPort : proxy server port

   p_GeoCodingServerName : MapQuest GeoCoding server name
   p_GeoCodingServerPath : MapQuest GeoCoding server path
   p_GeoCodingServerPort = MapQuest GeoCoding server port

   p_SpatServerName = MapQuest Spatial server name
   p_SpatServerPath = MapQuest Spatial server path
   p_SpatServerPort = MapQuest Spatial server port

   p_MapServerName = MapQuest Map server name
   p_MapServerPath = MapQuest Map server path
   p_MapServerPort = MapQuest Map server port

Returns:
None

*/
function startUp(p_ProxyServerName,
                    p_ProxyServerPath,
                    p_ProxyServerPort,
                    p_GeoCodingServerName,
                    p_GeoCodingServerPath,
                    p_GeoCodingServerPort,
                    p_SpatServerName,
                    p_SpatServerPath,
                    p_SpatServerPort,
                    p_MapServerName,
                    p_MapServerPath,
                    p_MapServerPort) {

    // instantiate populate Exec objects (Geocoding, Spatial, Map)
    m_GeoExec = new MQExec(p_GeoCodingServerName, p_GeoCodingServerPath, p_GeoCodingServerPort, p_ProxyServerName, p_ProxyServerPath, p_ProxyServerPort);
    m_SearchExec = new MQExec(p_SpatServerName, p_SpatServerPath, p_SpatServerPort, p_ProxyServerName, p_ProxyServerPath, p_GeoCodingServerPort);
    m_MapExec = new MQExec(p_MapServerName, p_MapServerPath, p_MapServerPort, p_ProxyServerName, p_ProxyServerPath, p_GeoCodingServerPort);
}

/*Function: getResults()

Geocodes the origin of the search, and call search function

Parameters:
none

Returns:
none
*/
var resultsHold = "";
function getResults() {
document.getElementById("resultsDisplay").innerHTML = "";
resultsHold = "";
    // if map object is null then instantiate
    if (m_Map == null) {
        m_Map = new MQA.TileMap(document.getElementById('mapWindow'));
        myLZControl = new MQA.LargeZoomControl(m_Mapoo);
        m_Map.getDeclutter().setDeclutterMode(2);
        m_Map.addControl(myLZControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(20, 20)));
    }

    // remove any shapes on existing map
    m_Map.removeAllShapes();

    // remove rows from result table
    removeResultRows();

    // geocode the address                                  
    var address = new MQAddress();
    var gaCollection = new MQLocationCollection();
    var postalCode = ""
    var city = ""
    var state = ""

    // evaluate user entry
    if (document.getElementById("postal").value == "Enter Zip Code") {
        postalCode = "";
    }
    else {
        postalCode = document.getElementById("postal").value;
    }

    if (document.getElementById("city").value == "Enter City") {
        city = "";
    }
    else {
        city = document.getElementById("city").value;
    }

    if (document.getElementById("state").value == "Select a State") {
        state = "";
    }
    else {
        state = document.getElementById("state").value
    }

    if (postalCode == "" && city == "" && state == "") {
        alert("Please enter location to search.");
        return;
    }
    else if (postalCode == "" && city == "" && state != "") {
        alert("Please enter city.");
        return;
    }
    else if (postalCode == "" && city != "" && state == "") {
        alert("Please enter state.");
        return;
    }

    if (postalCode == "") {
        address.setCity(city);
        address.setState(state);
    }
    else {
        address.setPostalCode(postalCode);
    }

    address.setCountry("US");

    // geo code the results based on what the user has entered
    m_GeoExec.geocode(address, gaCollection);

    // get the first geocode result - this will be used as the origin
    var geoAddr = gaCollection.get(0);

    // create a variable for the origin of the search
    var origin = geoAddr.getMQLatLng();

    // assign a feature collection with return value from the doSearch function
    var searchRes = new doSearch(origin);

    // map the orgin
    var originPoint = new MQA.Poi(origin);
    originPoint.setValue('key', 'origin');
    m_Map.addShape(originPoint);

    // add header row to result grid
    if (searchRes.getSize() > 0) {

        // add a row to the rows collection and get a reference to the newly added row
//        var oTable = document.getElementById("tblResults");

        // get the rowcount of the table and insert row at the bottom
//        var rowCount = oTable.rows.length;
//        var newRow = oTable.insertRow(rowCount);
//        var newAttS = document.createAttribute("class")
//        newAttS.nodeValue="header"
//        newRow.setAttributeNode(newAttS);
        // insert header row
//        var oCell = newRow.insertCell(0);
//        var newAttr = document.createAttribute("colspan")
//        newAttr.nodeValue = "2"
//        oCell.setAttributeNode(newAttr);
//        oCell.innerHTML = "Location";

//        var oCell = newRow.insertCell(1);
//        var newAttr = document.createAttribute("style")
//        newAttr.nodeValue = "text-align:right"
//        oCell.setAttributeNode(newAttr);
//        oCell.innerHTML = "Distance (miles)";
        
        resultsHold += "<table cellpadding='0' cellspacing='0' border='0' id='tblResults'>";
        resultsHold += "<tr class='header'><td colspan='2'>Location</td><td align='right'>Distance (miles)</td></tr>"
        //document.getElementById("resultsDisplay").innerHTML = "";
        
    }
    
    // iterate though the results, creating a POI out of each one
    var moreInfo = getMoreInfo(searchRes);
    for (var i = 0; i < searchRes.getSize(); i++) {
       
        // need to "line up" the moreInfo recordset with the search results
        while (!moreInfo.isEOF()) {

            if (moreInfo.getField("I") == searchRes.getAt(i).getKey().toString()) {
                break;
            }
            moreInfo.moveNext();
        }

        var numberLabel = String(i + 1);
        // TODO: add path below to a config setting
        var iconPath = 'http://www.pioneerelectronics.com/piocda/templates/images/pio/mq_icons/' + numberLabel + '.png';
        resultPoint = searchRes.get(i);
        poi = new MQA.Poi(resultPoint.getCenterLatLng());
        poi.setValue('infoTitleHTML', resultPoint.getName());
        poi.setValue('infoContentHTML', moreInfo.getField('address') + '<br />' + moreInfo.getField('city') + ', ' + moreInfo.getField('state') + ' ' + moreInfo.getField('postal') + '<br />' + moreInfo.getField('Phone'));
        poi.setValue('icon', new MQA.Icon(iconPath, 29, 29));
        poi.setValue('key', resultPoint.getKey());
        m_Map.addShape(poi);

        // add row to Results table for display purposes
        addResultRow(moreInfo, resultPoint);

        moreInfo.moveFirst();
    }
//THIS NEED REPLACING -------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------
    var resultCount = document.getElementById("resultsDisplayColumn");
    if (searchRes.getSize() > 0) {
        if (numberLabel != null) {
        resultCount.innerHTML = numberLabel + ' Results Found';
        } else {
            resultCount.innerHTML = 'No Results Found';
        }
    }
    else {
        resultCount.innerHTML = 'No Results Found';
    }

    // add header row to result grid
    if (searchRes.getSize() > 0) {

//        var oLabel = document.getElementById("lblRadius");
//        var newAttr = document.createAttribute("style");
//        newAttr.nodeValue = "text-align:right; visibility:visible";
//        oLabel.setAttributeNode(newAttr);

        //var oDropDown = document.getElementById("ddlRadius");
        //var newAttr = document.createAttribute("style");
        //newAttr.nodeValue = "visibility:visible";
        //oDropDown.setAttributeNode(newAttr);
        document.getElementById("ddlRadius").style.visibility = "visible";
    }
//---------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------
    
    m_Map.bestFit();
    var zoomValue = m_Map.getZoomLevel();
    m_Map.setZoomLevel(zoomValue - 1);
    resultsHold += "</table>";

document.getElementById("resultsDisplay").innerHTML = resultsHold;
}

/*Function: getMoreInfo()

Returns a recordset of information contained within MapQuest server search results

Parameters:
MapQuest search results object

Returns:
MapQuest record set object
*/

function getMoreInfo(searchRes) {
    var ids = new MQStringCollection();
    var moreInfo = new MQRecordSet();
    var fields = new MQStringCollection();
    for (i = 0; i < searchRes.getSize(); i++) {
        ids.add(searchRes.getAt(i).getKey());
    }
    m_SearchExec.getRecordInfo(fields, m_dbLayerQuery, moreInfo, ids);

    return moreInfo;
}

/*Function: getMoreInfo()

set up search parameters and search
returns search results(featurecollection)

Parameters:
MapQuest spatial map object

Returns:
MapQuest search results object
*/

function doSearch(LLobj) {

    // set up the SearchCriteria - centerLL and Latlng
    var sCriteria = new MQRadiusSearchCriteria();

    sCriteria.setMaxMatches(25);

    sCriteria.setCenter(LLobj);

    sCriteria.setRadius(document.getElementById("radius").value);

    // setup search source - in the case, the Test DB table
    var dbLayerQueryCollection = new MQDBLayerQueryCollection();
    m_dbLayerQuery = new MQDBLayerQuery();

    // build search criteria
    var model = document.getElementById("model").value;
    var searchStr = getFilterExpression("IsDlr", "P20532", model);

    m_dbLayerQuery.setExtraCriteria(searchStr);
    m_dbLayerQuery.setDBLayerName("MQA.MQ_34393_dealers_USA");
    dbLayerQueryCollection.add(m_dbLayerQuery);

    //empty FeatureCollection to hold the search results
    var searchResults = new MQFeatureCollection();

    // search!
    m_SearchExec.search(sCriteria, searchResults, '', dbLayerQueryCollection);

    return searchResults;
}


/*Function: StringBuilder()

Initializes a new instance of the StringBuilder class
and appends the given value if supplied and prototype defs

Parameters:
value to append to string

Returns:
concatenated string result
*/

// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function(value) {
    if (value) {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.clear = function() {
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.toString = function() {
    return this.strings.join("");
}

/*Function: getFilterExpression()

Get the WHERE clause of the sql statement to query category/models

Parameters:
storeType : string containing type of store (ie. dealer)
category : string containing the category of store (ie. Pioneer DJ)
model: string containing the model number

Returns:
string result containing the where clause to use in the filter expression
*/

function getFilterExpression(storeType, category, model) {
    sb = new StringBuilder();
    if (category != null && category != "") {
        sb.append("(");
        for (i = 1; i <= 2; i++) {
            if (i > 1)
                sb.append(" OR ");
            sb.append(" categories");
            sb.append(i);
            sb.append(" like '% ");
            sb.append(category);
            sb.append(" %'");
            sb.append(" OR ");
            sb.append(" categories");
            sb.append(i)
            sb.append(" like '% ")
            sb.append(category);
            sb.append("'");
        }
        sb.append(")");
    }

    if (model != null && model != "") {
        sb.append(" AND (");
        sb.append("model_");
        sb.append(category);
        sb.append(" like '% ");
        sb.append(model);
        sb.append(" %'");
        sb.append(" OR model_");
        sb.append(category);
        sb.append(" like '% ");
        sb.append(model);
        sb.append("'");
        sb.append(")");
    }

    return sb.toString();
}

/*Function: addResultRow(mqRecord, resPoint)

Adds search result rows to results table on dealer serach page

Parameters:
mqRecord : MapQuest Record object
resPoint : MapQuest Point object

Returns:
none
*/

function addResultRow(mqRecord, resPoint) {

    // add a row to the rows collection and get a reference to the newly added row
//    var oTable = document.getElementById("tblResults");

    // get the rowcount of the table and insert row at the bottom
//    var rowCount = oTable.rows.length;
//    var newRow = oTable.insertRow(rowCount);

    // add cell to display company name
//    var oCell = newRow.insertCell(0);
//    var newAttr = document.createAttribute("style")
//    newAttr.nodeValue = "text-align:right"
    
//    oCell.innerHTML = "<b>" + resPoint.getName() + "</b><br />" +
//		        mqRecord.getField('address') + '<br />' +
//		        mqRecord.getField('city') + ', ' +
//		        mqRecord.getField('state') + ' ' +
//		        mqRecord.getField('postal');

//    oCell = newRow.insertCell(1);
//    oCell.innerHTML = mqRecord.getField('Phone');

//    oCell = newRow.insertCell(2);
//    oCell.setAttributeNode(newAttr);
//    var result = Math.round(resPoint.getDistance() * 10) / 10;
//    oCell.innerHTML = result;
    
    resultsHold += "<tr><td align='left'>";
    resultsHold += "<b>" + resPoint.getName() + "</b><br />" +
		        mqRecord.getField('address') + '<br />' +
		        mqRecord.getField('city') + ', ' +
		        mqRecord.getField('state') + ' ' +
		        mqRecord.getField('postal');
    resultsHold += "</td>";
    resultsHold += "<td>"+mqRecord.getField('Phone')+"</td>"
    resultsHold += "<td align='right'>"+(Math.round(resPoint.getDistance() * 10) / 10)+"</td>";
    resultsHold += "</tr>";
}

/*Function: removeResultRows()

Removes all result rows from the results table

Parameters:
none

Returns:
none
*/

function removeResultRows() {
document.getElementById("resultsDisplay").innerHTML = "";
    //var tblResults = document.getElementById("tblResults");

    //if (tblResults.childElementCount > 0) {
    //    while (tblResults.hasChildNodes()) {
    //        tblResults.removeChild(tblResults.firstChild);
    //    }
    //}
}
