﻿var gMaps = {
    localsearch: "",
    icon: "",
    map: "",

    // enables us to create our html. (Dimas Code)
    createRecursiveObjects: function (spec) {
        for (var item in spec) {
            var obj = document.createElement(item);
            for (var attrib in spec[item].attributes) obj[attrib] = spec[item].attributes[attrib];
            if (spec[item].text && spec[item].text != "") obj.innerHTML = spec[item].text;
            for (var style in spec[item].styles) obj.style[style] = spec[item].styles[style];
            for (var child in spec[item].children) obj.appendChild(gMaps.createRecursiveObjects(spec[item].children[child]));
            if (spec[item].callback && typeof spec[item].callback == "function") spec[item].callback(obj);
            return obj;
        }
    },
    //initialise google maps.
    GMapsLoader: function () {
        if (GBrowserIsCompatible()) {
            //get the postcode, and show the gmaps panel.
            var searchString = $("#txtSearchBranches").val()

            // show loading div ( and gmaps div, as it needs to be visible to setup )
            $("#pnlBranches").hide();
            $("#map-overlay").show();
            $("#pnlBranchSearch").show();

            //google map setup.
            gMaps.map = new GMap2(document.getElementById("vacancyAreaMapFull"));
            gMaps.map.setUIToDefault();
            gMaps.map.setCenter(new GLatLng(50.049110507516254, 0.0246334075927734), 8);
            gMaps.icon = new GIcon(G_DEFAULT_ICON);
            gMaps.icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            gMaps.icon.iconSize = new GSize(25, 40);
            gMaps.icon.shadowSize = new GSize(37, 34);
            gMaps.icon.iconAnchor = new GPoint(10, 24);
            gMaps.icon.shadowAnchor = new GPoint(0, 0);

            // set google maps local search object + get the postcode latitude and longitude.
            gMaps.localsearch = new GlocalSearch();
            gMaps.GMapsGetPostcodePoint(searchString);

        }
        return false;
    },

    // get the latitude and longitude of your location.
    GMapsGetPostcodePoint: function (postcode) {
        var resultLat;
        var resultLng;
        //using the local search object, return our latitude and longitude.
        gMaps.localsearch.setSearchCompleteCallback(null, function () {
            if (gMaps.localsearch.results[0]) {
                //our latitude and longitud vars.
                resultLat = gMaps.localsearch.results[0].lat;
                resultLng = gMaps.localsearch.results[0].lng;
                //find all branches close to the location that you have specified.
                gMaps.GMapsFindBranches(resultLat, resultLng);
            } else {
                $("#pnlBranchSearch").hide();
                $("#NoResults").show();
            }
        });
        //execute the callback function above.
        gMaps.localsearch.execute(postcode + ", UK");
    },

    //get the closest 5 locations to the postcode, and output html.
    GMapsFindBranches: function (resultLat, resultLng) {

        var ptFrom = new GLatLng(resultLat, resultLng);
        var surroundingBranches = 12;

        //request branch details as json object.
        GDownloadUrl("http://www.cats.org.uk/cats_branches_json.ashx", function (doc) {
            //vars.
            var obj = eval('(' + doc + ')');
            var bounds = new GLatLngBounds();
            var containerDivElement = document.getElementById("jsGMapsBranchContainer");
            var obj3DivContainer = document.createElement("div");
            var objContentLine = document.createElement("div");
            var objContentImage = document.createElement("img");

            //sort our json object array by distance, (latitude and longitude).
            obj.branches.sort(function (a, b) {
                var distanceToA = ptFrom.distanceFrom(new GLatLng(a.point.Lat, a.point.Lng));
                var distanceToB = ptFrom.distanceFrom(new GLatLng(b.point.Lat, b.point.Lng));
                return distanceToA - distanceToB;
            });

            //create our container for our branches, per line.
            obj3DivContainer.className = 'branchContainer';

            for (i = 0; i < surroundingBranches; i++) {
                //branch variables for each branch
                var objPoint = obj.branches[i].point;
                var point = new GLatLng(objPoint.Lat, objPoint.Lng);
                var type = obj.branches[i].type;
                var address1 = obj.branches[i].address1;
                var address2 = obj.branches[i].address2;
                var town = obj.branches[i].town;
                var county = obj.branches[i].county;
                var postcode = obj.branches[i].postcode;
                var email = obj.branches[i].email;
                var tel = obj.branches[i].tel;
                var name = obj.branches[i].name;
                var tempBranchID = obj.branches[i].branchID;
                var branchTypeID = obj.branches[i].branchType;
                var branchLive = obj.branches[i].branchLive;
                var branchExternalUrl = obj.branches[i].branchExternalUrl;
                var friendlyurl;

                if (tempBranchID == 1) { friendlyurl = '/index.aspx' }
                else {
                    if (branchLive == 1) {
                        branchExternalUrl = branchExternalUrl.replace("http://", "");
                        friendlyurl = "http://" + branchExternalUrl;
                    }
                    else { friendlyurl = '/' + obj.branches[i].friendlyurl + '/'; }
                }

                //if they are closer than 30 miles away.
                if (ptFrom.distanceFrom(point) < 48280) {

                    //for each 3 branches, close append what we already have, create a new divider line, and open a new container div.
                    if ((i > 0) && (i % 3 == 0)) {
                        containerDivElement.appendChild(obj3DivContainer);

                        objContentLine = document.createElement("div");
                        objContentLine.className = 'mainContentLine';
                        objContentImage = document.createElement("img");
                        objContentImage.src = '/images/mainContentLine.jpg';
                        objContentImage.setAttribute('alt', ' ');
                        objContentImage.setAttribute('title', ' ');
                        objContentLine.appendChild(objContentImage);
                        containerDivElement.appendChild(objContentLine);

                        obj3DivContainer = document.createElement("div");
                        obj3DivContainer.className = 'branchContainer';
                    }

                    //popup window for the branch overlay.
                    var html = '<h3 class=\'h3Container h3\' style=\'margin:0;\'>' + name + '</h3><p>' + type + '</p>';

                    //if we have a lat and lng, then create a marker, and place it on the map.
                    if (objPoint.Lat != 0 && objPoint.Lng != 0 && branchTypeID != 3) {
                        var marker = gMaps.GMapsCreateMarker(point, friendlyurl, html, branchTypeID, branchLive);
                        gMaps.map.addOverlay(marker);
                        //one the marker is created and added,expand the map bounds to include that marker.
                        bounds.extend(point);
                    }

                    //css class differs for first and last div on a row or branches.
                    var branchBoxCssClass;
                    if (i % 3 == 0) { branchBoxCssClass = "branchBoxRight"; }
                    else { branchBoxCssClass = "branchBoxLeft"; }

                    // begin creating the html to output.
                    obj3DivContainer.appendChild(
                        gMaps.createRecursiveObjects(
                            {
                                "div": {
                                    //<div class="branchBoxRight">//this is the branch container.
                                    attributes: { "className": (i == 2 || i == 5) ? "branchBoxRight" : "branchBoxLeft" },
                                    children: [
                                        {
                                            "div": {
                                                //<div class="h3Container">//the h3 container for the branch.
                                                attributes: { "className": "h3Container" },
                                                children: [
                                                    {
                                                        "h3": {
                                                            //<h3>Branch Name</h3>//h3 tag, for branch name.
                                                            text: name
                                                        }
                                                    }
                                                ]
                                            }
                                        },

                                        {
                                            "div": 
                                            (
                                             branchTypeID != 3 ?
                                            {
                                                //<div class="pContainer">//p tag for branch details.
                                                attributes: { "className": "pContainer" },
                                                children: [
                                                    {
                                                        "p": {
                                                            //address line 1,<br />address line 2,....//the contact details.
                                                            text:
                                                                (address1.length > 0 ? address1 + '<br />' : '') +
                                                                (address2.length > 0 ? address2 + '<br />' : '') +
                                                                (town.length > 0 ? town + '<br />' : '') +
                                                                (county.length > 0 ? county + '<br />' : '') +
                                                                (postcode.length > 0 ? postcode + '<br />' : '')
                                                        }
                                                    }
                                                ]
                                            }
                                            :
                                            {} 
                                            )
                                        },

                                        {
                                            "div":
                                            (
                                            //dont worry about the below if all 3 fields are empty.
                                             email.length > 0 || tel.length > 0 || type.lenth > 0 ?
                                            {
                                                attributes: { "className": "contentContainer" },
                                                children: [
                                                    {
                                                        "p":
                                                        (
                                                        //email field exists.
                                                         email.length > 0 ?
                                                        {
                                                            children: [
                                                                { "strong": { text: "Email: " + email} }
                                                            ]
                                                        }
                                                        :
                                                        //no p.
                                                        {}
                                                        )
                                                    },
                                                    {
                                                        "p":
                                                        (
                                                        //telephone field exists.
                                                         tel.length > 0 ?
                                                        {
                                                            children: [
                                                                { "strong": { text: "Tel: " + tel} }
                                                            ]
                                                        }
                                                        :
                                                        //no p.
                                                        {}
                                                        )
                                                    },
                                                    {
                                                        "p":
                                                        (
                                                        //type field exists.
                                                        type.length > 0 ?
                                                        {
                                                            children: [
                                                                { "strong": { text: type} }
                                                            ]
                                                        }
                                                        :
                                                        //no p.
                                                        {}
                                                        )
                                                    }
                                                ]
                                            }
                                            :
                                            //no div if no results.
                                            {}
                                            )
                                        },

                                        {
                                            "div":
                                            (
                                            (branchTypeID != 4 && branchTypeID != 1) && branchLive != 0 ?
                                            {
                                                //<div class="mainAdLinkGMaps"//if we are not a charity shop.
                                                attributes: { "className": "mainAdLinkGMaps" },
                                                children: [
                                                    {
                                                        "div": {
                                                            //<div class="readMore">//link div.
                                                            attributes: { "className": "readMore" },
                                                            children: [
                                                                {
                                                                    "a": {
                                                                        //<a href="" title="Visit the branch site">Visit branch site</a>//a tag to branch site
                                                                        attributes: { "href": friendlyurl, "title": "Visit the branch site", "target": "_blank" },
                                                                        styles: { "float": "left", "text-align": "left" },
                                                                        text: "Visit branch site"
                                                                    }
                                                                }
                                                            ]
                                                        }
                                                    }
                                                ]
                                            }
                                            :
                                            {}
                                            )
                                        }
                                    ]
                                }
                            }
                        )
                    );
                }
            }

            //append our contents to our main div.
            containerDivElement.appendChild(obj3DivContainer);
            // set the zoom level to include all points plotted and reset the center.
            gMaps.map.setZoom(gMaps.map.getBoundsZoomLevel(bounds) - 1);
            gMaps.map.setCenter(bounds.getCenter());
            $("#map-overlay").hide();
        });
    },

    // function to place markers
    GMapsCreateMarker: function (point, friendlyurl, html, branchTypeID, branch_live) {

        //change marker type depending on what we are.        
        if (branchTypeID == 1) {
            gMaps.icon.image = "/icons/maps/NCCMarker.png";
            var marker = new GMarker(point, { icon: gMaps.icon });
        } else if (branchTypeID == 2) {
            gMaps.icon.image = "/icons/maps/AdoptionMarker.png";
            var marker = new GMarker(point, { icon: gMaps.icon });
        } else if (branchTypeID == 3) {
            gMaps.icon.image = "/icons/maps/BranchMarker.png";
            var marker = new GMarker(point, { icon: gMaps.icon });
        } else if (branchTypeID == 4) {
            gMaps.icon.image = "/icons/maps/ShopMarker.png";
            var marker = new GMarker(point, { icon: gMaps.icon });
        } else {
            var marker = new GMarker(point);
        }

        // set mouse over and click events for each brand.
        GEvent.addListener(marker, "mouseover", function () { marker.openInfoWindowHtml(html); });

        if ((branchTypeID != 4 && branchTypeID != 1) && branch_live != 0) {
            GEvent.addListener(marker, "click", function () { window.open(friendlyurl); });
        }

        return marker;
    },
    resetPanels: function () {
        $("#pnlBranchSearch").hide();
        $("#NoResults").hide();
        $("#pnlBranches").show();
    },
    //initialize the page.
    init: function () {
        $("#pnlBranches").show();
        $("#btnSearch").click(gMaps.GMapsLoader);
        $("#aBack").click(gMaps.resetPanels);
        $("#txtSearchBranches").keypress(function (e) {
            if (e.keyCode == 13 || e.charCode == 13) { gMaps.GMapsLoader(); return false; };
        });
    }
}

/* on page load */
$(document).ready(gMaps.init);

