﻿var geoXml, map, googleMapUrl;
var bigmap, bigGeoXml;

function getRelLink(rel,relative)
{
    var link = $("link[rel='" + rel + "']");
    if ( link.length > 0 ) {
        var rurl = link[0].href;
        if (!relative && rurl.charAt(0) == "/") {
            return "http://" + location.host + rurl;
        } else if (relative && rurl.charAt(0) != "/") {
            return rurl.replace("http://" + location.host,"");
        } else {
            return rurl;
        }
    } else {
        return "";
    }
}

function getPictureGalleryUrl()
{
    return getRelLink("PicGallDef",true);
}

function retrieveGoogleMapUrl()
{
    return getRelLink("MapKML",false);
}

$(document.body).unload(function() {
    if (GBrowserIsCompatible()) {
        GUnload();
    }
});

$(function(){
    googleMapUrl = retrieveGoogleMapUrl();
    if ( googleMapUrl && googleMapUrl != "" ) {
        if (GBrowserIsCompatible()) {

//googleMapUrl = "http://sites.google.com/site/tempgmapstest/probeer5.xml";

            geoXml = new GGeoXml(googleMapUrl);
            map = new GMap2($("#map_canvas")[0]);
            map.setCenter(new GLatLng(88,1),10);
            
            var verticaloffset = 0;
            if ( $.browser.msie && $.browser.version == "6.0" ) {
                verticaloffset = -1;
            }
            
            map.addControl(NewButtonControl(
                "Show larger map",
                $wms.resolveUrl("~/strategicsites/i/enlargeMap.gif"),
                function(){ $('#popout').click(); },
                new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(-1, verticaloffset))
            ));

            GEvent.addListener(geoXml,"load",function(){
                if (geoXml.hasLoaded()) {
                    GEvent.clearListeners(geoXml, "load");
                    geoXml.gotoDefaultViewport(map);
                    
                    var mo = new GMapUIOptions(new GSize($("#map_canvas").width(),$("#map_canvas").height()));
                    mo.maptypes.satellite = false;
                    mo.maptypes.hybrid = false;
                    mo.maptypes.physical = false;
                    mo.controls.maptypecontrol = false;
                    mo.controls.menumaptypecontrol = false;
                    mo.zoom.scrollwheel = false;
                    mo.zoom.doubleclick = false;
                    mo.controls.smallzoomcontrol3d = false;
                    
                    map.disableDragging();
                    map.disableInfoWindow();
                    
                    map.setUI(mo);
                    map.addOverlay(geoXml);
                    
                    map.savePosition();

                    $(".mapPanel a[href*='terms'], .homeMap a[href*='terms']").parent("div").css({ top:"0px", bottom:"auto"});
                }
            });
        }
    } else {
        // no map, remove mapPanel
        $(".mapPanel, .homeMap").remove();
    }

    $(".mainCol").css("min-height", $(".sideCol").height());
    
    // need to preload the linkLeft and linkRight images to make buttons and top nav smoother on hover
    var preloader = $(document.body).append("<div id='preloader' style='display:none'></div>").find("#preloader");
    for ( var i = 0; i < 6; i++ ) {
        (new Image()).src = preloader.append("<div id='preload" + (i+1) + "'></div>").find(":last-child").css("background-image").replace(/^url\(/,"").replace(/\)$/,"");
    }
    preloader.remove();
});

$(function(){
    if ( googleMapUrl && googleMapUrl != "" ) {
        if (GBrowserIsCompatible()) {
            var width = $("#bigmap").width(), height = $("#bigmap").height();

            $("#popout").fancybox({
                hideOnContentClick: false,
                frameWidth: $("#bigmap").width(),
                frameHeight: $("#bigmap").height(),
                overlayShow: true,
                overlayOpacity: 0.8,
                callbackOnShow: function() {

                    $("#fancy_div").html('<div id="bigmap2"></div>').find("#bigmap2").css({width:width,height:height});

                    bigGeoXml = new GGeoXml(googleMapUrl);
                    bigmap = new GMap2($("#bigmap2")[0]);
                    bigmap.setCenter(new GLatLng(88,1),10);
                    
                    GEvent.addListener(bigmap, "tilesloaded", function() {
                        bigmap.addControl(NewButtonControl(
                            "Print map",
                            $wms.resolveUrl("~/strategicsites/i/mapPrintButton.png"),
                            function(){
                                var $bigmap = $("#bigmap2");
                                var printwindow = window.open('about:blank','printwindow','width=' + $bigmap.width() + ',height=' + $bigmap.height(),true);
                                
                                var $print = $($bigmap.html());
                                $print.find(".gmnoprint:not(img),img[src$='dithshadow.gif']").remove();
                                
                                printwindow.document.open();
                                printwindow.document.write($print.html());
                                printwindow.document.close();
                                setTimeout(function() { printwindow.print(); }, 500);
                            },
                            new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(7, 7))
                        ));
                    });
                    
                    GEvent.addListener(bigmap, "infowindowopen", function() {
                        $("#iw_kml p:empty").remove();
                    });
                    
                    GEvent.addListener(bigGeoXml, "load", function(){
                        if (bigGeoXml.hasLoaded()) {
                            GEvent.clearListeners(bigGeoXml, "load");
                            bigGeoXml.gotoDefaultViewport(bigmap);
                            bigmap.addOverlay(bigGeoXml);

                            var mo = new GMapUIOptions(new GSize($("#bigmap2").width(),$("#bigmap2").height()));
                            mo.maptypes.satellite = false;
                            mo.maptypes.hybrid = false;
                            mo.maptypes.physical = false;
                            mo.controls.maptypecontrol = false;
                            mo.controls.menumaptypecontrol = false;

                            bigmap.setUI(mo);
                            
                            var latitude = $("input.centreLat").val();
                            var longitude = $("input.centreLong").val();
                            
                            if ( latitude && latitude != "" && longitude && longitude != "" ) {
                                bigmap.setCenter(new GLatLng(latitude,longitude));
                            }
                            
                            bigmap.savePosition();
                        }
                    });
                }
            });
        }
    }
});

function NewButtonControl(text,imageUrl,onclick, GControlPosition)
{
    var button = new ButtonControl();
    button.text = text;
    button.imageUrl = imageUrl;
    button.onclick = onclick;
    button.GControlPosition = GControlPosition;
    return button;
}

// We define the function first
function ButtonControl() {
}

if ( typeof(GBrowserIsCompatible) == "function" )
{
    // To "subclass" the GControl, we set the prototype object to
    // an instance of the GControl object
    ButtonControl.prototype = new GControl();

    // Creates a one DIV for each of the buttons and places them in a container
    // DIV which is returned as our control element. We add the control to
    // to the map container and return the element for the map class to
    // position properly.
    ButtonControl.prototype.initialize = function(map) {
      var container = document.createElement("div");

      var printDiv = document.createElement("div");
      this.setButtonStyle_(printDiv);
      container.appendChild(printDiv);
      var img = document.createElement("img");
      img.setAttribute("src", this.imageUrl);
      img.setAttribute("alt", this.text);
      printDiv.appendChild(img);
      GEvent.addDomListener(printDiv, "click", this.onclick);

      map.getContainer().appendChild(container);
      return container;
    }

    // By default, the control will appear in the bottom left corner of the
    // map with 7 pixels of padding.
    ButtonControl.prototype.getDefaultPosition = function() {
      return this.GControlPosition;
    }

    // Sets the proper CSS for the given button element.
    ButtonControl.prototype.setButtonStyle_ = function(button) {
      button.style.cursor = "pointer";
    }
}

function openVideoPlayer()
{
    var vidurl = '../video/durham.flv';
    
    var val = $(".media-enabled embed").attr("flashvars");
    if (!val)
    {
        val = $(".media-enabled object param[name='src']").attr('value');
    }
    
    var matches = unescape(val).match(/file=(.*?)&/);
    if ( matches && matches.length > 1 )
    {
        // %2fCDDC%2f_diskcache%2f22-durham.flv%26t%3d.flv
        vidurl = matches[1];
    }

    openTVPlayer(vidurl);
}
