﻿/// <reference path="/Scripts/jquery-1.6-vsdoc.js" />


Microsoft.Maps.Pushpin.prototype.pond = null;
var photoMap = null;
var photoPonds = [];
var nextPhoto = new Image();
var showPhotos = true;
var photoStopped = false;

$().ready(function () {

    var pondMap = null;

    //================ MENU ================

    $("#menu li").wrapInner("<span></span>");

    $("#menuAbout").bind("click", function () {
        StartPhotos();
        $("#photoShow").insertBefore("#contentAbout h2:first");
        SelectTab(this, "#contentAbout");
    });

    $("#menuPonds").bind("click", function () {
        showPhotos = false;
        SelectTab(this, "#contentPonds");
        if (pondMap == null) {
            createPondMap();
        }
    });

    $("#menuNews").bind("click", function () {
        showPhotos = false;
        SelectTab(this, "#contentNews");
        if ($("#contentNews li.selected").length == 0) {
            $("#contentNews li:first > span").click();
        }
    });

    $("#menuInvolved").bind("click", function () {
        showPhotos = false;
        SelectTab(this, "#contentInvolved");
    });

    $("#menuEvents").bind("click", function () {
        StartPhotos();
        $("#photoShow").insertBefore("#contentEvents h2:first");
        SelectTab(this, "#contentEvents");
    });

    $("#menuWildAbout").bind("click", function () {
        showPhotos = false;
        SelectTab(this, "#contentWildAbout");
        if ($("#contentWildAbout > div > div li.selected").length == 0) {
            $("#contentWildAbout > div > div li:eq(1)").click();
        }
    });

    $("#menuLinks").bind("click", function () {
        StartPhotos();
        $("#photoShow").insertBefore("#contentLinks a:first");
        SelectTab(this, "#contentLinks");
    });

    function SelectTab(button, page) {
        $("#menu li").removeClass("selected");
        $(button).addClass("selected");
        $(".content").hide();
        $(page).show();
    }

    //================ ABOUT US TAB ================

    photoMap = new Microsoft.Maps.Map(document.getElementById("photoMap"),
    { credentials: "AuICUC0fk2N_Y5UQWY0n1CSWbdvAqOxsMKjaV_2kOAFf8DCcGPWOAHv9vd_V_fw7",
        center: new Microsoft.Maps.Location(52.875933, -1.485853),
        mapTypeId: Microsoft.Maps.MapTypeId.mercator,
        showDashboard: false,
        showLogo: false,
        enableClickableLogo: false,
        enableSearchLogo: false,
        showScalebar: false,
        zoom: 13
    });

    $(window).bind("beforeunload", function () {
        if (typeof (photoMap) != "undefined" && photoMap != null) {
            photoMap.dispose();
            photoMap = null;
        }
    });

    for (i in PondInfo) {
        if (PondInfo[i].Photo != "" && PondInfo[i].GridRef != "") {
            photoPonds.push(i);
        }
    }

    setTimeout("LoadPhotoMap()", 3000);

    $("#contact > img").bind("click", function () {
        var contact = "moc.loa@";
        contact += "awpcd";                    // Electronic correspondence destination
        contact += ":otliam"
        var win = window.open(contact.split("").reverse().join(""));
        if (win && win.open && !win.closed) win.close();
    });

    function StartPhotos() {
        showPhotos = true;
        if (photoStopped) {
            LoadNextPhoto();
            photoStopped = false;
        }
    }

    //================ PONDS TAB ================

    function createPondMap() {
        pondMap = new Microsoft.Maps.Map(document.getElementById("pondMap"),
                        { credentials: "AuICUC0fk2N_Y5UQWY0n1CSWbdvAqOxsMKjaV_2kOAFf8DCcGPWOAHv9vd_V_fw7",
                            center: new Microsoft.Maps.Location(52.92, -1.48),
                            mapTypeId: Microsoft.Maps.MapTypeId.auto,
                            enableClickableLogo: false,
                            enableSearchLogo: false,
                            zoom: 12
                        });

        var wardenCount = 0;
        var pushpinOptions = { icon: "Images/PushPin.png", width: 25, height: 39 };

        for (i in PondInfo) {
            var latLong = LatLong(PondInfo[i]);
            if (latLong.latitude > 0) {
                var pushpin = new Microsoft.Maps.Pushpin(latLong, pushpinOptions);
                pushpin.pond = PondInfo[i];
                Microsoft.Maps.Events.addHandler(pushpin, "click", function (e) { ShowPondDetails(e) });
                Microsoft.Maps.Events.addHandler(pushpin, "mouseover", function (e) { ShowPondDetails(e) });
                pondMap.entities.push(pushpin);
            }
            if (PondInfo[i].Warden != "") {
                wardenCount++;
            }
        }
        $("#numPonds").html(PondInfo.length);
        $("#wardenPercent").html(((PondInfo.length - wardenCount) / PondInfo.length * 100).toFixed() + "%");

    }

    function LatLong(Pond) {
        if (!Pond.Latitude) {

            if (Pond.GridRef != "") {
                var latLong = OsGrid_To_Wgs84(Pond.GridRef);
            }
            else {
                var latLong = new Microsoft.Maps.Location(-80, 180);
            }
        }
        else {
            var latLong = new Microsoft.Maps.Location(Pond.Latitude, Pond.Longitude);
        }
        return latLong;
    }

    function ShowPondDetails(e) {
        var pond = e.target.pond;
        var location = e.target.getLocation();
        var psym2005 = (pond.PSYM2005) ? (pond.PSYM2005 * 100).toFixed() + "% &nbsp;&nbsp;&nbsp; " + PsymCat(pond.PSYM2005) : "";
        var psym2010 = (pond.PSYM2010) ? (pond.PSYM2010 * 100).toFixed() + "% &nbsp;&nbsp;&nbsp; " + PsymCat(pond.PSYM2010) : "";

        var html = "<h2>" + pond.Name + "</h2>";
        html += "<table>";
        html += "<tr><th>OS Grid Ref.</th><td>" + pond.GridRef + "</td></tr>";
        html += "<tr><th>Latitude</th><td>" + location.latitude.toFixed(6) + "°</td></tr>";
        html += "<tr><th>Longitude</th><td>" + location.longitude.toFixed(6) + "°</td></tr>";
        html += "<tr><th>Ownership</th><td>" + pond.Ownership + "</td></tr>";
        html += "<tr><th>Owner</th><td>" + pond.Owner + "</td></tr>";
        html += "<tr><th>Warden</th><td>" + pond.Warden + "</td></tr>";
        html += "<tr><th><span class='psym'>PSYM</span> 2005</th><td>" + psym2005 + "</td></tr>";
        html += "<tr><th><span class='psym'>PSYM</span> 2010</th><td>" + psym2010 + "</td></tr>";

        if (pond.Report) {
            var pdfLink = (pond.Report.indexOf("html", pond.Report.length - 4) != -1) ? "<a style='float:right;' href='" +
            pond.Report.replace(".html", ".pdf") + "' target='_blank'><img src='Images/Pdf.png' alt='' />PDF</a>" : "";

            html += "<tr><td colspan='2' class='report'><strong><a href='" + pond.Report +
            "'  target='_blank'>Pond Survey Report</a></strong>" + pdfLink + "</td><tr>";
        }
        html += "</table>";

        if (pond.Photo) {
            html += "<img src='" + pond.Photo + "' alt='" + pond.Name + "' width='291px'/>"
        }

        $("#pondDetails").html(html);
        $(".psym").mouseenter(function () { $("#psym").show() }).mouseleave(function () { $("#psym").hide() });

        function PsymCat(score) {
            if (score > 0.75) return "Good";
            if (score > 0.5) return "Fair";
            if (score > 0.25) return "Poor";
            return "Very Poor";
        }
    }

    $(window).bind("beforeunload", function () {
        if (typeof (pondMap) != "undefined" && pondMap != null) {
            pondMap.dispose();
            pondMap = null;
        }
    });

    //================ NEWSLETTERS TAB ================

    $("#contentNews > div").resizable({ handles: 'w', helper: "ui-resizable-helper" });
    $("#contentNews li > a").each(function () {
        var link = $(this).attr("href").toString();
        $("<span/>").appendTo($(this).parent()).text($(this).text()).bind("click", link, function (e) {
            $("#contentNews li").removeClass("selected");
            $(this).parent().addClass("selected");
            $("#contentNews iframe").attr("src", e.data);
            $("#contentNews > div a").attr("href", e.data.replace(".html", ".pdf"));
        });
    }).remove();

    //================ WILD ABOUT PONDS TAB ================

    $("#contentWildAbout > div > div ul").html("<li>&lt;&lt;</li><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>&gt;&gt;</li>");

    $("#contentWildAbout > div").resizable({ handles: 'sw', minHeight: 190, minWidth: 225, resize: function (event, ui) {
        $(this).css("width", $(this).width()).css("left", "")
    }
    });

    $("#contentWildAbout > div li").disableSelection().click(function () {
        switch ($(this).text()) {
            case "Bid Presentation":
                $(this).addClass("selected").next().removeClass("selected");
                $("#contentWildAbout > div > div ul").show();
                $("#contentWildAbout > div > div li.selected").click();
                break;
            case "Location Map":
                $(this).addClass("selected").prev().removeClass("selected");
                $("#contentWildAbout > div img").attr("src", "Images/Presentation/Map.png");
                $("#contentWildAbout > div > div ul").hide();
                break;
            case "<<":
                if ($("#contentWildAbout > div > div li.selected").text() != "1") {
                    $("#contentWildAbout > div > div li.selected").prev().click();
                }
                break;
            case ">>":
                if ($("#contentWildAbout > div > div li.selected").text() != "11") {
                    $("#contentWildAbout > div > div li.selected").next().click();
                }
                break;
            default:
                $("#contentWildAbout > div > div li").removeClass("selected");
                $(this).addClass("selected");
                $("#contentWildAbout > div img").attr("src", "Images/Presentation/Slide" + $(this).text() + ".png");
        }
    });

});

//================ PHOTO SHOW ================

function LoadPhotoMap () {
    photoMap.setMapType(Microsoft.Maps.MapTypeId.road);
    LoadNextPhoto();
};

function LoadNextPhoto() {
    if (showPhotos) {
        var nextIndex = photoPonds[Math.floor(Math.random() * photoPonds.length)];
        nextPhoto.src = PondInfo[nextIndex].Photo;
        setTimeout("HidePhoto(" + nextIndex + ")", 11000);
    }
    else {
        photoStopped = true;
    }
}

function HidePhoto(nextIndex) {
    $("#photoShow span").hide();
    $("#photo").animate({left: "214px", right: "214px", top: "161px", bottom: "161px"}, 2000, function () {
        ZoomNextPond(nextIndex);
    });
}

function ZoomNextPond(nextIndex) {
    photoMap.setView({ center: OsGrid_To_Wgs84(PondInfo[nextIndex].GridRef), animate: true });
    $("#photoShow span").html(PondInfo[nextIndex].Name);
    setTimeout("ShowPhoto()", 1000);
}

function ShowPhoto() {
    $("#photoShow span").show();
    $("#photo>img").attr("src", nextPhoto.src + "").parent().
        animate({ left: "0px", right: "0px", top: "0px", bottom: "0px" }, 2000, function () {
        LoadNextPhoto();
    });
}

//================ GEOGRAPHY MATHS ================

function OsGrid_To_Wgs84(SkRef) {

    var ellipsoids = {
        WGS84: {
            a: 6378137,      // Semi-major axis
            b: 6356752.3142  // Semi-minor axis
        },
        Airy1830: {
            a: 6377563.396,  // Semi-major axis
            b: 6356256.909   // Semi-minor axis
        }
    };

    var coords = SkRef.split(" ");
    var east = 400000 + parseFloat(coords[1]);   // Grid SK east starts at 400000m
    var north = 300000 + parseFloat(coords[2]);  // Grid SK north starts at 300000m

    var airy1930 = OsGrid_To_Airy1830(east, north);
    var wgs84 = Airy1830_To_Wgs84(airy1930.Latitude, airy1930.Longitude);
   
    return new Microsoft.Maps.Location(wgs84.Latitude * (180 / Math.PI), wgs84.Longitude * (180 / Math.PI));


    function OsGrid_To_Airy1830(East, North) {

        //====== Ordnance Survey National Grid (from Wikipedia) ======
        var f0 = 0.9996012717;     // Scale Factor
        var E0 = 400000;           // False origin east
        var N0 = -100000;          // False origin north
        var Phi0 = 0.855211333477; // True origin 49 deg N in radians
        var Lam0 = -0.03490658504; // True origin 2 deg W in radians

        //====== Compute af0, bf0, e squared (e2), n, dE and dN ======
        var af0 = ellipsoids.Airy1830.a * f0;
        var bf0 = ellipsoids.Airy1830.b * f0;
        var e2 = (af0 * af0 - bf0 * bf0) / (af0 * af0);
        var n = (af0 - bf0) / (af0 + bf0);
        var n2 = n * n, n3 = n2 * n;
        var dE = East - E0;
        var dE2 = dE * dE, dE3 = dE2 * dE, dE4 = dE3 * dE, dE5 = dE4 * dE, dE6 = dE5 * dE, dE7 = dE6 * dE;
        var dN = North - N0;

        //====== Compute initial value for latitude (phi) in radians ======
        var phi = Phi0, M = 0;
        do {
            phi = ((dN - M) / af0) + phi;
            M = bf0 * ((1 + n + 5 / 4 * n2 + 5 / 4 * n3) * (phi - Phi0) -
             (3 * n + 3 * n2 + 21 / 8 * n3) * Math.sin(phi - Phi0) * Math.cos(phi + Phi0) + 
             ((15 / 8 * n2) + (15 / 8 * Math.pow(n, 3))) * Math.sin(2 * (phi - Phi0)) * Math.cos(2 * (phi + Phi0)) -
             (35 / 24 * n3) * Math.sin(3 * (phi - Phi0)) * Math.cos(3 * (phi + Phi0)));  // Arc of meridian
        } while (Math.abs(dN - M) > 0.0000001)
        
        var sinPhi = Math.sin(phi);
        var tanPhi = Math.tan(phi);
        var tan2Phi = tanPhi * tanPhi, tan4Phi = tan2Phi * tan2Phi, tan6Phi = tan4Phi * tan2Phi;
        var secPhi = 1 / Math.cos(phi);

        //====== Compute nu, rho and eta2 using value for phi ======
        var nu = af0 / (Math.sqrt(1 - (e2 * sinPhi * sinPhi)));
        var nu3 = nu * nu * nu, nu5 = nu3 * nu * nu, nu7 = nu5 * nu * nu;
        var rho = (nu * (1 - e2)) / (1 - (e2 * sinPhi * sinPhi));
        var eta2 = nu / rho - 1;

        //====== Compute Latitude ======
        var VII = tanPhi / (2 * rho * nu);
        var VIII = tanPhi / (24 * rho * nu3) * (5 + 3 * tan2Phi + eta2 - 9 * eta2 * tan2Phi);
        var IX = tanPhi / (720 * rho * nu5) * (61 + 90 * tan2Phi + 45 * tan4Phi);

        var latitude = phi - dE2 * VII + dE4 * VIII - dE6 * IX;

        //====== Compute Longitude ======
        var X = secPhi / nu;
        var XI = secPhi / (6 * nu3) * (nu / rho + 2 * tan2Phi);
        var XII = secPhi / (120 * nu5) * (5 + 28 * tan2Phi + 24 * tan4Phi);
        var XIIA = secPhi / (5040 * nu7) * (61 + 662 * tan2Phi + 1320 * tan4Phi + 720 * tan6Phi);

        var longitude = Lam0 + dE * X - dE3 * XI + dE5 * XII - dE7 * XIIA;

        return { Latitude: latitude, Longitude: longitude };
    }

    function Airy1830_To_Wgs84(Latitude, Longitude) {
        //====== convert polar to cartesian coordinates (using Airy1830) ======

        var a = ellipsoids.Airy1830.a;
        var b = ellipsoids.Airy1830.b;

        var sinPhi = Math.sin(Latitude), cosPhi = Math.cos(Latitude);
        var sinLambda = Math.sin(Longitude), cosLambda = Math.cos(Longitude);
        var height = 0;

        var e2 = (a * a - b * b) / (a * a);
        var nu = a / Math.sqrt(1 - e2 * sinPhi * sinPhi);

        var x1 = (nu + height) * cosPhi * cosLambda;
        var y1 = (nu + height) * cosPhi * sinLambda;
        var z1 = ((1 - e2) * nu + height) * sinPhi;

        //====== apply helmert transform ======

        var helmert = { tx: 446.448, ty: -125.157, tz: 542.060,  // m
            rx: 0.1502, ry: 0.2470, rz: 0.8421,                  // sec
            s: -20.4894                                          // ppm
        };

        var rx = helmert.rx / 3600 * (Math.PI / 180);  // normalise seconds to radians
        var ry = helmert.ry / 3600 * (Math.PI / 180);
        var rz = helmert.rz / 3600 * (Math.PI / 180);
        var s1 = helmert.s / 1e6 + 1;              // normalise ppm to (s+1)

        var x2 = helmert.tx + x1 * s1 - y1 * rz + z1 * ry;
        var y2 = helmert.ty + x1 * rz + y1 * s1 - z1 * rx;
        var z2 = helmert.tz - x1 * ry + y1 * rx + z1 * s1;

        //====== convert cartesian to polar coordinates (using WGS84) ======

        a = ellipsoids.WGS84.a;
        b = ellipsoids.WGS84.b;
        e2 = (a * a - b * b) / (a * a);

        var p = Math.sqrt(x2 * x2 + y2 * y2);
        var phi = Math.atan2(z2, p * (1 - e2));
        var phiP = 2 * Math.PI;
        while (Math.abs(phi - phiP) > 0.0000001) {
            nu = a / Math.sqrt(1 - e2 * Math.sin(phi) * Math.sin(phi));
            phiP = phi;
            phi = Math.atan2(z2 + e2 * nu * Math.sin(phi), p);
        }
        var lambda = Math.atan2(y2, x2);

        return { Latitude: phi, Longitude: lambda };
    }
}
