dojo.require("dojo.parser");
dojo.require("esri.map");
dojo.require("esri.toolbars.navigation");
dojo.require("dijit.form.Slider");

var gdMap, gdMapSlider, gdNavToolbar, gdCurrentNavToolbarMode, gdMapLayer, gdOvMapCountry, gdOvMapArea, gdOvMapCountryLayer;
var gdInitialPoiCount = null;
var gdMapLoadCount = 0;

// TODO: Implement client-side behaviour if map service is unavailable

var gdRequestCounter = 0;
var gdLastUpdateContentRequest = 0;
function gdDoCallback(callbackArgument)
{
    if(callbackArgument == "operation=updatecontent" || callbackArgument == "operation=sortlist")
    {
        dojo.style("gdMapPreloader", "visibility", "visible");
        dojo.style("gdTabPreloader", "visibility", "visible");
    }
    dijit.byId(gdClientData.elementIds.thePoiFilter).getCheckedCategories(function(items) {
        var cats = "";
        for(var i = 0, len = items.length; i < len; i++)
        {
            cats = cats + "|" + items[i]._S.getValue(items[i], "name");
        }
        if(cats.length > 0)
            cats = cats.substring(1);
        var requestId = (++gdRequestCounter);
        if(callbackArgument == "operation=updatecontent")
        {
            gdLastUpdateContentRequest = requestId;
            // Uncomment lines below to bypass fetching of content:
//            var response = {"requestId":requestId,"requestType":"updatecontent","responseType":"updatecontent","isArticleResultListAvailable" :false,"isProductResultListAvailable":false,"productList":{"totalCount":0,"shownCount":0,"maxCount":100 ,"isZoomInRequired":true,"checkedCategoryCount":79,"items":[]},"pois":[{"X":205091,"Y":6841282,"screenX" :299,"screenY":362,"index":1,"name":null,"htmlContent":"<div class=\"c_mappoimouseovermultiplepois\"  onclick=\"\" onclick=\"javascript:gdZoomToPoi(205091,6841282);;return false;\">   <div class=\"c_mappoimouseovermultiplepois_top \"></div>      <div class=\"c_mappoimouseovermultiplepois_content\">           <div class=\"leftfloating \">               <div class=\"c_map_multipleproductsheader\">483&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink\"><a href=\"\" onclick=\"javascript:gdZoomToPoi(205091,6841282 );;return false;\">Click to zoom in on area</a></div>          </div>          <div style=\"clear: both \"></div>      </div>      <div class=\"c_mappoimouseovermultiplepois_bottom\"></div>  </div>","icon" :{"defaultIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32},"hoverIcon" :{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32},"clickIcon":null},"iconHtml" :"&nbsp;&nbsp;483","stackIcon":{"defaultIcon":{"url":"/images/map/categories/stackLarge.gif","width" :58,"height":32},"hoverIcon":{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32},"clickIcon" :{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32}},"contentByCategory":"null"} ,{"X":216303,"Y":6639088,"screenX":301,"screenY":424,"index":2,"name":null,"htmlContent":"<div class =\"c_mappoimouseovermultiplepois\" onclick=\"\" onclick=\"javascript:gdZoomToPoi(216303,6639088);;return  false;\">   <div class=\"c_mappoimouseovermultiplepois_top\"></div>      <div class=\"c_mappoimouseovermultiplepois_content \">           <div class=\"leftfloating\">               <div class=\"c_map_multipleproductsheader\" >1981&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink\"><a href=\"\" onclick =\"javascript:gdZoomToPoi(216303,6639088);;return false;\">Click to zoom in on area</a></div>          </div>          <div style=\"clear: both\"></div>      </div>      <div class=\"c_mappoimouseovermultiplepois_bottom \"></div>  </div>","icon":{"defaultIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58 ,"height":32},"hoverIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32} ,"clickIcon":null},"iconHtml":"&nbsp;&nbsp;1981","stackIcon":{"defaultIcon":{"url":"/images/map/categories /stackLarge.gif","width":58,"height":32},"hoverIcon":{"url":"/images/map/categories/stackLarge.gif","width" :58,"height":32},"clickIcon":{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32}} ,"contentByCategory":"null"},{"X":-9527,"Y":6555989,"screenX":231,"screenY":452,"index":3,"name":null ,"htmlContent":"<div class=\"c_mappoimouseovermultiplepois\" onclick=\"\" onclick=\"javascript:gdZoomToPoi (-9527,6555989);;return false;\">   <div class=\"c_mappoimouseovermultiplepois_top\"></div>      <div  class=\"c_mappoimouseovermultiplepois_content\">           <div class=\"leftfloating\">               <div class=\"c_map_multipleproductsheader\">374&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink \"><a href=\"\" onclick=\"javascript:gdZoomToPoi(-9527,6555989);;return false;\">Click to zoom in on  area</a></div>          </div>          <div style=\"clear: both\"></div>      </div>      <div class =\"c_mappoimouseovermultiplepois_bottom\"></div>  </div>","icon":{"defaultIcon":{"url":"/images/map/symbols /vn_map_poipointer.png","width":58,"height":32},"hoverIcon":{"url":"/images/map/symbols/vn_map_poipointer .png","width":58,"height":32},"clickIcon":null},"iconHtml":"&nbsp;&nbsp;374","stackIcon":{"defaultIcon" :{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32},"hoverIcon":{"url":"/images/map /categories/stackLarge.gif","width":58,"height":32},"clickIcon":{"url":"/images/map/categories/stackLarge .gif","width":58,"height":32}},"contentByCategory":"null"},{"X":36355,"Y":6773697,"screenX":245,"screenY" :383,"index":4,"name":null,"htmlContent":"<div class=\"c_mappoimouseovermultiplepois\" onclick=\"\" onclick =\"javascript:gdZoomToPoi(36355,6773697);;return false;\">   <div class=\"c_mappoimouseovermultiplepois_top \"></div>      <div class=\"c_mappoimouseovermultiplepois_content\">           <div class=\"leftfloating \">               <div class=\"c_map_multipleproductsheader\">796&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink\"><a href=\"\" onclick=\"javascript:gdZoomToPoi(36355,6773697 );;return false;\">Click to zoom in on area</a></div>          </div>          <div style=\"clear: both \"></div>      </div>      <div class=\"c_mappoimouseovermultiplepois_bottom\"></div>  </div>","icon" :{"defaultIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32},"hoverIcon" :{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32},"clickIcon":null},"iconHtml" :"&nbsp;&nbsp;796","stackIcon":{"defaultIcon":{"url":"/images/map/categories/stackLarge.gif","width" :58,"height":32},"hoverIcon":{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32},"clickIcon" :{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32}},"contentByCategory":"null"} ,{"X":102726,"Y":6976529,"screenX":267,"screenY":320,"index":5,"name":null,"htmlContent":"<div class =\"c_mappoimouseovermultiplepois\" onclick=\"\" onclick=\"javascript:gdZoomToPoi(102726,6976529);;return  false;\">   <div class=\"c_mappoimouseovermultiplepois_top\"></div>      <div class=\"c_mappoimouseovermultiplepois_content \">           <div class=\"leftfloating\">               <div class=\"c_map_multipleproductsheader\" >442&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink\"><a href=\"\" onclick =\"javascript:gdZoomToPoi(102726,6976529);;return false;\">Click to zoom in on area</a></div>          </div>          <div style=\"clear: both\"></div>      </div>      <div class=\"c_mappoimouseovermultiplepois_bottom \"></div>  </div>","icon":{"defaultIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58 ,"height":32},"hoverIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32} ,"clickIcon":null},"iconHtml":"&nbsp;&nbsp;442","stackIcon":{"defaultIcon":{"url":"/images/map/categories /stackLarge.gif","width":58,"height":32},"hoverIcon":{"url":"/images/map/categories/stackLarge.gif","width" :58,"height":32},"clickIcon":{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32}} ,"contentByCategory":"null"},{"X":271476,"Y":7040484,"screenX":319,"screenY":299,"index":6,"name":null ,"htmlContent":"<div class=\"c_mappoimouseovermultiplepois\" onclick=\"\" onclick=\"javascript:gdZoomToPoi (271476,7040484);;return false;\">   <div class=\"c_mappoimouseovermultiplepois_top\"></div>      <div  class=\"c_mappoimouseovermultiplepois_content\">           <div class=\"leftfloating\">               <div class=\"c_map_multipleproductsheader\">331&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink \"><a href=\"\" onclick=\"javascript:gdZoomToPoi(271476,7040484);;return false;\">Click to zoom in on  area</a></div>          </div>          <div style=\"clear: both\"></div>      </div>      <div class =\"c_mappoimouseovermultiplepois_bottom\"></div>  </div>","icon":{"defaultIcon":{"url":"/images/map/symbols /vn_map_poipointer.png","width":58,"height":32},"hoverIcon":{"url":"/images/map/symbols/vn_map_poipointer .png","width":58,"height":32},"clickIcon":null},"iconHtml":"&nbsp;&nbsp;331","stackIcon":{"defaultIcon" :{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32},"hoverIcon":{"url":"/images/map /categories/stackLarge.gif","width":58,"height":32},"clickIcon":{"url":"/images/map/categories/stackLarge .gif","width":58,"height":32}},"contentByCategory":"null"},{"X":447052,"Y":7464236,"screenX":375,"screenY" :166,"index":7,"name":null,"htmlContent":"<div class=\"c_mappoimouseovermultiplepois\" onclick=\"\" onclick =\"javascript:gdZoomToPoi(447052,7464236);;return false;\">   <div class=\"c_mappoimouseovermultiplepois_top \"></div>      <div class=\"c_mappoimouseovermultiplepois_content\">           <div class=\"leftfloating \">               <div class=\"c_map_multipleproductsheader\">256&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink\"><a href=\"\" onclick=\"javascript:gdZoomToPoi(447052,7464236 );;return false;\">Click to zoom in on area</a></div>          </div>          <div style=\"clear: both \"></div>      </div>      <div class=\"c_mappoimouseovermultiplepois_bottom\"></div>  </div>","icon" :{"defaultIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32},"hoverIcon" :{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32},"clickIcon":null},"iconHtml" :"&nbsp;&nbsp;256","stackIcon":{"defaultIcon":{"url":"/images/map/categories/stackLarge.gif","width" :58,"height":32},"hoverIcon":{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32},"clickIcon" :{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32}},"contentByCategory":"null"} ,{"X":633495,"Y":7699716,"screenX":434,"screenY":92,"index":8,"name":null,"htmlContent":"<div class= \"c_mappoimouseovermultiplepois\" onclick=\"\" onclick=\"javascript:gdZoomToPoi(633495,7699716);;return  false;\">   <div class=\"c_mappoimouseovermultiplepois_top\"></div>      <div class=\"c_mappoimouseovermultiplepois_content \">           <div class=\"leftfloating\">               <div class=\"c_map_multipleproductsheader\" >24&nbsp;listings </div>              <div class=\"c_map_multiplepoiszoomlink\"><a href=\"\" onclick =\"javascript:gdZoomToPoi(633495,7699716);;return false;\">Click to zoom in on area</a></div>          </div>          <div style=\"clear: both\"></div>      </div>      <div class=\"c_mappoimouseovermultiplepois_bottom \"></div>  </div>","icon":{"defaultIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58 ,"height":32},"hoverIcon":{"url":"/images/map/symbols/vn_map_poipointer.png","width":58,"height":32} ,"clickIcon":null},"iconHtml":"&nbsp;&nbsp;24","stackIcon":{"defaultIcon":{"url":"/images/map/categories /stackLarge.gif","width":58,"height":32},"hoverIcon":{"url":"/images/map/categories/stackLarge.gif","width" :58,"height":32},"clickIcon":{"url":"/images/map/categories/stackLarge.gif","width":58,"height":32}} ,"contentByCategory":"null"}],"poiCount":[{"name":"3446257","count":2930},{"name":"3446275","count":937 },{"name":"3446384","count":106},{"name":"3446835","count":146},{"name":"3447496","count":174},{"name" :"3446282","count":203},{"name":"3446632","count":84},{"name":"3447321","count":207},{"name":"3446503" ,"count":142},{"name":"3447157","count":73},{"name":"3447866","count":43},{"name":"3448107","count":53 },{"name":"3447761","count":52},{"name":"3447038","count":33},{"name":"3447796","count":21},{"name":"3447922" ,"count":28},{"name":"3448169","count":1021},{"name":"3448176","count":342},{"name":"3448919","count" :404},{"name":"3448596","count":350},{"name":"3449080","count":5},{"name":"3448498","count":81},{"name" :"3449773","count":371},{"name":"3449954","count":115},{"name":"3450027","count":32},{"name":"3449780" ,"count":289},{"name":"3450125","count":9},{"name":"3449143","count":788},{"name":"3449297","count":531 },{"name":"3449150","count":402},{"name":"3449724","count":209},{"name":"3449752","count":52},{"name" :"3450139","count":183},{"name":"3450804","count":64},{"name":"3450517","count":10},{"name":"3450146" ,"count":56},{"name":"3450391","count":28},{"name":"3450293","count":23},{"name":"3450867","count":16 },{"name":"3450552","count":12},{"name":"3450755","count":16},{"name":"3450643","count":13},{"name":"3450720" ,"count":7},{"name":"3451956","count":270},{"name":"3453286","count":0},{"name":"3452992","count":75 },{"name":"3453188","count":4},{"name":"3453153","count":1},{"name":"3452999","count":55},{"name":"3453223" ,"count":23},{"name":"3451974","count":106},{"name":"3452338","count":52},{"name":"3451981","count":17 },{"name":"3452149","count":21},{"name":"3452072","count":14},{"name":"3452093","count":4},{"name":"3452184" ,"count":4},{"name":"3452226","count":5},{"name":"3452303","count":0},{"name":"3452607","count":60}, {"name":"3452873","count":22},{"name":"3452670","count":26},{"name":"3452614","count":8},{"name":"3452908" ,"count":6},{"name":"3452359","count":50},{"name":"3452366","count":14},{"name":"3452408","count":9} ,{"name":"3452457","count":13},{"name":"3452520","count":2},{"name":"3452586","count":17},{"name":"3451525" ,"count":109},{"name":"3451690","count":81},{"name":"3451844","count":8},{"name":"3451795","count":24 },{"name":"3451697","count":12},{"name":"3451872","count":5},{"name":"3451739","count":28},{"name":"3451893" ,"count":9},{"name":"3451543","count":27},{"name":"3451585","count":26},{"name":"3451571","count":3} ,{"name":"3451550","count":0},{"name":"3451669","count":0},{"name":"3450951","count":1380},{"name":"3450969" ,"count":546},{"name":"3451102","count":257},{"name":"3451434","count":84},{"name":"3451235","count" :623},{"name":"3451186","count":234},{"name":"3451053","count":156},{"name":"3451413","count":79},{"name" :"3451483","count":30},{"name":"3451504","count":46},{"name":"3451903","count":108}],"articleListHtml" :"<div class='map_morearticles'>There are more than 90 articles related to this area. Zoom in to view  articles.</div>","articleListHeaderHtml":"990&nbsp;articles related to area"};
//            gdProcessCallbackResults(response);
//            return;
        }
        callbackArgument += "&extent=" + gdMap.extent.xmin + ":" + gdMap.extent.ymin + ":" + gdMap.extent.xmax + ":" + gdMap.extent.ymax;
        callbackArgument += "&level=" + gdMap.getLevel();
        callbackArgument += "&scale=" + gdMapLayer.tileInfo.lods[gdMap.getLevel()].scale;
        callbackArgument += "&mapWidth=" + gdMap.width;
        callbackArgument += "&mapHeight=" + gdMap.height;
        callbackArgument += "&sortby=" + dojo.byId(gdClientData.elementIds.productListSortBy).value;
        callbackArgument += "&languageCode=" + gdClientData.languageCode;
        callbackArgument += "&selectedProductId=" + gdClientData.selectedProductId;
        callbackArgument += "&requestId=" + requestId;
        callbackArgument += "&seasonId=" + gdClientData.selectedProductId;
        callbackArgument += "&categories=" + cats;
        gdInvokeCallback(callbackArgument);
    });
}

function gdProcessCallbackResults(results)
{
    var r = null;
    try
    {
        eval("r = " + results + ";");
    }
    catch(ex)
    {
        alert('Invalid response: ' + ex);
    }
    if(r == null) return;
    if(r.responseType == "error")
    {
        gdHidePrintPreLoaders();
        gdHidePreLoaders();
        alert(r.error);
    }
    else if(r.responseType == "updatecontent")
    {
        gdHidePreLoaders();
        gdProcessUpdateContentResponse(r);
    }
    else if(r.responseType == "print")
    {
        gdHidePrintPreLoaders();
        gdProcessPrintResponse(r);
    }
    else
    {
        gdHidePrintPreLoaders();
        gdHidePreLoaders();
        alert('Unknown response type: ' + r.responseType);
    }
}

function gdHidePrintPreLoaders()
{
    dojo.forEach(gdClientData.elementIds.printPreloaderIds, function(item) {
        dojo.style(item, "visibility", "hidden");
    });
}

function gdHidePreLoaders()
{
    dojo.style("gdMapPreloader", "visibility", "hidden");
    dojo.style("gdTabPreloader", "visibility", "hidden");
}

function gdProcessPrintResponse(response)
{
    if(response.requestType == "print")
        ShowMapPrintPreview(response.url);
    else if(response.requestType == "email")
        SendMapEmail(response.url);
}

function gdProcessUpdateContentResponse(response)
{
    if((response.requestType == "updatecontent") && (gdLastUpdateContentRequest > response.requestId))
    {
        // There is a more recent update content request pending, ignore the current response and wai t for the pending response.
        return;
    }
    updateProductList(response.productList);
    if(response.requestType == "updatecontent")
    {
        dijit.byId(gdClientData.elementIds.thePoiFilter).updatePoiCount(response.poiCount);
        dojo.byId(gdClientData.elementIds.articleListDiv).innerHTML = response.articleListHtml;
        dojo.byId(gdClientData.elementIds.articleListHeaderDiv).innerHTML = response.articleListHeaderHtml;
        gdEnableArticleListing = response.isArticleResultListAvailable;
        gdEnableProductListing = response.isProductResultListAvailable;
        gdPrintListOptionsClick();
        if(response.isProductResultListAvailable)
        {
            dojo.byId("gdPrintProductsLink").innerHTML = gdGetText("/map/print/printproducts");
        }
        else
        {
            dojo.byId("gdPrintProductsLink").innerHTML = gdGetText("/map/print/printmap");
        }
        if(response.isArticleResultListAvailable)
        {
            dojo.byId("gdPrintArticlesLink").innerHTML = gdGetText("/map/print/printarticles");
        }
        else
        {
            dojo.byId("gdPrintArticlesLink").innerHTML = gdGetText("/map/print/printmap");
        }
        if(response.selectedPoi)
            gdClientData.selectedPoi = response.selectedPoi;
        geodata.maptips.currentMapTipsLayer.addMapTips(response.pois, gdClientData.selectedPoi);
    }
}

function updateProductList(pl)
{
    var html = "";
    var poiFilterFooter = dojo.byId(gdClientData.elementIds.poiFilterFooter);
    var maxHits = dojo.byId(gdClientData.elementIds.productListMaxHits);
    var maxHitsDiv = dojo.byId(gdClientData.elementIds.productListMaxHitsDiv);
    var productList = dojo.byId(gdClientData.elementIds.productList);
    var sortBy = dojo.byId(gdClientData.elementIds.productListSortBySpan);
    gdSetElementVisibility(maxHitsDiv, false);
    gdSetElementVisibility(sortBy, pl.totalCount > 0);
    if(pl.totalCount < 1)
    {
        poiFilterFooter.innerHTML = gdGetText("/map/poifilterfooternooffers");
    }
    else
    {
        poiFilterFooter.innerHTML = gdGetText("/map/poifilterfooter").replace("{0}", pl.totalCount);
    }
    if(pl.isZoomInRequired)
    {
        maxHits.innerHTML = "";
        html += gdGetText("/map/poifilterfooterzoomin");
    }
    else
    {
        if(pl.totalCount > pl.maxCount)
        {
            maxHits.innerHTML = gdGetText("/map/poifilterfootermaxhits").replace("{0}",pl.maxCount);
            gdSetElementVisibility(maxHitsDiv, true);
        }
        else
        {
            maxHits.innerHTML = "";
        }
        if(pl.totalCount < 1)
        {
            if(pl.checkedCategoryCount < 1)
                html += gdGetText("/map/poifilterfooterselectcategories");
            else
                html += gdGetText("/map/poifilterfooterzoomout");
        }
        else
        {
            for(var i = 0, len = pl.items.length; i < len; i++)
            {
                html += pl.items[i].htmlContent;
            }
        }
    }
    productList.innerHTML = html;
}

function gdSetElementVisibility(elem, visible)
{
    if(visible)
    {
        dojo.style(elem, "display", "");
        dojo.style(elem, "visibility", "");
    }
    else
    {
        dojo.style(elem, "display", "none");
        dojo.style(elem, "visibility", "hidden");
    }
}

function gdGetText(textId)
{
    for(var i = 0, len = gdClientData.texts.length; i < len; i++)
    {
        var t = gdClientData.texts[i];
        if(t.textId == textId)
            return t.text;
    }
    return "";
}

function gdGetTooltip(textId)
{
    for(var i = 0, len = gdClientData.texts.length; i < len; i++)
    {
        var t = gdClientData.texts[i];
        if(t.textId == textId)
            return t.tooltip;
    }
    return "";
}

function gdSetupClient(clientData)
{
    gdSetWeatherCheckboxImage(false);
    gdLeftPaneTabIndex = clientData.activeLeftPaneTab;
    gdLeftPaneShowing = clientData.isLeftPaneShowing;
    ShowLeftPaneTab(gdLeftPaneTabIndex);
    ShowOvTab(clientData.activeOvMapsTab);
    gdPrintListOptionsClick();
    var sendToFriendIframe = document.getElementById('iFrameSendToFriend');
    if(sendToFriendIframe) { sendToFriendIframe.title = gdGetTooltip("/map/alt/sendmap"); }
}

function gdMapLoad()
{
    gdMapLoadCount++;
    if(gdMapLoadCount == 3)
    {
        gdSetupScalebar();
        // All maps have been loaded
        dojo.connect(gdOvMapArea, "onExtentChange", gdOvMapArea_extentChanged);
        dojo.connect(gdMap, "onExtentChange", gdMap_extentChanged);
        // Size of overview maps must be set manually, is erroneously set to 400x400 by JSAPI, probably when map div is not visible at creation time.
        gdOvMapCountry.width = 150;
        gdOvMapCountry.height = 170;
        gdOvMapArea.width = 150;
        gdOvMapArea.height = 170;
        gdOvMapCountry.disableMapNavigation();
        gdOvMapArea.disableMapNavigation();
        if(gdClientData.fullExtent != null)
        {
            gdOvMapCountry.setExtent(new esri.geometry.Extent(gdClientData.fullExtent.minx,gdClientData.fullExtent.miny,gdClientData.fullExtent.maxx,gdClientData.fullExtent.maxy,null));
        }
        gdSelectNavigationTool(esri.toolbars.Navigation.ZOOM_IN);
        geodata.maptips.setupMapTips(gdMap);
        if(gdClientData.initialCenterPoint != null)
        {
            gdZoomToInitialPoint();
        }
        else if(gdClientData.initialExtent != null)
        {
            var e = new esri.geometry.Extent(
                gdClientData.initialExtent.minx,
                gdClientData.initialExtent.miny,
                gdClientData.initialExtent.maxx,
                gdClientData.initialExtent.maxy,
                gdMap.spatialReference);
            gdZoomToExtent(gdMap, e);
        }
        else
        {
            gdMap_extentChanged();
        }
        // TODO: Activate correct tool based on initial extent?
    }
}

function gdZoomToExtent(map, extent)
{
    // Method map.setExtent() seems to adjust the envelope's aspect ratio,
    // possibly reducing the extent in the process, before doing the zoom,
    // even though the fit parameter is set to true. So we have to adjust the
    // envelope ourselves first to ensure that the entire extent is visible after the zoom.
    //map.setExtent(extent, true);
    var aspectRatio = map.extent.getWidth() / map.extent.getHeight();
    var eAspectRatio = extent.getWidth() / extent.getHeight();
    var c = extent.getCenter();
    if(aspectRatio > eAspectRatio)
    {
        // Map is wider than new extent, make the new extent wider
        var newWidth = extent.getWidth() * (aspectRatio / eAspectRatio);
        extent.update(c.x - newWidth / 2, extent.ymin, c.x - newWidth / 2 + newWidth, extent.ymax, extent.spatialReference);
    }
    else {
        // Map is taller than new extent, make the new extent taller
        var newHeight = extent.getHeight() * (eAspectRatio / aspectRatio);
        extent.update(extent.xmin, c.y - newHeight / 2, extent.xmax, c.y - newHeight / 2 + newHeight, extent.spatialReference);
    }
    extent = extent.expand(gdClientData.zoomExpandFactor);
    map.setExtent(extent, true);
}

function gdZoomToInitialPoint()
{
    gdMap.centerAndZoom(new esri.geometry.Point(gdClientData.initialCenterPoint.x, gdClientData.initialCenterPoint.y, null), gdClientData.initialLevel);
}

function gdOvMapArea_extentChanged()
{
    gdPositionAoi(gdMap, gdOvMapArea, 'ovMapAreaAOI');
}

function gdScalebarClick()
{
    gdClientData.useMiles = !(gdClientData.useMiles);
    gdUpdateScalebar(true);
    return false;
}

function gdSetupScalebar()
{
    var sb = dojo.byId("gdMapScalebar");
    dojo.connect(sb, "onclick", gdScalebarClick);
    dojo.connect(sb, "onmouseover", function() {
        var img = dojo.byId("gdMapScalebarImage");
        img.src = "/images/map/malestokk1_mo.png";
    });
    dojo.connect(sb, "onmouseout", function() {
        var img = dojo.byId("gdMapScalebarImage");
        img.src = "/images/map/malestokk1.png";
    });
}

function gdUpdateScalebar(hover)
{
    var MetersPerMile = 1609.344;
    var YardsPerMile = 1760;
    
    var r = gdMapLayer.tileInfo.lods[gdMap.getLevel()].resolution;
    var yards = false;
    if (gdClientData.useMiles)
    {
        r = r / MetersPerMile;
        if (r*50 <= 1)
        {
            yards = true;
            r = r * YardsPerMile;
        }
    }

    var refUnit = r*50; // Width, in world units, of a scalebar of 50 pixels' width
    var b = 1; while(b*10 < refUnit) b *= 10;
    // b is largest 100...00 smaller than refUnit
    var maxValue = b;
    if (refUnit < b)
        maxValue = b;
    else if (refUnit < b * 2)
        maxValue = b * 2;
    else if (refUnit < b * 4)
        maxValue = b * 4;
    else if (refUnit < b * 8)
        maxValue = b * 8;
    else
        maxValue = b * 16;
    var width = maxValue / r;

    var unit = null;
    if (yards)
    {
        unit = gdGetText("/map/print/units/yards");
    }
    else if (gdClientData.useMiles)
    {
        unit = gdGetText("/map/print/units/miles");
    }
    else
    {
        if(maxValue > 1000)
        {
            maxValue = maxValue / 1000;
            unit = gdGetText("/map/print/units/km");
        }   
        else
        {
            unit = gdGetText("/map/print/units/meters");
        }
    }

    dojo.byId("gdMapScalebarText").innerHTML = maxValue + " " + unit;
    if(!dojo.isIE)
    {
        dojo.style("gdMapScalebarText", "padding", "0px 0px 2px 0px");
        dojo.style("gdMapScalebar", "padding", "5px 5px 5px 5px");
    }
    dojo.byId("gdMapScalebarImage").src = hover ? "/images/map/malestokk1_mo.png" : "/images/map/malestokk1.png";
    dojo.style("gdMapScalebarImage", "width", Math.round(width) + "px");
    dojo.style("gdMapScalebarImage", "visibility", "visible");
}

function gdMap_extentChanged()
{
    gdUpdateScalebar();
	gdPositionAoi(gdMap, gdOvMapCountry, 'ovMapCountryAOI');
	gdPositionAoi(gdMap, gdOvMapArea, 'ovMapAreaAOI');

    // Update extent of area overview map:
    var areaExt = gdMap.extent.expand(3.2);
    // Don't let area overview map zoom out beyond the country overview map:	    
    if(areaExt.getWidth() > gdOvMapCountry.extent.getWidth() || areaExt.getHeight() > gdOvMapCountry.extent.getHeight())
    {
        areaExt = gdOvMapCountry.extent.expand(1);
    }
    gdOvMapArea.setExtent(areaExt, true);

    gdMapSlider.setValue(gdMap.getLevel());
    gdDoCallback('operation=updatecontent');
    if (gdClientData.isShowingWeather) requestWeather();
}

function requestWeather() {
    // Request weather data:
    esri.request({
      url: gdClientData.weatherServiceUrl, 
      content:{
        maxPriority: weatherPrioritiesByLevel[gdMap.getLevel()],
        minX:Math.min(gdMap.extent.xmin,gdMap.extent.xmax),
        minY:Math.min(gdMap.extent.ymin,gdMap.extent.ymax),
        maxX:Math.max(gdMap.extent.xmin,gdMap.extent.xmax),
        maxY:Math.max(gdMap.extent.ymin,gdMap.extent.ymax)
        },
      callbackParamName:"callback",
      load: gdShowWeather, 
      error: esriConfig.defaults.io.errorHandler
    });
}

function gdShowWeather(weatherForecasts, io) {
    if (!gdClientData.isShowingWeather) weatherForecasts = [];
    var env = {
        minX:Math.min(gdMap.extent.xmin,gdMap.extent.xmax),
        minY:Math.min(gdMap.extent.ymin,gdMap.extent.ymax),
        maxX:Math.max(gdMap.extent.xmin,gdMap.extent.xmax),
        maxY:Math.max(gdMap.extent.ymin,gdMap.extent.ymax)
        };
    if (io.args.content.minX == env.minX && io.args.content.minY == env.minY && io.args.content.maxX == env.maxX && io.args.content.maxY == env.maxY)
    {
        // Map extent is the same as when the weather data was requested
        geodata.maptips.currentMapTipsLayer.addWeather(weatherForecasts);
    }
}
function gdSelectWeather() {
    gdClientData.isShowingWeather = !gdClientData.isShowingWeather;
    gdSetWeatherCheckboxImage(true);
    if (gdClientData.isShowingWeather){
    
        dojo.byId('txtWeatherTool').title = gdGetTooltip("/map/alt/hideweather");
        dojo.byId('imgSelectWeather').title = gdGetTooltip("/map/alt/hideweather");
        //dojo.byId('txtWeatherTool').innerHTML = "hepp"  //gdGetText("/map/hideweather");
      
       
 
        requestWeather();
        }
    else {
        dojo.byId('txtWeatherTool').title = gdGetTooltip("/map/alt/showweather");
        dojo.byId('imgSelectWeather').title = gdGetTooltip("/map/alt/showweather");
        //dojo.byId('txtWeatherTool').innerHTML = "xx"  //gdGetText("/map/showweather");
        geodata.maptips.currentMapTipsLayer.addWeather([]);
        geodata.maptips.currentMapTipsLayer.hideCurrentItem();
    }
}
function gdSetWeatherCheckboxImage(hover) {
    if (gdClientData.isShowingWeather)
        dojo.byId('imgSelectWeather').src = hover ? '/images/poifilter/checked_box_mouseover.png' : '/images/poifilter/checked_box.png';
    else
        dojo.byId('imgSelectWeather').src = hover ? '/images/poifilter/unchecked_box_mouseover.png' : '/images/poifilter/unchecked_box.png';
}

function gdSetToggleMapResize(hover) {
    gdLeftPaneShowing =!gdLeftPaneShowing;
    
    if (gdLeftPaneShowing)
        dojo.byId('imgToggleMap').src = hover ? '/images/map/toolbar/vn_largemap_out.png' : '/images/map/toolbar/vn_largemap_out.png';
    else
        dojo.byId('imgToggleMap').src = hover ? '/images/map/toolbar/vn_largemap_in.png' : '/images/map/toolbar/vn_largemap_in.png';
        
   
    ToggleLeftPane(gdLeftPaneShowing);
}

var weatherPrioritiesByLevel = [10,20,25,30,40,40,80,80,100,100,100,100,100,100,100,100,100,100,100];

function gdSelectNavigationTool(mode)
{
	gdCurrentNavToolbarMode = mode;
	gdNavToolbar.activate(gdCurrentNavToolbarMode);
	//gdSelectCurrent();
}

function gdZoomToPlace(place) {
    var a = place.split(':');
    gdClearMapTipsAndWeather();
    gdMap.centerAndZoom(new esri.geometry.Point(a[1]*1, a[2]*1, null), gdClientData.zoomToPlaceLevel);
}

function gdRepositionMap(map) {
    map.reposition();
    // There seems to be a bug in the reposition() method, it doesn't take
    // scrollbars into account. Workaround:
    var c = dojo.coords(map._root, true);
    map.position.x = c.x;
    map.position.y = c.y;
}

function gdWindowResize() {
    // As the map is placed inside a CENTER tag, its position changes when the window is resized.
    gdRepositionMap(gdMap);
}

function gdCloseAddressPanel_IE() {
    if(gdAddressPanelId != null) dojo.byId(gdAddressPanelId).style.display='none';
}
var gdAddressPanelId = null;
function gdProcessAddressCallbackResult_IE(result) {
    if(!result.resultId) eval('try{result='+result+';}catch(e) {}');
    if(result.resultId) {
        dojo.byId(result.panelId).innerHTML = "";
		var panelID = 
        gdAddressPanelId = result.panelId + "_IEWorkaround";
		var panel = dojo.byId(gdAddressPanelId);
		if (panel==null)
		{
			panel=document.createElement('div');
			panel.id=gdAddressPanelId;
			panel.style.position="absolute";
			panel.style.margin="0px";
			panel.style.display="none";
			panel.style.padding="0px";
			document.body.appendChild(panel);
		}
	    var c = dojo.coords(dojo.byId(result.panelId).parentNode);
		panel.style.zIndex=2000;
//		panel.style.width= c.w + "px";
//		panel.style.height= c.h + "px";
		panel.style.top= c.y + "px";
		panel.style.left= c.x + "px";
        panel.innerHTML = result.resultPanelHtml;
        panel.firstChild.style.display = 'block';
        panel.firstChild.style.visibility = 'visible';
		panel.style.display="block";
    }
}

function gdLayerError(err) {
    dojo.style("gdMapError", "visibility", "visible");
}

function gdInit() {
    if(dojo.isIE) {
        gdProcessAddressCallbackResult = gdProcessAddressCallbackResult_IE;
        gdCloseAddressPanel = gdCloseAddressPanel_IE;
    }
    
         // dojo versions later than 1.3.2 should be fine
                if (dojo.isFF == 3.5 && dojo.version.major == 1 && (dojo.version.minor < 3  || (dojo.version.minor == 3 && dojo.version.patch < 3))) {
                    var setRawNode = function(rawNode){
                    // summary:
                    //  assigns and clears the underlying node that will represent this
                    //  shape. Once set, transforms, gradients, etc, can be applied.
                    //  (no fill & stroke by default)
                    var r = this.rawNode = rawNode;
                    if (this.shape.type != "image") {
                        r.setAttribute("fill", "none");
                    }
                    r.setAttribute("fill-opacity", 0);
                    r.setAttribute("stroke", "none");
                    r.setAttribute("stroke-opacity", 0);
                    r.setAttribute("stroke-width", 1);
                    r.setAttribute("stroke-linecap", "butt");
                    r.setAttribute("stroke-linejoin", "miter");
                    r.setAttribute("stroke-miterlimit", 4);
                    };
                    dojox.gfx.Shape.prototype.setRawNode = setRawNode; 
                }
    gdAddressSelected = gdZoomToPlace;
    esriConfig.defaults.map.zoomDuration = 500; //time in milliseconds; default is 250
    esriConfig.defaults.map.zoomRate = 50; //refresh rate of zoom animation; default is 25
    gdSetupClient(gdClientData);
    
    gdMapLayer = new esri.layers.ArcGISTiledMapServiceLayer(gdClientData.mapServiceUrl);
    gdOvMapCountryLayer = new esri.layers.ArcGISDynamicMapServiceLayer(gdClientData.mapServiceUrl);
    var ovMapAreaLayer = new esri.layers.ArcGISDynamicMapServiceLayer(gdClientData.mapServiceUrl);
    dojo.connect(gdMapLayer, "onError", gdLayerError);
    dojo.connect(gdOvMapCountryLayer, "onError", gdLayerError);
    dojo.connect(ovMapAreaLayer, "onError", gdLayerError);

    gdMap = new esri.Map("gdMapDiv", { nav: false, slider: false });
    gdOvMapCountry = new esri.Map("ovMapCountryMapDiv", {nav: false, slider: false});
    gdOvMapArea = new esri.Map("ovMapAreaMapDiv", {nav: false, slider: false});
    gdNavToolbar = new esri.toolbars.Navigation(gdMap);
    
    dojo.connect(window, "onresize", gdWindowResize);
    dojo.connect(gdOvMapCountry, "onLoad", gdMapLoad);
    dojo.connect(gdOvMapArea, "onLoad", gdMapLoad);
    dojo.connect(gdMap, "onLoad", gdMapLoad);

    dojo.parser.parse();
    gdMapSlider = new dijit.form.VerticalSlider({
        name: "gdMapSlider",
        value: 0,
        onChange: gdMapSliderChange,
        maximum: 13,
        minimum: 0,
        discreteValues: 14,
        style: "height:" + (dojo.isIE || dojo.isOpera ? 68 : 112) + "px;"}, dojo.byId('gdMapSlider'));

    gdMap.addLayer(gdMapLayer);
    gdOvMapCountry.addLayer(gdOvMapCountryLayer);
    gdOvMapArea.addLayer(ovMapAreaLayer);
}

function gdPositionAoi(map, ovMap, aoiId)
{
    if(ovMap.extent == null || map.extent == null) return;
	var aoi = dojo.byId(aoiId);
	// xmin and xmax are sometimes swapped in the extent...
	var mx = map.extent.xmin; if(map.extent.xmax < mx) mx = map.extent.xmax;
	var my = map.extent.ymin; if(map.extent.ymax < my) my = map.extent.ymax;
	var omx = ovMap.extent.xmin; if(ovMap.extent.xmax < omx) omx = ovMap.extent.xmax;
	var omy = ovMap.extent.ymin; if(ovMap.extent.ymax < omy) omy = ovMap.extent.ymax;
	var mw = map.extent.getWidth(); var mh = map.extent.getHeight();
	var omw = ovMap.extent.getWidth(); var omh = ovMap.extent.getHeight();
	
	var width = mw * ovMap.width / omw;
	var height = mh * ovMap.height / omh;

	if(width > ovMap.width - 8) width = ovMap.width - 8;
	if(width < 1) width = 1;
	if(height > ovMap.height - 8) height = ovMap.height - 8;
	if(height < 1) height = 1;

	var left = (mx - omx) * ovMap.width / omw;
	var top = ovMap.height - height - (my - omy) * ovMap.height / omh;

	if(left < 2) left = 2;
	if(left > ovMap.width - width - 2) left = ovMap.width - width - 2;
	if(top < 2) top = 2;
	if(top > ovMap.height - height - 5) top = ovMap.height - height - 5;

	dojo.style(aoi, "display", "none");
	dojo.style(aoi, "left", left+"px");
	dojo.style(aoi, "top", top+"px");
	dojo.style(aoi, "width", width+"px");
	dojo.style(aoi, "height", height+"px");
	dojo.style(aoi, "display", "block");
}

function gdMapSliderChange(value)
{
	gdMap.setLevel(value);
}

function gdExpandOrCollapsePanel(id)
{
	var fpBody = dojo.byId(id + "_BodyRow");
	var expandButton = dojo.byId(id + "_ExpandButton");
	var resizeRow = dojo.byId(id + "_ResizeRow");
	if (fpBody == null || expandButton == null) return;
	if (fpBody.style.display == "none") {
	        fpBody.style.display = "";
	        if (resizeRow != null) {
	            resizeRow.style.display = "";
	        }
		expandButton.src = '/images/map/collapse.gif';
	}
	else {
	    if (fpBody.style.display != "none") {
        	fpBody.style.display = "none";
	        if (resizeRow != null) {
	            resizeRow.style.display = "none";
	        }
		expandButton.src = '/images/map/expand.gif';
	    }
	}
}
function gdSetToolbarImage(imageId, imageUrl)
{
	dojo.byId(imageId).src = imageUrl;
}
function gdSelectNavigationTool(mode)
{
	gdCurrentNavToolbarMode = mode;
	gdNavToolbar.activate(gdCurrentNavToolbarMode);
	gdSelectCurrent();
}
function gdSelectCurrent()
{
	if(gdCurrentNavToolbarMode == esri.toolbars.Navigation.ZOOM_IN)
	{
	    gdSetToolbarImage('tb1MapZoomInImage', '/Images/map/overview/vn_map_tools_zoom_active.png');
	    gdSetToolbarImage('tb1MapPanImage', '/Images/map/overview/vn_map_tools_pan_inactive.png');
	}
	else if(gdCurrentNavToolbarMode == esri.toolbars.Navigation.PAN)
	{
	    gdSetToolbarImage('tb1MapZoomInImage', '/Images/map/overview/vn_map_tools_zoom_inactive.png');
	    gdSetToolbarImage('tb1MapPanImage', '/Images/map/overview/vn_map_tools_pan_active.png');
	}
}
function gdSelectPrint()
{
	gdLeftPaneTabIndex = 0;
	ShowLeftPaneTab(2);
}
function gdZoomToPoi(x,y)
{
    gdClearMapTipsAndWeather();
    var level = gdMap.getLevel()+2;
    if(level >= gdMapLayer.tileInfo.lods.length)
        level = gdMapLayer.tileInfo.lods.length - 1;
    gdMap.centerAndZoom(new esri.geometry.Point(x, y, null), level);
}

function gdPrintMouseOver(tr)
{
    dojo.addClass(tr, "PrintOptionHover");
}

function gdPrintMouseOut(tr)
{
    dojo.removeClass(tr, "PrintOptionHover");
}

function gdGetPrintParameters()
{
    var printOption = gdGetCheckedValue(['printOptionsMapOnly','printOptionsMapAndList','printOptionsListOnly'], "MapOnly");
    var listOption = gdGetCheckedValue(['listDetailSimple','listDetailDetailed'], "Simple");
    var paperSize = gdGetCheckedValue(['paperSizeA4','paperSizeUSLegal','paperSizeUSLetter'], "A4");
    var listContent = "Products";
    if(gdLeftPanePreviousTabIndex == 1) listContent = "Articles";
    var params = "Operation=Print&PrintOption=" + printOption + "&ListOption=" + listOption + "&PaperSize=" + paperSize + "&ListContent=" + listContent;
    return params;
}

var gdEnableProductListing = false;
var gdEnableArticleListing = false;

function gdPrintListDetailsClick(checkedInput)
{
    gdSetCheckedInput(['listDetailSimple','listDetailDetailed'], checkedInput);
    // Refresh css class:
    gdGetCheckedValue(['listDetailSimple','listDetailDetailed']);
}

function gdPrintListOptionsClick(checkedInput)
{
    if(checkedInput)
        gdSetCheckedInput(['printOptionsMapOnly','printOptionsMapAndList','printOptionsListOnly'], checkedInput);
    var printOption = gdGetCheckedValue(['printOptionsMapOnly','printOptionsMapAndList','printOptionsListOnly'], "MapOnly");
    var listDetails = document.getElementById('printListDetailContainer');
    if(listDetails)
    {
        var en = (gdEnableProductListing || gdLeftPanePreviousTabIndex != 0) && (gdEnableArticleListing || gdLeftPanePreviousTabIndex != 1);
        var printExpl = dojo.byId("PrintListOptionsExplanation");
        if(printExpl)
        {
            if(en)
                printExpl.innerHTML = "";
            else
                printExpl.innerHTML = gdGetText("/map/print/zoomintoenableresultlist");
               
        }
        gdSetEnabledOptions([{id: 'printOptionsMapOnly', enabled: true},{id: 'printOptionsMapAndList', enabled: en},{id: 'printOptionsListOnly', enabled: en}], "MapOnly");
        printOption = gdGetCheckedValue(['printOptionsMapOnly','printOptionsMapAndList','printOptionsListOnly'], "MapOnly");
        if(printOption == "MapOnly" || gdLeftPanePreviousTabIndex == 1)
        {
            listDetails.style.display="none";
            listDetails.style.visibility="hidden";
        }
        else
        {
            listDetails.style.display="";
            listDetails.style.visibility="";
            // Refresh css class:
            gdGetCheckedValue(['listDetailSimple','listDetailDetailed']);
        }
    }
}

function gdSetCheckedInput(inputIDs, checkedInputID) {
    var isCheckedInputDisabled = false;
    for(var i = 0, len = inputIDs.length; i < len; i++)
    {
        var id = inputIDs[i];
        var input = document.getElementById(id);
        if(id == checkedInputID)
            isCheckedInputDisabled = input.disabled;
    }
    if(!isCheckedInputDisabled)
    {
        for(var i = 0, len = inputIDs.length; i < len; i++)
        {
            var id = inputIDs[i];
            var input = document.getElementById(id);
            if(id == checkedInputID)
                input.checked = true;
            else
                input.checked = false;
        }
    }
}

function gdGetCheckedValue(inputIDs, defaultValue) {
    var checkedValue = null;
    for(var i = 0, len = inputIDs.length; i < len; i++)
    {
        var id = inputIDs[i];
        var input = document.getElementById(id);
        if(input && input.checked) checkedValue = input.value;
    }
    if(checkedValue == null) checkedValue = defaultValue;
    for(var i = 0, len = inputIDs.length; i < len; i++)
    {
        var id = inputIDs[i];
        var input = document.getElementById(id);
        if(input && input.parentNode && input.parentNode.parentNode)
        {
            var tr = input.parentNode.parentNode;
            if(input.value == checkedValue)
                dojo.addClass(tr, "PrintOptionSelected");
            else
                dojo.removeClass(tr, "PrintOptionSelected");
            if(input.disabled)
            {
                dojo.addClass(tr, "PrintOptionsDisabled");
                dojo.removeClass(tr, "PrintOptionsEnabled");
                dojo.removeClass(tr, "PrintOptionSelected");
            }
            else
            {
                dojo.addClass(tr, "PrintOptionsEnabled");
                dojo.removeClass(tr, "PrintOptionsDisabled");
            }
        }
    }
    return checkedValue;
}

function gdSetEnabledOptions(inputs, defaultValue) {
    var checkedRemoved = false;
    for(var i = 0, len = inputs.length; i < len; i++)
    {
        var info = inputs[i];
        var input = document.getElementById(info.id);
        if(input)
        {
            var p = input.parentNode.parentNode;
            if(!info.enabled)
            {
                if(input.checked)
                {
                    input.checked = false;
                    checkedRemoved = true;
                }
                input.disabled = true;
                dojo.removeClass(p, "PrintOptionsEnabled");
                dojo.addClass(p, "PrintOptionsDisabled");
                dojo.removeClass(p, "PrintOptionSelected");
            }
            else
            {
                input.disabled = false;
                dojo.addClass(p, "PrintOptionsEnabled");
                dojo.removeClass(p, "PrintOptionsDisabled");
            }
        }
    }
    if(checkedRemoved)
    {
        for(var i = 0, len = inputs.length; i < len; i++)
        {
            var info = inputs[i];
            var input = document.getElementById(info.id);
            if(input && input.value == defaultValue)
            {
                input.checked = true;
                if(input.parentNode && input.parentNode.parentNode)
                    dojo.addClass(input.parentNode.parentNode, "PrintOptionSelected");
            }
        }
    }
}

function ShowMapPrintPreview(url)
{
  printwindow = window.open(url,'vnprintwindow','location=1,status=1,scrollbars=1,width=1000,height=800');
  try
  {
    printwindow.focus();
    //alert(printwindow.location);
  }
  catch(ex)
  {
      var div = dojo.byId(gdClientData.elementIds.printPopupBlockedDiv);
      if(div)
      {
          div.innerHTML = '<a onclick="hidePopupBlockedDiv(\'' + gdClientData.elementIds.printPopupBlockedDiv + '\')" href="' + url + '" target="vnprintwindow">' + gdGetText("/map/print/popupblocked") + '</a>';
          div.style.display = "block";
          div.style.visibility = "";
      }
      
      var div2 = dojo.byId(gdClientData.elementIds.printPopupBlockedDiv2);
      if(div2)
      {
          div2.innerHTML = '<a onclick="hidePopupBlockedDiv(\'' + gdClientData.elementIds.printPopupBlockedDiv2 + '\')" href="' + url + '" target="vnprintwindow">' + gdGetText("/map/print/popupblocked") + '</a>';
          div2.style.display = "block";
          div2.style.visibility = "";
      }
  }
  return false; 
} 

function hidePopupBlockedDiv(popupBlockedDivId)
{
      var div = document.getElementById(popupBlockedDivId);
      if(div)
      {
          div.style.display = "none";
          div.style.visibility = "hidden";
      }
}

function gdSelectEmail()
{
    SendMapEmail();
}

function gdBase64EncodeCoordinate(c, minChars)
{
    var b64chars = gdClientData.base64chars; // "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,";
    var result = "";
    if(c < 0) c = 0;
    if(c >= 16777216) c = 16777215; 
    while(c >= 0)
    {
        var n = c % 64;
        result = b64chars.substr(n,1) + result;
        c = (c-n)/64;
        if(c == 0) c = -1;
    }
    while(result.length < minChars)
        result = b64chars.substr(0,1) + result;
    return result;
}

function SendMapEmail(url)
{
    var b64chars = gdClientData.base64chars; // "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,";
    var cats = dijit.byId(gdClientData.elementIds.thePoiFilter).data.items;
    var checkedB64 = 0; var expandedB64 = 0; var base = 1;
    var checkedString = ""; var expandedString = "";
    for(var i = 0, len = cats.length; i < len; i++)
    {
        var cat = cats[i];
        if(cat.isChecked[0])
            checkedB64 += base;
        if(cat.expanded[0])
            expandedB64 += base;
        base *= 2;
        if(base > 32)
        {
            base = 1;
            checkedString = b64chars.substr(checkedB64, 1) + checkedString;
            expandedString = b64chars.substr(expandedB64, 1) + expandedString;
            checkedB64 = 0; expandedB64 = 0;
        }
    }
    if(base > 1)
    {
        checkedString = b64chars.substr(checkedB64, 1) + checkedString;
        expandedString = b64chars.substr(expandedB64, 1) + expandedString;
    }
    var x = Math.round((gdMap.extent.xmin+gdMap.extent.xmax)/2) + gdClientData.xEncodingOffset;
    var y = Math.round((gdMap.extent.ymin+gdMap.extent.ymax)/2) + gdClientData.yEncodingOffset;
    var lvl = gdMap.getLevel();
    var posString = gdBase64EncodeCoordinate(x, 4) + gdBase64EncodeCoordinate(y, 4) + gdBase64EncodeCoordinate(lvl, 1);

    url = window.location;
    if(url.href) url = url.href;
    var ix = url.indexOf("?");
    if(ix < 0)
        url += "?";
    else
        url = url.substr(0, ix+1);
    url += "c=" + checkedString + "&e=" + expandedString + "&p=" + posString;
    var fullUrl = gdClientData.emailBaseUrl; //"/{0}/VN/Email-map-to-a-friend/?pagelink={1}";
    fullUrl = fullUrl.replace("{0}", gdClientData.languageCode);
    fullUrl = fullUrl.replace("{1}", url.replace(/[?]/g,"%3F").replace(/[&]/g,"%26"));
    parent.document.getElementById('iFrameSendToFriend').style.display='block';
    parent.document.getElementById('iFrameSendToFriend').src = fullUrl;
    return false;
}

function _MapHoverFunctions()
{
    this.selectCategory = function(catIndex, poiIndex)
    {
        var containerName = "c_mappoimouseovermulticatleft_" + poiIndex;
        var elements = document.getElementById(containerName).getElementsByTagName('div');
        var current;
        var suffix = "_cat" + catIndex;
        var length = elements.length;
        for(var i=0; i<length; i++){
            current = elements[i];
            if(current.className == 'c_mappoimouseovercategory_s'){
                current.className = 'c_mappoimouseovercategory';
            }
            if(current.id && current.id.endsWith(suffix))
                current.className = 'c_mappoimouseovercategory_s';
        }
        return false;
    }
    
    this.multiCatMouseOver = function(catIndex, poiIndex, productID)
    {
        this.selectCategory(catIndex, poiIndex);
        this.replaceHTML(catIndex, poiIndex, productID);    
    }
    
    this.replaceHTML = function(catIndex, poiIndex, productID)
    {
        if(!(productID)) productID = -1;
        var html = "";
        var poi = geodata.maptips.currentMapTipsLayer.getMapTip(poiIndex);
        if(poi != null && poi.contentByCategory != null && poi.contentByCategory.length > catIndex)
        {
            var cat = poi.contentByCategory[catIndex];
            if(cat.products != null)
            {
                for(var i = 0, len = cat.products.length; i < len; i++)
                {
                    var p = cat.products[i];
                    var className = "map_poimouseovercategoryright";
                    if(p.productId == productID) className = "map_poimouseovercategoryright map_poimouseovercategoryright_active";
                    html +=  "<div id=\"map_poimouseovercategoryright_pid" + p.productId + "\" class=\"" + className + "\" onclick=document.location='" + p.url + "'><img src='" + p.thumbnail + "' class='mapactionicon' alt='' /><div class='map_poimouseovercentertext'><a href='" + p.url + "'>" + p.name + "</a></div></div>";
                }
            }
        }
        document.getElementById('c_mappoimouseovermultiplecatecoriesright_' + poiIndex).innerHTML=html;
        return false; 
    }
}
var mapHoverFunctions = new _MapHoverFunctions();

function gdSetClass(elementId, className, mouseOutClass)
{
    var elem = document.getElementById(elementId);
    if(elem)
    {
        elem.className = className;
        if(mouseOutClass)
            elem.onmouseout = function() { this.className = mouseOutClass; }
    }
}
function gdSetButtonText(elementId, text, tooltip)
{
    var elem = document.getElementById(elementId);
    if(elem)
    {
        elem.text = text;
        elem.alt = tooltip;
        elem.title = tooltip;
    }
}
function ToggleLeftPane(open)
{
    gdLeftPaneShowing = open;
    gdShowTabs(open, gdClientData.leftPaneTabs, gdLeftPaneTabIndex);
    if(gdLeftPaneShowing)
    {
        gdSetClass(gdClientData.elementIds.divMapOpen, "map_btn_visibility_hidden");
        gdSetClass(gdClientData.elementIds.divMapClose, "c_mapclosearrow c_mapclosearrowclose");
        gdSetClass(gdClientData.elementIds.divFltOverviewMap, "c_mapoverview c_mapoverview_open");
        gdSetClass(gdClientData.elementIds.divFltTools, "c_map_toolbar maptoolbar_open");
        gdSetClass(gdClientData.elementIds.c_map, "c_maplarge c_maplarge_closed");
        gdSetClass(gdClientData.elementIds.c_toctabs, "c_toctabs c_toctabs_open");
        if (dojo.isIE) {
            dojo.style(/* settings.mapId */"gdMapDiv", "width", "640px");
            dojo.style("gdMapPreloader", "width", "640px");
            dojo.style("gdMapError", "width", "640px");
        }
        else {
            dojo.style(/* settings.mapId */"gdMapDiv", "width", "647px");
            dojo.style("gdMapPreloader", "width", "647px");
            dojo.style("gdMapError", "width", "647px");
        }
    }
    else
    {
        gdSetClass(gdClientData.elementIds.divMapOpen, "c_mapclosearrow c_mapclosearrowopen");
        gdSetClass(gdClientData.elementIds.divMapClose, "map_btn_visibility_hidden");
        gdSetClass(gdClientData.elementIds.divFltOverviewMap, "c_mapoverview c_mapoverview_closed");
        gdSetClass(gdClientData.elementIds.divFltTools, "c_map_toolbar maptoolbar_closed");
        gdSetClass(gdClientData.elementIds.c_map, "c_maplarge c_maplarge_open");
        gdSetClass(gdClientData.elementIds.c_toctabs, "c_toctabs c_toctabs_closed");
        if (dojo.isIE) {
            dojo.style(/* settings.mapId */"gdMapDiv", "width", "978px");
            dojo.style("gdMapPreloader", "width", "978px");
            dojo.style("gdMapError", "width", "978px");
        }
        else {
            dojo.style(/* settings.mapId */"gdMapDiv", "width", "984px");
            dojo.style("gdMapPreloader", "width", "984px");
            dojo.style("gdMapError", "width", "984px");
        }
    }
    gdRepositionMap(gdMap);
    var c = dojo.coords(gdMap._root, true);
    gdMap.position.x = c.x;
    gdMap.position.y = c.y;
    gdMap.resize();
}

function gdSortChanged()
{
    gdDoCallback('operation=sortlist');
}

function gdSelectAllCategories()
{
    gdClearMapTips();
    dijit.byId(gdClientData.elementIds.thePoiFilter).checkAll(true);
    gdDoCallback('operation=updatecontent');
    return false;
}

function gdSelectNoCategories()
{
    gdClearMapTips();
    dijit.byId(gdClientData.elementIds.thePoiFilter).checkAll(false);
    gdDoCallback('operation=updatecontent');
    return false;
}

function gdZoomToLevel(level)
{
    gdMapSlider.setValue(level);
    return false;
}

function gdShowTabs(open, tabs, index)
{
    var activeTab = null;
    for(var i = 0, len = tabs.length; i < len; i++)
    {
        var tab = document.getElementById(tabs[i].tabContentId);
        if(tab)
        {
            tab.style.visibility = "hidden";
            tab.style.display = "none";
            if(tabs[i].index == index)
                activeTab = tab;
        }
    }
    if(open)
    {
        if(activeTab != null)
        {
            activeTab.style.visibility = "visible";
            activeTab.style.display = "block";
        }
    }
    for(i = 0, len = tabs.length; i < len; i++)
    {
        if(tabs[i].tabButtonId != null)
        {
            var tabButton = document.getElementById(tabs[i].tabButtonId);
            if(tabButton)
            {
                if(tabs[i].index == index && open)
                {
                    dojo.removeClass(tabButton, "ajax__tab_inactive");       
                    dojo.addClass(tabButton, "ajax__tab_active");
                }
                else
                {
                    dojo.removeClass(tabButton, "ajax__tab_active");       
                    dojo.addClass(tabButton, "ajax__tab_inactive");
                }
            }
        }
    }
}
var gdLeftPanePreviousTabIndex = 0;
function ShowLeftPaneTab(tabIndex)
{
    gdLeftPanePreviousTabIndex = gdLeftPaneTabIndex;
    gdLeftPaneTabIndex = tabIndex;
    if(gdLeftPaneTabIndex == 2) gdPrintListOptionsClick();
    if(!gdLeftPaneShowing)
        ToggleLeftPane(true);
    else
        gdShowTabs(true, gdClientData.leftPaneTabs, tabIndex);
}
function ShowOvTab(tabIndex)
{
    gdOvTabIndex = tabIndex;
    gdShowTabs(true, gdClientData.ovMapTabs, tabIndex);
}