function doMasonry() {
    resizing = false;
    if ($("#right_col .single, .reports").length > 0) {
        $('#right_col, .reports, .white').masonry({
            itemSelector: 'div.box, div.select_container',
            columnWidth: 310,
            gutterWidth: 20,
            isAnimated: $(".reports").length > 0
        });
    }
}

var lastKnownSize = ''

function iphoneMoveStuff() {
    if ($("#left_col div.up").length <= 0) {
        $("#right_col .box").removeClass("masonry-brick").removeAttr("style").attr("data-moved", "true").insertBefore("#left_col div:first");
    } else {
        $("#right_col .box").removeClass("masonry-brick").removeAttr("style").attr("data-moved", "true").insertAfter("#left_col div.up:last");
    }
    $("#right_col").hide();
}

function iphoneDropdowns() {
    $("#left_col .dropdown").each(function () {
        var html = '<option value="">Choose…</option>';
        $(this).find("a").each(function () {
            html += '<option value="' + $(this).attr("href") + '">' + $(this).text() + '</option>';
        });
        html = '<div class="iphone_dropdown"><h2>' + $(this).find("h2").text() + '</h2><select name="" class="iphone_select">' + html + '</select></div>';
        $(html).insertBefore("#left_col div:first");
        $(this).hide();
    });
}

function resizeStuff() {

    if (lastKnownSize == '') {
        lastKnownSize = $("body").width();
        if (lastKnownSize == 310) {
            iphoneMoveStuff();
            iphoneDropdowns();
        }
    }

    if (lastKnownSize != '' && lastKnownSize < $("body").width()) {
        // console.log("growing up!");
        lastKnownSize = $("body").width();
        if ($("#right_col:visible").length <= 0) {
            $("#left_col div[data-moved]").appendTo("#right_col").removeAttr("data-moved");
            $("#right_col").show();
        }

        $("#left_col div:hidden").show();
        $("#left_col div.iphone_dropdown").remove();

    }

    if (lastKnownSize != '' && lastKnownSize > $("body").width()) {
        // console.log("shrinking!");
        lastKnownSize = $("body").width();
        if ($("#right_col:visible").length > 0) {
            if (lastKnownSize == 310) {
                iphoneMoveStuff();
                iphoneDropdowns();
            }
        }
    }

}

/**********************************************
START - TRILLIUM CODE
***********************************************/
function AddAsFavourite(inTitle, inUrl) {
    var params = {
        PageTitle: inTitle, //window.document.title
        PageUrl: inUrl //window.location.pathname
    };
    $.ajax({
        type: "POST",
        url: "/WebServices/AddFav.aspx/AddAsFavourite",
        data: JSON.stringify(params),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var x = 1;
            // Do something interesting here.
        },
        error: function (msg) {
            var x = 1;
            // Do something interesting here.
        }
    });
}

function RemoveAsFavourite(inUrl) {
    var params = {
        PageUrl: inUrl
    };
    $.ajax({
        type: "POST",
        url: "/WebServices/AddFav.aspx/RemoveAsFavourite",
        data: JSON.stringify(params),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var x = 1;
            // Do something interesting here.
        },
        error: function (msg) {
            var x = 1;
            // Do something interesting here.
        }
    });
}

/**********************************************
END - TRILLIUM CODE
***********************************************/

$(document).ready(function () {

    /**********************************************
    START - TRILLIUM CODE
    ***********************************************/

    if (typeof Challow_Loader != "undefined") {
        Challow_Loader();
    }

    /**********************************************
    END - TRILLIUM CODE
    ***********************************************/

    $(".header_add_to_faves, .header_in_faves").live("mouseover", function (e) {
        e.stopPropagation();
        return false;
    }).live("mouseout", function (e) {
        e.stopPropagation();
        return false;
    });

    $("#header ul li:last a").live("mouseenter", function () {
        if (lastKnownSize != 310) {
            if (!$(this).hasClass("starred")) {
                var offset = $(this).offset();
                $('<div class="header_add_to_faves">add to favourites</div>').appendTo("body").css({ display: "block", top: offset.top + 23, left: offset.left - 53 });
            } else {
                var offset = $(this).offset();
                $('<div class="header_in_faves">in favourites</div>').appendTo("body").css({ display: "block", top: offset.top + 23, left: offset.left - 40 });
            }
            $(this).addClass("star_hovered");
        }
    }).live("mouseleave", function () {
        if (lastKnownSize != 310) {
            $(".header_add_to_faves, .header_in_faves").remove();
            $(this).removeClass("star_hovered");
        }
    });

    $("#header ul li:last a").live("click", function () {
        var offset = $(this).offset();
        $(".header_add_to_faves, .header_in_faves").remove();
        if ($(this).hasClass("starred")) {
            /**********************************************
            START - TRILLIUM CODE
            ***********************************************/
            RemoveAsFavourite(window.location.pathname);
            /**********************************************
            END - TRILLIUM CODE
            ***********************************************/

            $(this).find("span:last").text('add to favourites');
            if (lastKnownSize != 310) {
                $('<div class="header_in_faves">removed</div>').appendTo("body").css({ display: "block", top: offset.top + 23, left: offset.left - 40 });
            }
            $(this).removeClass("starred");
        } else {
            /**********************************************
            START - TRILLIUM CODE
            ***********************************************/
            AddAsFavourite(window.document.title, window.location.pathname);
            /**********************************************
            END - TRILLIUM CODE
            ***********************************************/

            $(this).find("span:last").text('in favourites');
            if (lastKnownSize != 310) {
                $('<div class="header_in_faves">added</div>').appendTo("body").css({ display: "block", top: offset.top + 23, left: offset.left - 40 });
            }
            $(this).addClass("starred");
        }
        return false;
    });


    $(".star_alt").live("mouseenter", function () {
        if (!$(this).hasClass("starred")) {
            if (lastKnownSize != 310) {
                var offset = $(this).offset();
                $('<div class="add_to_faves">add to favourites</div>').appendTo("body").css({ display: "block", top: offset.top - 33, left: offset.left - 100 });
            }
        } else {
            if (lastKnownSize != 310) {
                var offset = $(this).offset();
                $('<div class="in_faves">in favourites</div>').appendTo("body").css({ display: "block", top: offset.top - 33, left: offset.left - 71 });
            }
        }
        $(this).addClass("star_hovered");
    }).live("mouseleave", function () {
        $(".add_to_faves, .in_faves").remove();
        $(this).removeClass("star_hovered");
    });

    $(".star_alt").live("click", function () {
        var offset = $(this).offset();
        $(".add_to_faves, .in_faves").remove();
        if ($(this).hasClass("starred")) {
            /**********************************************
            START - TRILLIUM CODE
            ***********************************************/
            RemoveAsFavourite($(this).attr("data-url"));
            /**********************************************
            END - TRILLIUM CODE
            ***********************************************/

            if (lastKnownSize != 310) {
                $('<div class="in_faves">removed</div>').appendTo("body").css({ display: "block", top: offset.top - 33, left: offset.left - 71 });
            }
            $(this).removeClass("starred");
        } else {
            /**********************************************
            START - TRILLIUM CODE
            ***********************************************/
            AddAsFavourite($(this).attr("data-title"), $(this).attr("data-url"));
            /**********************************************
            END - TRILLIUM CODE
            ***********************************************/

            if (lastKnownSize != 310) {
                $('<div class="in_faves">added</div>').appendTo("body").css({ display: "block", top: offset.top - 33, left: offset.left - 71 });
            }
            $(this).addClass("starred");
        }
        return false;
    });

    // all links with class "partner" will open the partner only modal window (the content of the modal has to be in the document tree for this to work)
    if (typeof $.colorbox != 'undefined') {
        $(".partner").colorbox({ inline: !0, width: "350px", fixed: false, href: "#partner", scrolling: false })
    }

    // focus/blur for the partner modal window
    $(".partner_popup form .t").blur(function () {
        if ($(this).val() == '') $(this).val($(this).attr("data-placeholder"));
    }).focus(function () {
        if ($(this).val() == $(this).attr("data-placeholder")) $(this).val('');
        if ($(this).attr("data-placeholder") == "Password") {
            $(this).hide();
            $('.partner_popup form input[type="password"]').attr("style", "").focus();
        }
    });

    // this is the click event for the favourites/downloads sections of my dashboard
    $(".dashboard span.delete").live("click", function () {
        var elem = $(this).closest("div.dashboard");
        
        /**********************************************
        START - TRILLIUM CODE
        ***********************************************/
        var elemTR = $(this).closest("tr");
        var elemRemove = $(elemTR).find("td .icons");
        RemoveAsFavourite($(elemRemove).attr("href"));

        elemTR.fadeOut(function () {
            
            /**********************************************
            END - TRILLIUM CODE
            ***********************************************/

            $(this).remove();

            if ($(elem).find(".delete").length <= 0) {
                $(elem).find("table").remove();
                if ($(elem).hasClass("faves")) {
                    $('<p>You do not currently have any favourite items. Favourites can be added wherever you see this symbol: <span>&nbsp;<span class="thestar">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></span></p>').appendTo($(elem));
                } else if ($(elem).hasClass("downloads")) {
                    $('<p>You do not currently have any downloaded items. You can download reports, partner briefings and more.</p>').appendTo($(elem));
                }
                $(elem).find("span.edit").removeClass("editing");
            }
            doMasonry();
        });
    });

    // this is click event when clicking on "edit" in my dashboard
    $(".dashboard h2.blue span.edit").live("click", function () {
        if (!$(this).hasClass("editing")) {
            $(this).addClass("editing");
            $(this).closest("div.dashboard").find("div.hidden").show();
            $(this).closest("div.dashboard").find(".read_more").remove();
            $(this).closest("div.dashboard").find("span.delete").fadeIn(200);
            doMasonry();
        } else {
            $(this).removeClass("editing");
            $(this).closest("div.dashboard").find("span.delete").fadeOut(200, function () {
                $(this).attr("style", "display: none;");
            });
        }
    });

    /* rounded corners for IE8 – on IE6/7 rounds some elements fine but others with artifacts, IE6/7 are using PIE.htc and we are not using PIE.htc on IE8 because it breaks the layout for some reason */
    if (!Modernizr.borderradius && $.browser.msie && jQuery().corner) {
        $(".box").filter(function (index) {
            return $(this).parent().filter("[id='share_container']").length == 0;
        }).corner();
        $("nav a").corner("6px");
        $(".dashboard h2.blue span.edit").corner("6px");
    }

    $("a.share_link").live("click", function () {
        if ($("#share_container").length > 0) {
            if ($("#share_container").is(":visible")) {
                $("#share_container").hide();
            } else {
                $("#share_container").show();
            }
            return false;
        }
    });

    $("#homepage .box").live("mouseenter", function () {
        if (Modernizr.borderradius) $(this).addClass("hovered");
    }).live("mouseleave", function () {
        if (Modernizr.borderradius) $(this).removeClass("hovered");
    });

    $("#homepage .box").filter(":not('.no_linking')").click(function (event) {
        event.preventDefault();
        document.location.href = $(this).find("a:first").attr("href");
    });

    $(".iphone_select").live("change", function () {
        document.location.href = $(this).val();
    });

    resizeStuff();

    $(".sheet").click(function (event) {
        event.preventDefault();
        document.location.href = $(this).find("a:first").attr("href");
    });

    $(".date_container").click(function (event) {
        event.preventDefault();
        document.location.href = $(this).find("a:first").attr("href");
    });

    $(".events_show a").click(function () {
        var elem = $(this);
        var hiddenDiv = $(this).closest("div.box").find("div.hidden");
        if ($(hiddenDiv).length > 0) {
            if ($(elem).closest("div").hasClass("dashboard")) $(elem).parent().remove();
            if ($(hiddenDiv).is(":visible")) {
                $(this).removeClass("darr").addClass("rarr");
                $(elem).text('Show more');
                $(hiddenDiv).hide();
                doMasonry();
            } else {
                $(this).removeClass("rarr").addClass("darr");
                var opened = $(".box").find("div.hidden:visible");
                if ($(opened).length > 0) {
                    $(opened).closest("div.box").find("p.events_show a:first").click();
                }
                $(elem).text('Show less');
                $(hiddenDiv).show();
                doMasonry();
            }
        }
        return false;
    });

    $(".reports_show").click(function () {
        var elem = $(this);
        var hiddenDiv = $(this).closest("div.box").find("div.hidden");
        if ($(hiddenDiv).length > 0) {
            if ($(hiddenDiv).is(":visible")) {
                $(this).removeClass("darr").addClass("rarr");
                $(elem).text('Show more');
                $(hiddenDiv).hide();
                doMasonry();
            } else {
                $(this).removeClass("rarr").addClass("darr");
                var opened = $(".reports").find("div.hidden:visible");
                if ($(opened).length > 0) {
                    $(opened).closest("div.box").find("a.show_more").click();
                }
                $(elem).text('Show less');
                $(hiddenDiv).show();
                doMasonry();
            }
        }
        return false;
    });

    if ($("input.event_email").length > 0) {
        $("input.event_email").focus(function () {
            if ($(this).val() == 'Email address') $(this).val('');
        });
        $("input.event_email").blur(function () {
            if ($(this).val() == '') $(this).val('Email address');
        });
    }

    doMasonry();

});

var shownMarkers = 0;

function InfoBox(opts) {
    google.maps.OverlayView.call(this);
    this.latlng_ = opts.latlng;
    this.map_ = opts.map;
    this.offsetVertical_ = -240;
    this.offsetHorizontal_ = -73;
    this.height_ = 180;
    this.width_ = 310;

    var me = this;
    this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function () {
        return me.panMap.apply(me);
    });

    this.setMap(this.map_);
}

if (typeof google != "undefined" && google.maps != null) {
    InfoBox.prototype = new google.maps.OverlayView();
}

InfoBox.prototype.remove = function () {
    if (this.div_) {
        this.setMap(null);
        $(this.div_).remove();
        this.div_ = null;
    }
};

InfoBox.prototype.draw = function () {
    this.createElement();
    if (!this.div_) return;

    var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (!pixPosition) return;

    this.div_.style.width = this.width_ + "px";
    this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
    this.div_.style.height = this.height_ + "px";
    this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
    this.div_.style.display = 'block';
};

InfoBox.prototype.createElement = function () {
    var panes = this.getPanes();
    var div = this.div_;
    if (!div) {

        div = this.div_ = document.createElement("div");
        div.style.border = "0px none";
        div.style.position = "absolute";
        div.style.background = "url('/images/sprite.png')";
        div.style.backgroundPosition = "-350px -142px";
        div.style.backgroundRepeat = "no-repeat";
        div.style.width = this.width_ + "px";
        div.style.height = this.height_ + "px";
        div.className = "map_info";
        div.style.display = 'none';

        panes.floatPane.appendChild(div);
        $('#map_text').clone().appendTo($(".map_info")).show();
        this.panMap();

    } else if (div.parentNode != panes.floatPane) {
        panes.floatPane.appendChild(div);
    }
}

InfoBox.prototype.panMap = function () {

    var map = this.map_;
    var bounds = map.getBounds();
    if (!bounds) return;

    var position = this.latlng_;

    var iwWidth = this.width_;
    var iwHeight = this.height_;

    var iwOffsetX = this.offsetHorizontal_;
    var iwOffsetY = this.offsetVertical_;

    var padX = 60;
    var padY = 40;

    var mapDiv = map.getDiv();
    var mapWidth = mapDiv.offsetWidth;
    var mapHeight = mapDiv.offsetHeight;
    var boundsSpan = bounds.toSpan();
    var longSpan = boundsSpan.lng();
    var latSpan = boundsSpan.lat();
    var degPixelX = longSpan / mapWidth;
    var degPixelY = latSpan / mapHeight;

    var mapWestLng = bounds.getSouthWest().lng();
    var mapEastLng = bounds.getNorthEast().lng();
    var mapNorthLat = bounds.getNorthEast().lat();
    var mapSouthLat = bounds.getSouthWest().lat();

    var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
    var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
    var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
    var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;

    var shiftLng =
      (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
      (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
    var shiftLat =
      (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
      (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

    var center = map.getCenter();

    var centerX = center.lng() - shiftLng;
    var centerY = center.lat() - shiftLat;

    map.setCenter(new google.maps.LatLng(centerY, centerX));

    google.maps.event.removeListener(this.boundsChangedListener_);
    this.boundsChangedListener_ = null;
};

function initializeMap() {
    if (typeof google != "undefined") {
        var latlng = new google.maps.LatLng(mapAddress[0][1], mapAddress[0][2]);
        var myOptions = {
            zoom: 16,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            streetViewControl: false,
            mapTypeControl: false,
            zoomControl: true,
            panControl: true
        };
        var map = new google.maps.Map(document.getElementById("map"), myOptions);
        setMarkers(map, mapAddress);
        setTimeout(function () {
            google.maps.event.trigger(marker, 'click');
        }, 1200);
    }
}

var mapAddress = [
  ['Address', 51.498971, -0.135014, 1]
];

function setMarkers(map, locations) {
    var image = new google.maps.MarkerImage('/images/sprite.png');
    var shape = {
        coord: [1, 1, 1, 20, 18, 20, 18, 1],
        type: 'poly'
    };
    for (var i = 0; i < locations.length; i++) {
        var item = locations[i];
        var myLatLng = new google.maps.LatLng(item[1], item[2]);
        marker = new RichMarker({
            position: myLatLng,
            map: map,
            draggable: false,
            shadow: false,
            content: '<a id="map_marker"></a>'
        });
        google.maps.event.addListener(marker, "click", showInfoDialog);
    }

}

function showInfoDialog() {
    shownMarkers++;
    if (shownMarkers == 1) {
        var infoBox = new InfoBox({ latlng: this.getPosition(), map: this.map });
    }
}

$(window).load(function () {

    if (!$.browser.msie) {
        setTimeout(function () {
            setInterval(function () {
                resizeStuff();
            }, 50);
        }, 1000);
    }

    doMasonry();

    if ($("#homepage").length > 0) {
        $('#homepage').masonry({
            itemSelector: 'div.box',
            columnWidth: 310,
            gutterWidth: 20,
            isAnimated: !Modernizr.csstransitions
        });

        /* resize the body onload and resize it back to trigger a redraw of masonry, this only affects/it's needed on the homepage and it's only needed for IE6/7 (does not affect IE8) */
        if ($.browser.msie && !jQuery().corner && typeof doIEMasonry == "undefined") { // we are only loading jQuery.corner on IE8 so this is good way to know this browser is IE8
            setTimeout(function () {
                $("body").css({ width: 975 });
                setTimeout(function () {
                    $("body").css({ width: 990 });
                }, 50);
            }, 50);
        }

    }

    if (typeof swfobject != "undefined") {
        swfobject.embedSWF("/swf/britain_2.swf", "home_flash_two", "290", "290", "10.0.0", "/swf/expressInstall.swf");
        swfobject.embedSWF("/swf/network_animation.swf", "home_flash_one", "290", "290", "10.0.0", "/swf/expressInstall.swf");
        swfobject.embedSWF("/swf/thinkbig.swf", "home_flash_three", "290", "290", "10.0.0", "/swf/expressInstall.swf");
    }
   
    if ($("#map").length > 0) {
        initializeMap();
    }

});
