// Global oMap object is instantiated in mapplet.js file.
// Remember check that applet and plugin are fully loaded(oMap.bAppletReady) before calling any applet method.

// Global variables.
var elResults = null;
var elInfo = null;

// Text messages for the client.
var txt_MoreThanOneResults  = "Valitse vaihtoehdoista oikea osoite, jotta saat näkyviin @450-laajakaistan tilanteen hakemallasi paikkakunnalla.";
var txt_NoResults           = "Antamillasi hakuehdoilla ei löytynyt tietoja. Tarkista antamasi hakuehdot. Jos haluat keskittää kartan tiettyyn katuosoitteeseen, käytä hakua muodossa \"Katuosoite 1, Kunta\". Jos haluat kartan sisältävän tietyn kunnan, voit kirjoittaa pelkän kunnan nimen hakukenttään. Voit käyttää myös pelkkää kadun nimeä (tai sen osaa) hakuehtona.";
//var txt_StartInfo         = "<b>Tervetuloa Digitan @450-karttapalveluun!</b><p>Voit hakea karttapalvelusta paikkakuntakohtaiset @450-laajakaistaverkon saatavuutta koskevat tiedot.</p><p>Haun voi tehdä joko osoitteen tai kunnan nimen perusteella. Kartalla voi liikkua lähennä- ja loitonna-painikkeilla. Karttaa voi tarkentaa siirtämällä hiiri kartan päälle ja käyttämällä hiiren rullanäppäintä tarkennukseen. Myös hiiren oikealla näppäimellä voi rajata haluamansa alueen tarkempaan tarkasteluun. Lisäohjeita löytyy Info-näppäintä painamalla.</p><p>Peittoaluekartta on ennuste @450-verkon peittoalueesta. Katvealueita voi esiintyä vaikka peittoaluekartan perusteella palvelun pitäisi olla saatavissa. Katvealueita saattavat aiheuttaa esimerkiksi radioaaltojen etenemistä haittaavat maastoesteet sekä kiinteistöjen rakennusmateriaalit.</p>";
var txt_Executing           = "<img src=\"/karttapalvelu/ajax/executing.gif\" style=\"margin-right: 5px\">Haetaan...";

var txt_legend1_1           = "Sisätiloissa, max 1 Mbit/s";
var txt_legend2_1           = "Ulkona, sisätiloissa ja mobiilikäytössä vaatii ulos sijoitettavan lisäantennin, max 1 Mbit/s";
var txt_legend3_1           = "Suuntaavalla antennilla, max 1 Mbit/s";

var txt_legend1_2           = "Sisätiloissa, max 2 Mbit/s";
var txt_legend2_2           = "Ulkona, sisätiloissa ja mobiilikäytössä vaatii ulos sijoitettavan lisäantennin, max 2 Mbit/s";
var txt_legend3_2           = "Suuntaavalla antennilla, max 2 Mbit/s";
var txt_legend4_2           = "Mahdollisuus saada maksimissaan 1M:n nopeus, katso tarkemmin 1M:n peittoaluekartta";

// Initialize user interface.
window.onload = function () {

    elResults = document.getElementById("results");
    elInfo = document.getElementById("resultsInfo");
    Karttapalvelu.Reset();
 //document.getElementById("StreetAddress").focus();
}

// UI javascript functions here are defined in associative array.
Karttapalvelu = {

    Reset: function () {

        // Reset map.
        if (oMap.bAppletReady) {
            oMap.goTo('HOME'); // Zoom back to finland view.
            oMap.geocodeClear(); // Clear possible streetname spots.
        }

        //keep coverage selection
        var cbo=document.getElementById('SelectCoverage');
        var coverage=cbo.options[cbo.selectedIndex].text;

        // Show introduction and hide results block.
        Karttapalvelu.ShowDefaultTextBlock();

        // Set form element default values.
        document.forms[0].reset();

        // Set the coverage
        Karttapalvelu.SelectCoverage(coverage);
    },

    ShowDefaultTextBlock: function() {
        // Show introduction and hide results block.
        var str=txt_StartInfo.replace("&lt;", "<");
        var str2=str.replace("&gt;", ">");
        Karttapalvelu.ShowTextBlock(elInfo, str2, "" ,true);
        Karttapalvelu.ShowTextBlock(elResults, "", "", false);
    },

    SelectCoverage: function (sCoverage) {
        var cbo=document.getElementById('SelectCoverage');
        if(sCoverage!=null) {
            for(i=0; i<cbo.options.length; i++) {
                if(cbo.options[i].text==sCoverage) {
                    cbo.selectedIndex=i;
                    break;
                }
            }
        }
        var coverage=cbo.options[cbo.selectedIndex].text;

        if(coverage.substr(0,1)=="1") {
            document.getElementById('legend_text1').innerHTML=txt_legend1_1;
            document.getElementById('legend_text2').innerHTML=txt_legend2_1;
            document.getElementById('legend_text3').innerHTML=txt_legend3_1;
            document.getElementById('legend_tr4').style.visibility="hidden";
        } else {
            document.getElementById('legend_text1').innerHTML=txt_legend1_2;
            document.getElementById('legend_text2').innerHTML=txt_legend2_2;
            document.getElementById('legend_text3').innerHTML=txt_legend3_2;
            document.getElementById('legend_text4').innerHTML=txt_legend4_2;
            document.getElementById('legend_tr4').style.visibility="visible";
        }

        if (!oMap.bAppletReady) return;
        var LAYER_INVISIBLE = 0;
        var LAYER_VISIBLE = 3;
        if(coverage.substr(0,1)=="1") {
            oMap.showLayer("L450_alueet_1", LAYER_VISIBLE);
            oMap.showLayer("L450_alueet_1g", LAYER_INVISIBLE);
            oMap.showLayer("L450_alueet_2", LAYER_INVISIBLE);
        } else {
            oMap.showLayer("L450_alueet_1", LAYER_INVISIBLE);
            oMap.showLayer("L450_alueet_1g", LAYER_VISIBLE);
            oMap.showLayer("L450_alueet_2", LAYER_VISIBLE);
        }
        oMap.refresh(false);
    },

    Search: function (sMunicipality) {

        // Check that Applet is available.
        if (!oMap.bAppletReady) return;

        oMap.goTo('HOME');      // Zoom back to finland view.
        oMap.geocodeClear();    // Clear possible streetname spots.

        // Show introduction and hide results block.
        Karttapalvelu.ShowDefaultTextBlock();

        //key phrase is given.
        if (sMunicipality.length > 0) {
            //streetname and municipality
            if(sMunicipality.indexOf(",")>0) {
              Karttapalvelu.ShowTextBlock(elInfo, txt_Executing, "" ,true);
              SearchAddress=sMunicipality.split(",")[0].replace(/^\s+|\s+$/g, '');
              SearchMunicipality=sMunicipality.split(",")[1].replace(/^\s+|\s+$/g, '');
              // Call Applet to get results and move map.
              oMap.geocode(SearchAddress, SearchMunicipality, 0);
            }
            //streetname / municipality only
            else {
                //looking for municiplaity
                retVal1 = oMap.goToMunicipalityByName(sMunicipality);
                if (retVal1==false)
                {
                    Karttapalvelu.ShowTextBlock(elInfo, txt_Executing, "" ,true);
                    //no municipality found -> looking for an address
                    oMap.geocode(sMunicipality, "", 0);

                    // "No results!" informative text.
                    //Karttapalvelu.ShowTextBlock(elInfo, txt_NoResults, "" ,true);

                    // Turn off the results label.
                    //Karttapalvelu.ShowTextBlock(elResults, "", "" ,false);
                }
            }

        }
        /*
        // Search only with municipality.
        else if (sStreetAddress.length == 0 && sMunicipality.length > 0) {

            retVal1 = oMap.goToMunicipalityByName(sMunicipality);

            if (retVal1==false)
            {
                // "No results!" informative text.
                Karttapalvelu.ShowTextBlock(elInfo, txt_NoResults, "" ,true);

                // Turn off the results label.
                Karttapalvelu.ShowTextBlock(elResults, "", "" ,false);
            }

        }
        */
    },

    ShowTextBlock: function (el, sText, sColor, bVisible) {

        if (!el) return;

        el.style.color = (sColor == "") ? "black" : sColor;
        el.innerHTML = sText;
        el.style.display = (bVisible) ? "block" : "none";

    },

    //
    // Handlers for events raised from Map class (oMap).
    //
    AppletEvents: {

        onGeogodingResults: function (resCnt) {

            var ZOOM_LEVEL_FOR_GEOCODING_RESULT = 6;
            var sResultsHtml = "";
            var sName = "";
            var sName2 = "";
            var sMunicipalityId = "";
            var x,y;
            var i = 0

            if (resCnt == 1) {

                // Show in map.
                oMap.oGeocoderResultModel.goTo('0', ZOOM_LEVEL_FOR_GEOCODING_RESULT, oMapConst.NO_INCREMENTAL_UPDATE);

                // Show introduction and hide results block.
                Karttapalvelu.ShowDefaultTextBlock();

            }
            else if (resCnt > 1) {

                // Create multiple results Html.
                if(resCnt > 0) {
                    sResultsHtml += "<ul>";
                    for(i = 0; i < resCnt; i++) {

                        sName = oMap.oGeocoderResultModel.getValueAt(i, oMapConst.COLUMN_GEOLOC_NAME);
                        sName2 = oMap.oGeocoderResultModel.getValueAt(i, oMapConst.COLUMN_GEOLOC_NAME2);

                        sMunicipalityId = "" + oMap.oGeocoderResultModel.getValueAt(i, oMapConst.COLUMN_GEOLOC_AREA_CODE);
                        //x = oMap.oGeocoderResultModel.getValueAt(i, oMapConst.COLUMN_GEOLOC_COORDX).doubleValue();
                        //y = oMap.oGeocoderResultModel.getValueAt(i, oMapConst.COLUMN_GEOLOC_COORDY).doubleValue();

                        x=decodeNumber(oMap.oGeocoderResultModel.getValueAt(i,oMapConst.COLUMN_GEOLOC_COORDX));
                        y=decodeNumber(oMap.oGeocoderResultModel.getValueAt(i,oMapConst.COLUMN_GEOLOC_COORDY));

                        if(sName2 != null) sName += " - " + sName2;

                        sName += ", " + oMap.oGeocoderResultModel.getValueAt(i, oMapConst.COLUMN_GEOLOC_AREA);

                        sResultsHtml += "<li><a href=\"javascript:" +
                        "oMap.oGeocoderResultModel.goTo(" + i + "," + ZOOM_LEVEL_FOR_GEOCODING_RESULT + "," + oMapConst.NO_INCREMENTAL_UPDATE + ");" +
                        "\">" + sName + "</a></li>";

                    }
                    sResultsHtml += "</ul>";
                }

                // Multiple results text.
                Karttapalvelu.ShowTextBlock(elInfo, txt_MoreThanOneResults, "" ,true);

                // Turn on the results label and show results.
                Karttapalvelu.ShowTextBlock(elResults, sResultsHtml, "", true);

            }
            else {

                // "No results!" informative text.
                Karttapalvelu.ShowTextBlock(elInfo, txt_NoResults, "" ,true);

                // Turn off the results label.
                Karttapalvelu.ShowTextBlock(elResults, "", "" ,false);

            }

        }

    }
}

// Extend functionality of the String object to have trim() -method.
String.prototype.trim = function trim(){
    return /^(\s*)$/.test(this) ? "" : this.replace( /^(\s*)((.|\n)*)(\b\s*)$/, '$2' )
}

function startSearch(e) {
  if (!e) var e = window.event;
  with (e)
   //catching ENTER key press for submitting the search form
   if (e.keyCode)
      key = e.keyCode;
   else
      key = e.which;
   if(key==13){
     Karttapalvelu.Search(document.getElementById('StreetAddress').value, document.getElementById('Municipality').value);
   }
}
function decodeNumber(n) {
   if(typeof(n)=="number")
       return n;
   else
       return n.doubleValue();
}
