/******************************************************************************
 * @file    searchtool.js
 * @brief   This JavaScript file is used to create a tool
 *          that allows a user to search for features.
 * @author  Kyle Overby
 *
 *  $Revision: YMmaps_Development_koverby/2 $
 *  $Date: 2008/11/04 21:13:45 $
 *  $LastEditedBy: koverby $
 *
 * $Copyright: 2007-2008, Southwest Research Institute.  All rights reserved. $
 *****************************************************************************/

/******************************************************************************
 *  $Log: searchtool.js $
 *  Revision YMmaps_Development_koverby/2 2008/11/04 21:13:45 koverby
 *     Changed a element type to button.
 *  
 *
 *****************************************************************************/

/******************************************************************************
 * This Prototype class is used to create a widget that allows a user to
 * search for a specific feature.
 *
 * @author Kyle Overby
 * @since October 7th, 2008
 * @version $Revision: YMmaps_Development_koverby/2 $
 *****************************************************************************/
SearchTool = Class.create({

    /** Constructor */
    initialize:function(){

        /** If a MapTool passed in, associate it with Search Tool */
        if(arguments[0]) {
            this.mapTool = arguments[0];
        }
        else this.mapTool = null;

        /** Tracks the AJAX Call */
        this.searchToolAJAXCall = null;

        this.lastSearchResultList = new Array(0);

        this.searchToolHeader = Builder.node("div", {className:"searchToolHeader"});
        this.searchToolHeader.innerHTML = "Search for Wells, Borings and Other Features";

        this.searchToolLabel = Builder.node("div", {className:"searchLabel"});
        this.searchToolLabel.innerHTML = "Name:";
        this.searchToolInputName = Builder.node("input", {type:"text", size:"20", style:"font-size:16px;"});
        this.searchToolName = Builder.node("div", {className:"searchField"}, [this.searchToolInputName]);
        this.searchToolSearchButton = Builder.node("button", {type:"submit", style:"font-size:16px;"});
        this.searchToolSearchButton.innerHTML = "Search";
        this.searchToolSearch = Builder.node("div", {className:"searchButton"}, [this.searchToolSearchButton]);
        this.searchToolPanel = Builder.node("div", {className:"searchInputContainer"}, [this.searchToolLabel, this.searchToolName, this.searchToolSearch]);

        this.searchToolResultsList = Builder.node("div", {className: "searchToolResultsList"});
        this.searchToolResultsList.groupContainer = this.searchToolResultsList;

        this.searchToolWindow = Builder.node("div", {className: "searchToolWindow", style:"display:none;"}, [this.searchToolHeader, this.searchToolPanel, this.searchToolResultsList]);

        this.searchToolSearchButtonEvent = this.searchToolSearchButtonClicked.bindAsEventListener(this);
        Event.observe(this.searchToolSearchButton, "click", this.searchToolSearchButtonEvent);

        this.searchToolKeyPressEvent = this.handleKeyPress.bindAsEventListener(this);
        Event.observe(this.searchToolName, 'keydown', this.searchToolKeyPressEvent);
    },

    /** Used to set the Map Tool */
    setMapTool:function(mapTool) {
        this.mapTool = mapTool;
    },

    /** Submit an AJAX call when the submit search button is pressed */
    searchToolSearchButtonClicked:function() {

        /** Remove the old search results */
        this.clearSearchResults();

        var name = $F(this.searchToolInputName);

        /** If name is blank, print an error */
        if (name.blank()) {

            var featureListResponse = Builder.node("div", {style:"left:30px; padding-left:70px;"});
            featureListResponse.setStyle({color: "#FF0000"});
            featureListResponse.innerHTML = "No Name input in Search Field";
            this.searchToolResultsList.appendChild(featureListResponse);
            Effect.Pulsate(featureListResponse, {duration: 1.0, pulses: 2});

            this.searchToolWindow.setStyle({height: "120px"});
        }

        /** Otherwise perform search */
        else {

            /** Setup Search Parameters */
            var searchParamters = "type=name&name=" + name;

            /** Check to see if there is already an active call and abort if necessary*/
            if (this.searchToolAJAXCall)
                this.searchToolAJAXCall.abort();

            /** Make the AJAX Request to retrieve the missions that match the parameters */
            this.searchToolAJAXCall = new Ajax.Request("search",
                {method: "get",
                 requestHeaders: "application/json",
                 parameters: searchParamters,
                 asynchronous:true,
                 onSuccess: this.parseSearchToolResponse.bind(this)
                }
            );
        }
    },

    /** Parse the AJAX response */
    parseSearchToolResponse:function(transport){

        var response = transport.responseText.evalJSON();

        if (response.search == "Success") {

            this.searchToolResultsList.setStyle({color: "#000000"});

            var arrayIndex = 0;
            this.lastSearchResultList = new Array(response.featureList.size());

            response.featureList.each(function(feature) {

                /** Add the feature to the list features */
                this.lastSearchResultList[arrayIndex] = feature.name;
                arrayIndex++;

                /** If a valid MapTool is present, add the features to it */
                if (this.mapTool != null) {
                    this.mapTool.addFeatureToMap(feature, "#0000FF");
                    this.mapTool.addFeatureToSideBar(feature, this.searchToolResultsList);
                }

                else {
                    var featureElementText = Builder.node("div");
                    featureElementText.innerHTML = feature.name;
                    var featureElementGraphic = Builder.node("div", {className:"ymmapsFeatureImage"});
                    var featureElement = Builder.node("div", {className:"ymmapsFeature"}, [featureElementText, featureElementGraphic]);
                    this.searchToolResultsList.appendChild(featureElement);
                }

            }.bind(this));
        }

        else if (response.search == "NoFeature") {

            var featureListResponse = Builder.node("div", {style:"left:30px; padding-left:70px;"});
            featureListResponse.innerHTML = "No Features matched given Name";
            this.searchToolResultsList.appendChild(featureListResponse);
        }

        else if (response.search == "Failed") {

            var featureListResponse = Builder.node("div", {style:"left:30px; padding-left:70px;"});
            featureListResponse.setStyle({color: "#FF0000"});
            featureListResponse.innerHTML = "Error Occured";
            this.searchToolResultsList.appendChild(featureListResponse);
            Effect.Pulsate(featureListResponse, {duration: 1.0, pulses: 2});
        }

        else if (response.search == "FailedDB") {

            var featureListResponse = Builder.node("div", {style:"left:30px; padding-left:70px;"});
            featureListResponse.setStyle({color: "#FF0000"});
            featureListResponse.innerHTML = "Database Error Occured";
            this.searchToolResultsList.appendChild(featureListResponse);
            Effect.Pulsate(featureListResponse, {duration: 1.0, pulses: 2});
        }


        else if (response.search == "FailedJSON") {

            var featureListResponse = Builder.node("div", {style:"left:30px; padding-left:70px;"});
            featureListResponse.setStyle({color: "#FF0000"});
            featureListResponse.innerHTML = "JSON Error Occured";
            this.searchToolResultsList.appendChild(featureListResponse);
            Effect.Pulsate(featureListResponse, {duration: 1.0, pulses: 2});
        }

        /** Remove the current AJAX Request */
        this.searchToolAJAXCall = null;

        var listCount = 1;

        if (response.featureList)
            listCount = response.featureList.size();

        /** Calculate the new window height */
        var newHeight = 100 + 18 * listCount;


        if (newHeight > 600) {
            newHeight = 600;
            this.searchToolResultsList.setStyle({height: newHeight-100 + "px"});
        }

        /** Update the window height */
        this.searchToolWindow.setStyle({height: newHeight + "px"});
    },

    /**************************************************************************
     * This method is invoked to clear the search results and remove any
     * markers from the map.
     *************************************************************************/
    clearSearchResults:function() {

        /** Remove the old search results */
        if (this.mapTool != null)
            if (this.lastSearchResultList.size() != 0) {
                this.mapTool.removeSearchFeatures();
                this.lastSearchResultList = new Array(0);
            }

        /** Remove old result list entries */
        while (this.searchToolResultsList.childNodes[0])
            this.searchToolResultsList.removeChild(this.searchToolResultsList.childNodes[0]);
    },

    /**************************************************************************
     * This method is invoked when the enter key is pressed on the search field
     *************************************************************************/
    handleKeyPress:function(event) {

        /** Determine which key was pressed */
        var key = event.keyCode || event.which;

        /** If it is the enter key, attempt a search */
        if (key == 13)  {
            this.searchToolSearchButtonClicked();
        }
    },

    /** Cleanup timers and event monitors upon destruciton */
    destroy:function () {
        Event.stopObserving(this.searchToolSearchButton, "click", this.submitSearchButtonEvent);
    }
});