/*
Author: Prashanth Thiyagalingam, Daniel Reed
*/
var verticalResize = true;
var hiddenRibbon = false;
var dashboard = false;
var main;

$(document).ready(function () {
    dashboard = $("#DeveloperDashboard table").length > 0;
    main = $("#main");
    resizeText();

    if (hiddenRibbon) {
        FPFixRibbonAndWorkspaceDimensionsForResize();
        $(window).unbind('resize').resize(FPFixRibbonAndWorkspaceDimensionsForResize);
    }
    else {
        $("#s4-workspace").resize(resizeWorkspace);
    }

    var lightboxImages = $("a[rel='FBGallery'], a[rel='right_photo']");
    if (lightboxImages.length > 0) {
        lightboxImages.fancybox({
            'opacity': true,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'titlePosition': 'inside'
        });
    }

    $("#DolphinDialogBox").fancybox({
        'width': '80%',
        'height': '100%',
        'autoScale': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'type': 'iframe',
        'showCloseButton': true
    });

    initialiseMenu();
    initialiseCarousel();
});


var load = false;
var operating = false;

var showPrev = false;
var showNext = true;

var fade = true;

var carousel;
var next;
var prev;

var currentIndex = 0;
var imageCount = 0;

function initialiseCarousel() {
    carousel = $(".carousel");
    prev = carousel.find(".prev");
    next = carousel.find(".next");
    imageCount = carousel.find(".carousel_image").length - 1;
    if (fade) {
        $(".carousel").addClass("fade");
        operating = true;
        load = true;
    }

    loadImage();
    setInterval(nextTimedImage, 8000);
}

function isiPhone() {
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

function loadImage() {
    var carouselImage = carousel.find(".carousel_image:eq(" + currentIndex + ")");
    if (carouselImage.find('.thumb').length == 0) {
        return false;
    }

    showLoading(true);

    if (!fade) {
        var pane = carousel.find(".pane");
        pane.width(pane.width() + 500);
    }


    var src = carouselImage.find('.src');
    var thumb = carouselImage.find('.thumb');
    var text = carouselImage.find('.text');

    carouselImage.children().remove();

    if (src.length > 0) {
        carouselImage.append("<div class='inner'><a rel='slideshow' href='" + src.html() + "' title='" + text.html() + "'><img src='" + thumb.html() + "' onload='imageLoaded(this)' onerror='imageError(this)'/></a></div><div class='description'><div class='overlay'></div><div class='words'><div>" + text.html() + "</div></div></div>");
        carouselImage.find("a[rel='slideshow']").fancybox({
            'opacity': true,
            'transitionIn': 'elastic',
            'transitionOut': 'none'

        });
    }
    else {
        carouselImage.append("<div class='inner'><img src='" + thumb.html() + "' onload='imageLoaded(this)' onerror='imageError(this)'/></div><div class='description'><div class='overlay'></div><div class='words'><div>" + text.html() + "</div></div></div>");
    }
    return true;
}

//swipe between images

function transition(direction) {
    showButtons();
    if (fade) {
        fadePane(direction);
    }
    else {
        swipePane(direction);
    }
}

function swipePane(direction) {
    if (direction < 0) {
        carousel.find('.pane').animate({ left: '+=500' }, { duration: 800, complete: function () { operating = false; } });
    }
    else {
        carousel.find('.pane').animate({ left: '-=500' }, { duration: 800, complete: function () { operating = false; } });
    }
}

// fade between images
function fadePane(direction) {
    if (direction > 0) {
        carousel.find(".pane .carousel_image:eq(" + currentIndex + ")").fadeIn(1000, function () { carousel.find(".pane .carousel_image:not(:eq(" + currentIndex + "))").hide(); operating = false; });
    }
    else {
        carousel.find(".pane .carousel_image:eq(" + currentIndex + ")").show();
        carousel.find(".pane .carousel_image:eq(" + (currentIndex + 1) + ")").fadeOut(1000, function () { carousel.find(".pane .carousel_image:not(:eq(" + currentIndex + "))").hide(); operating = false; });
    }
}

function showLoading(show) {
    carousel.find(".loading").toggle(show);
}

//fade in and out buttons as appropriate
function showButtons() {
    showPrev = currentIndex > 0;
    showNext = currentIndex < imageCount;

    if (showPrev) {
        prev.stop(true, false).fadeTo(200, 1);
    }
    else {
        prev.stop(true, false).fadeTo(200, 0);
    }
    if (showNext) {
        next.stop(true, false).fadeTo(200, 1);
    }
    else {
        next.stop(true, false).fadeTo(200, 0);
    }
}

function previousImage() {
    if (!operating) {
        operating = true;
        if (currentIndex > 0) {
            currentIndex--;
            transition(-1)
        }
    }
}

function nextImage() {
    if (!operating) {
        operating = true;
        if (currentIndex < imageCount) {
            currentIndex++;
            load = true;
            if (!loadImage()) {
                transition(1);
            }
        }
    }
}

function nextTimedImage() {
    if (!operating) {
        operating = true;
        if (currentIndex < imageCount) {
            currentIndex++;
        }
        else {
            currentIndex = 0;
        }
        load = true;
        if (!loadImage()) {
            transition(1);
        }
    }
}

function imageLoaded(image) {
    if (load) {
        load = false;
        transition(1);
    }
    else {
        operating = false;
    }
    showLoading(false);
}

function imageError(image) {
    showLoading(false);
    $(image).attr("src", "/_layouts/images/FremantlePorts.Internet/not_found.png");
    if (load) {

        load = false;
        transition(1);
    }
    else {
        operating = false;
    }
}

function initialiseMenu() {
    //if below ie8
    if ($.browser.msie && $.browser.version < 8) {
        $(".menu-horizontal .root > li > a").each(function () {
            var span = $(this).find("span > span");
            var margin = (($(this).height() - span.height()) / 2);
            $(this).height($(this).height() - margin).css("display", "block").css("margin-top", margin);
        });
    }
    //if below firefox 4
    if ($.browser.mozilla && parseFloat($.browser.version) < 2) {
        $(".menu-horizontal .root > li > ul").css("margin-top", 38).css("margin-left", -165);
    }

    //identify the menu items with children
    $(".menu li").each(function () {
        if ($(this).children("ul").length > 0) {
            $(this).addClass("haschildren");
        }
        if ($(this).find("li.selected").length > 0) {
            $(this).addClass("selected");
        }
    });

    //identify the first and last menu items
    $(".menu-horizontal > ul").each(function () {
        $(this).children("li:first").addClass("first");
        $(this).children("li:last").addClass("last");
    });


    $(".menu-horizontal .root > li").hover(
	  function () {
	      var ul = $(this).children("ul");
	      var other = $(".menu-horizontal .root > li > ul").not(ul);
	      other.stop(true, false).fadeTo(0, 0, function () { other.hide(); $(".menu-horizontal .root li ul li ul").css({ height: 0, display: 'none' }); });
	      $(this).children("ul").stop(true, false).height('auto').css({ 'z-index': 1000 }).fadeTo(0, 1, function () { ul.css({ opacity: '' }); });
	  },
	  function () {
	      var ul = $(this).children("ul");
	      ul.stop(true, false).delay(600).fadeTo(0, 0, function () { ul.hide().height(0); $(".menu-horizontal .root li ul li ul").css({ height: 0, display: 'none' }); });
	  }
	);



    $(".menu-horizontal .root li ul li.haschildren").hover(
	  function () {
	      var ul = $(this).find("ul");
	      ul.stop(true, false);

	      //calculate size to expand to 
	      //var other = ul.parent().parent().find("li ul").not(ul);
	      ul.css({ 'visibility': 'hidden', 'display': 'block', 'height': 'auto' });
	      var ulheight = ul.height();

	      ul.css({ 'visibility': 'visible', 'display': 'none' });
	      ul.css("height", 0).show().animate({ height: ulheight }, { duration: 400, complete: function () { } });
	  },
	  function () {
	      var ul = $(this).find("ul");
	      ul.stop(true, false).delay(10).animate({ height: 0 }, { duration: 400, complete: function () { ul.css({ height: 0, display: 'none' }); } });
	  }
	);
}

function resetWorkspace() {
    $("#main, .left_content, .mid_content, .right_content, .white_pane").css("min-height", "0px");
}

function resizeWorkspace() {
    //make sure we are not in a dialog
    if ($(".ms-dialog").length == 0) {
        resetWorkspace();

        var headerFooterHeight = $(".page").height() - main.height();

        //stretch the footer to the bottom
        if (verticalResize && !dashboard && (main.height() < $("#s4-workspace").height() - headerFooterHeight)) {

            main.css("min-height", $("#s4-workspace").height() - headerFooterHeight);
        }
        //make all the columns the same height
        main.children("div").css("min-height", main.height());
        $(".white_pane").css("min-height", main.height() - $(".top_content").height());

        if ($.browser.msie != null && $.browser.version < 8) {
            $(".carousel").css("position", "relative");
        }
    }
}

/* SiteMap Organizer */
function SiteMapOrganize() {
    $('li > ul').each(function (i) {

        var parent_li = $(this).parent('li');

        if ($(parent_li).hasClass('SiteMapLiNode')) {
            parent_li.addClass('folderClose');

            var sub_ul = $(this).remove();
            parent_li.wrapInner('<a/>').find('a').click(function () {
                var imageSource = $(parent_li).children().children('img').attr('src').toString();

                if (imageSource.indexOf("node-closed.gif") > -1)
                    $(parent_li).children().children('img').attr('src', imageSource.replace('node-closed.gif', 'node-open.gif'))
                else if (imageSource.indexOf("node-open.gif") > -1)
                    $(parent_li).children().children('img').attr('src', imageSource.replace('node-open.gif', 'node-closed.gif'))


                if (sub_ul.is(":visible")) {
                    sub_ul.slideUp(1000);
                } else {
                    sub_ul.slideDown(1000);
                }

            });

            parent_li.append(sub_ul);
        }
    });
    // Hide all lists except the outermost.
    $('ul ul').filter(".SiteMapULNode").hide();

}
/* End */

/* Dolphin Plotting */


var map = null;
var geocoder;
var numberOfDolphinsArr;
var arrayCnt = 0;

var arrDolphinCount = new Array();
var arrDate = new Array();
var arrDtTime = new Array();
var arrDirections = new Array();
var arrDolactivity = new Array();
var arrDolLongitude = new Array();
var arrLatitude = new Array();

var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];

function initialize() {
    var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi?key=" + MapKey + "&callback=DolphinPageMaps";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function DolphinPageMaps() {
    google.load("maps", "2", { "callback": loadDolphinPageMapApi });
}

function loadDolphinPageMapApi() {
    if (GBrowserIsCompatible()) {
        numberOfDolphinsArr = new Array();
        map = new GMap2(document.getElementById("map"));
        var latlng = new GLatLng(-32.05123, 115.73756)

        map.setCenter(latlng, 15);
        map.setUIToDefault();
        geocoder = new GClientGeocoder();
        var d = new Date();
        var monthNumber = d.getMonth() + 1;
        GEvent.addListener(map, 'click',
                    function (overlay, point) {
                        if (point) {
                            $("#txtLat").attr("value", point.x);
                            $("#txtLong").attr("value", point.y);
                            $("#TextBoxDolDate").attr("value", d.getDate() + "/" + monthNumber + "/" + d.getFullYear());
                            $("#DropDownListHour").attr("value", "01");
                            $("#DropDownListMinute").attr("value", "10");
                            $("#DropDownListAMPM").attr("value", "AM");
                            $find('modalPopupBehavior').show();
                        }
                    });
    }
}


function loadMarker() {
    var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi?key=" + MapKey + "&callback=LoadDolAdminMaps";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function LoadDolAdminMaps() {
    google.load("maps", "2", { "callback": loadDolphinAdminMapApi });
}

function loadDolphinAdminMapApi() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        var lat = $("#longtitudeHidden").val();
        var lang = $("#LatitudeHidden").val();
        var latlng = new GLatLng(-32.05123, 115.73756)

        map.setCenter(latlng, 15);
        map.setUIToDefault();
        geocoder = new GClientGeocoder();

        var latlng1 = new GLatLng(lat, lang);
        var marker1 = new GMarker(latlng1, { icon: getDolphinIcon() });
        map.addOverlay(marker1);
    }
}

function loadDolphinPage() {
    var options = {
        url: '/_layouts/FremantlePorts.Internet/AddDolphinMarker.aspx',
        tite: 'Dolphin Plotting',
        allowMaximize: true,
        showClose: true,
        width: 800,
        height: 800,
        dialogReturnValueCallback: function demoCallback(result, target) {
            if (result == SP.UI.DialogResult.OK) {
                SP.UI.Notify.addNotification('Dolphin Markings have been added successfully, Dolphin sightings will be updated shortly');
            }
            else if (result == SP.UI.DialogResult.cancel) {
                SP.UI.Notify.addNotification('Dolphin Markings Cancelled');
            }
        }
    };
    SP.UI.ModalDialog.showModalDialog(options);
}

function DolphinWPinitialize() {
    var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi?key=" + MapKey + "&callback=DolloadMaps";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function DolloadMaps() {
    google.load("maps", "2", { "callback": loadDolMapApi });
}

function loadDolMapApi() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("DolWPmap"));
        var latlng = new GLatLng(-32.05123, 115.73756)

        map.setCenter(latlng, 15);
        map.setUIToDefault();
        geocoder = new GClientGeocoder();

        var temarrDolphinCount = $("[id$=arrayDataDolphinCount]").val().split(",");
        var temarrDate = $("[id$=arrayDataDate]").val().split(",");
        var temarrDtTime = $("[id$=arrayDataTime]").val().split(",");
        var temarrDirections = $("[id$=arrayDataActivity]").val().split(",");
        var temarrDolactivity = $("[id$=arrayDataDirection]").val().split(",");
        var temarrDolLongitude = $("[id$=arrayDataLongitude]").val().split(",");
        var temarrLatitude = $("[id$=arrayDataLatitude]").val().split(",");

        if (temarrDolphinCount != null) {
            for (var a = 0; a < temarrDolphinCount.length; a++) {
                createStaticDolphinMarkers(temarrDate[a], temarrDtTime[a], temarrDolactivity[a], temarrDirections[a], temarrDolphinCount[a], temarrLatitude[a],
                    temarrDolLongitude[a]);
            }
        }
    }
}

function createStaticDolphinMarkers(Dt, DtTime, driections, Dolactivity, numberOfDolphins, lat, lang) {
    var latlng1 = new GLatLng(lang, lat);
    var marker1 = new GMarker(latlng1, { icon: getDolphinIcon() });
    GEvent.addListener(marker1, "click", function () {
        marker1.openInfoWindowHtml("Date & Time: " + Dt + "  " + DtTime + "<br />" + "Number of Dolphins: " + numberOfDolphins + "<br/>Direction of movement:  " + driections + "<br/>Activity:  " + Dolactivity);
    });
    map.addOverlay(marker1);

}

function createDummyMarker() {
    if ($("#TextBoxDolDate").attr("value") == "Click here to select a date") {
        $("#labelMandatory").show();
        return false;
    } else {
        var numOfDolphins = $("#DropDownListDolphinNumber").attr("value");
        var Dt = $("#TextBoxDolDate").attr("value");
        var DtTime = $("#DropDownListHour").attr("value") + ":" + $("#DropDownListMinute").attr("value") + " " + $("#DropDownListAMPM").attr("value");
        var driections = $("#DropDownListDirection").attr("value");
        var Dolactivity = $("#DropDownListActivity").attr("value");
        var Longitude = $("#txtLong").attr("value");
        var Latitude = $("#txtLat").attr("value");

        arrDolphinCount[arrayCnt] = numOfDolphins;
        arrDate[arrayCnt] = Dt;
        arrDtTime[arrayCnt] = DtTime;
        arrDirections[arrayCnt] = driections;
        arrDolactivity[arrayCnt] = Dolactivity;
        arrDolLongitude[arrayCnt] = Longitude;
        arrLatitude[arrayCnt] = Latitude;

        var marker2 = new GMarker(new GLatLng($("#txtLong").attr("value"), $("#txtLat").attr("value")), { icon: getDolphinIcon() });

        GEvent.addListener(marker2, "click", function () {
            marker2.openInfoWindowHtml("Date & Time: " + Dt + "  " + DtTime + "<br />" + "Number of Dolphins: " + numOfDolphins + "<br/>Direction of movement:  " + driections + "<br/>Activity:  " + Dolactivity);

        });
        map.addOverlay(marker2);
        arrayCnt = arrayCnt + 1;
        $("#labelMandatory").hide();
        HideModal();
    }
}

function getDolphinIcon() {
    var icon2 = new GIcon();
    icon2.image = "/_layouts/images/FremantlePorts.Internet/"
                + "dolphin-icon.PNG";
    icon2.iconAnchor = new GPoint(16, 16);
    icon2.infoWindowAnchor = new GPoint(16, 0);
    icon2.iconSize = new GSize(32, 32);
    icon2.shadowSize = new GSize(59, 32);

    return icon2;
}

function populateArrays() {
    var temDolCnt = arrDolphinCount.join(",");
    document.getElementById("arrayDataDolphinCount").value = temDolCnt;

    var temarrDate = arrDate.join(",");
    document.getElementById("arrayDataDate").value = temarrDate;

    var temarrDtTime = arrDtTime.join(",");
    document.getElementById("arrayDataTime").value = temarrDtTime;

    var temarrDolactivity = arrDolactivity.join(",");
    document.getElementById("arrayDataActivity").value = temarrDolactivity;

    var temarrDirections = arrDirections.join(",");
    document.getElementById("arrayDataDirection").value = temarrDirections;

    var temarrDolLongitude = arrDolLongitude.join(",");
    document.getElementById("arrayDataLongitude").value = temarrDolLongitude;

    var temarrLatitude = arrLatitude.join(",");
    document.getElementById("arrayDataLatitude").value = temarrLatitude;

    return true;
}

function ClosePopup() {
    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancelled clicked');
}

function addFremantleNotification(message) {
    SP.UI.Notify.addNotification(message);

}

/* End Dolphin Plotting */



/* Start Ports General Google Maps */

function PortsMapWPinitialize(isSpecific) {
    var script = document.createElement("script");
    if (isSpecific != "True")
        script.src = "http://www.google.com/jsapi?key=" + MapKey + "&callback=loadMaps";
    else
        script.src = "http://www.google.com/jsapi?key=" + MapKey + "&callback=loadMapsSpecific";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadMaps() {
    //AJAX API is loaded successfully. Now lets load the maps api     
    google.load("maps", "2", { "callback": loadPortsMapApi });
}

function loadMapsSpecific() {
    //AJAX API is loaded successfully. Now lets load the maps api     
    google.load("maps", "2", { "callback": loadPortsMapSpecificApi });
}

function loadPortsMapApi() {
    if (GBrowserIsCompatible()) {
        var latlng;
        map = new GMap2(document.getElementById("PortsWPMap"));
        var isOuterHarbourMap = $("[id$=isOuterHarbourMap]").val();

        if (isOuterHarbourMap == "True") {
            latlng = new GLatLng(-32.2262, 115.7562);
            map.setCenter(latlng, 12);
        }
        else {
            latlng = new GLatLng(-32.05123, 115.73756);
            map.setCenter(latlng, 15);
        }


        map.setUIToDefault();
        geocoder = new GClientGeocoder();
    }
}


function loadPortsMapSpecificApi() {
    if (GBrowserIsCompatible()) {
        var latlng;
        map = new GMap2(document.getElementById("PortsWPMap"));
        var isOuterHarbourMap = $("[id$=isOuterHarbourMap]").val();

        if (isOuterHarbourMap == "True") {
            latlng = new GLatLng(-32.2262, 115.7562);
            map.setCenter(latlng, 12);
        }
        else {
            latlng = new GLatLng(-32.05123, 115.73756);
            map.setCenter(latlng, 15);
        }

        map.setUIToDefault();
        geocoder = new GClientGeocoder();

        var temarrMapTitle = $("[id$=selectedCategoryHidden]").val().split(";");
        for (var a = 0; a < temarrMapTitle.length; a++) {
            if (temarrMapTitle[a] == "1")
                PortsBuildingMarkersLoad("true");
            if (temarrMapTitle[a] == "2")
                PortsBerthsMarkersLoad("true");
            if (temarrMapTitle[a] == "3")
                PortsGatesMarkersLoad("true");
            if (temarrMapTitle[a] == "4")
                PortsTouristsAttMarkersLoad("true");
            if (temarrMapTitle[a] == "5")
                PortsParkingMarkersLoad("true");
        }

    }
}


function PortsBuildingMarkersLoad(isOverlap) {
    gmarkers = [];
    htmls = [];
    to_htmls = [];
    from_htmls = [];

    if (isOverlap != "true")
        map.clearOverlays();

    var temarrMapTitle = $("[id$=arrayPortMapTitle]").val().split("#$%@^@");
    var temarrAddress = $("[id$=arrayPortMapAddress]").val().split("#$%@^@");
    var temarrComments = $("[id$=arrayPortMapComments]").val().split("#$%@^@");
    var temarrLongitude = $("[id$=arrayPortMapLongitude]").val().split("#$%@^@");
    var temarrLatitude = $("[id$=arrayPortMapLatitude]").val().split("#$%@^@");
    var isOuterHarbourMap = $("[id$=isOuterHarbourMap]").val();

    if (temarrMapTitle != null) {
        for (var a = 0; a < temarrMapTitle.length; a++) {
            if ((temarrLongitude != null) && (temarrLatitude != null))
                if ((temarrLongitude[a] != "Empty") && (temarrLatitude[a] != "Empty"))
                    createPortsGeneralMapMarker("", temarrMapTitle[a], temarrComments[a], temarrLongitude[a], temarrLatitude[a], getBuildingIcon(), isOuterHarbourMap);
                else if (temarrAddress[a] != "Empty")
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getBuildingIcon(), isOuterHarbourMap);
                else if (temarrAddress != null)
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getBuildingIcon(), isOuterHarbourMap);
        }
    }
}

function PortsBerthsMarkersLoad(isOverlap) {
    gmarkers = [];
    htmls = [];
    to_htmls = [];
    from_htmls = [];

    if (isOverlap != "true")
        map.clearOverlays();

    var temarrMapTitle = $("[id$=arrayPortBerthTitle]").val().split("#$%@^@");
    var temarrAddress = $("[id$=arrayPortBerthAddress]").val().split("#$%@^@");
    var temarrComments = $("[id$=arrayPortBerthComments]").val().split("#$%@^@");
    var temarrLongitude = $("[id$=arrayPortBerthLongitude]").val().split("#$%@^@");
    var temarrLatitude = $("[id$=arrayPortBerthLatitude]").val().split("#$%@^@");
    var isOuterHarbourMap = $("[id$=isOuterHarbourMap]").val();

    if (temarrMapTitle != null) {
        for (var a = 0; a < temarrMapTitle.length; a++) {
            if ((temarrLongitude != null) && (temarrLatitude != null))
                if ((temarrLongitude[a] != "Empty") && (temarrLatitude[a] != "Empty"))
                    createPortsGeneralMapMarker("", temarrMapTitle[a], temarrComments[a], temarrLongitude[a], temarrLatitude[a], getBerthsJettiesIcon(), isOuterHarbourMap);
                else if (temarrAddress[a] != "Empty")
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getBerthsJettiesIcon(), isOuterHarbourMap);
                else if (temarrAddress != null)
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getBerthsJettiesIcon(), isOuterHarbourMap);
        }
    }
}


function PortsGatesMarkersLoad(isOverlap) {
    gmarkers = [];
    htmls = [];
    to_htmls = [];
    from_htmls = [];

    if (isOverlap != "true")
        map.clearOverlays();

    var temarrMapTitle = $("[id$=arrayGatesTitle]").val().split("#$%@^@");
    var temarrAddress = $("[id$=arrayGatesAddress]").val().split("#$%@^@");
    var temarrComments = $("[id$=arrayGatesComments]").val().split("#$%@^@");
    var temarrLongitude = $("[id$=arrayGatesLongitude]").val().split("#$%@^@");
    var temarrLatitude = $("[id$=arrayGatesLatitude]").val().split("#$%@^@");
    var isOuterHarbourMap = $("[id$=isOuterHarbourMap]").val();

    if (temarrMapTitle != null) {
        for (var a = 0; a < temarrMapTitle.length; a++) {
            if ((temarrLongitude != null) && (temarrLatitude != null))
                if ((temarrLongitude[a] != "Empty") && (temarrLatitude[a] != "Empty"))
                    createPortsGeneralMapMarker("", temarrMapTitle[a], temarrComments[a], temarrLongitude[a], temarrLatitude[a], getGatesIcon(), isOuterHarbourMap);
                else if (temarrAddress[a] != "Empty")
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getGatesIcon(), isOuterHarbourMap);
                else if (temarrAddress != null)
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getGatesIcon(), isOuterHarbourMap);
        }
    }
}

function PortsTouristsAttMarkersLoad(isOverlap) {
    gmarkers = [];
    htmls = [];
    to_htmls = [];
    from_htmls = [];

    if (isOverlap != "true")
        map.clearOverlays();


    var temarrMapTitle = $("[id$=arrayTouristAttTitle]").val().split("#$%@^@");
    var temarrAddress = $("[id$=arrayTouristAttAddress]").val().split("#$%@^@");
    var temarrComments = $("[id$=arrayTouristAttComments]").val().split("#$%@^@");
    var temarrLongitude = $("[id$=arrayTouristAttLongitude]").val().split("#$%@^@");
    var temarrLatitude = $("[id$=arrayTouristAttLatitude]").val().split("#$%@^@");
    var isOuterHarbourMap = $("[id$=isOuterHarbourMap]").val();

    if (temarrMapTitle != null) {
        for (var a = 0; a < temarrMapTitle.length; a++) {
            if ((temarrLongitude != null) && (temarrLatitude != null))
                if ((temarrLongitude[a] != "Empty") && (temarrLatitude[a] != "Empty"))
                    createPortsGeneralMapMarker("", temarrMapTitle[a], temarrComments[a], temarrLongitude[a], temarrLatitude[a], getTouristsAttIcon(), isOuterHarbourMap);
                else if (temarrAddress[a] != "Empty")
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getTouristsAttIcon(), isOuterHarbourMap);
                else if (temarrAddress != null)
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getTouristsAttIcon(), isOuterHarbourMap);
        }
    }
}

function PortsParkingMarkersLoad(isOverlap) {
    gmarkers = [];
    htmls = [];
    to_htmls = [];
    from_htmls = [];

    if (isOverlap != "true")
        map.clearOverlays();

    var temarrMapTitle = $("[id$=arrayParkingTitle]").val().split("#$%@^@");
    var temarrAddress = $("[id$=arrayParkingAddress]").val().split("#$%@^@");
    var temarrComments = $("[id$=arrayParkingComments]").val().split("#$%@^@");
    var temarrLongitude = $("[id$=arrayParkingLongitude]").val().split("#$%@^@");
    var temarrLatitude = $("[id$=arrayParkingLatitude]").val().split("#$%@^@");
    var isOuterHarbourMap = $("[id$=isOuterHarbourMap]").val();

    if (temarrMapTitle != null) {
        for (var a = 0; a < temarrMapTitle.length; a++) {
            if ((temarrLongitude != null) && (temarrLatitude != null))
                if ((temarrLongitude[a] != "Empty") && (temarrLatitude[a] != "Empty"))
                    createPortsGeneralMapMarker("", temarrMapTitle[a], temarrComments[a], temarrLongitude[a], temarrLatitude[a], getParkingIcon(), isOuterHarbourMap);
                else if (temarrAddress[a] != "Empty")
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getParkingIcon(), isOuterHarbourMap);
                else if (temarrAddress != null)
                    createPortsGeneralMapMarker(temarrAddress[a], temarrMapTitle[a], temarrComments[a], "", "", getParkingIcon(), isOuterHarbourMap);
        }
    }
}

function createPortsGeneralMapMarker(address, name, html, interlong, interlat, icon, isQwinana) {
    if (address != "") {
        geocoder.getLatLng(
                address, function (point) {

                    var i = gmarkers.length;

                    if (icon != "")
                        var marker = new GMarker(point, { icon: icon, title: name });
                    else
                        var marker = new GMarker(point, { title: name });

                    map.addOverlay(marker);

                    // The info window version with the "to here" form open
                    to_htmls[i] = "<b>" + name + "</b>" + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
                       '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
                       '<input type="text" SIZE=40 name="saddr" id="saddr" value="" /><br><br>' +
                       '<INPUT style="background-color: #E66F26;color:#FFFFFF;border-color: #FFFFFF #FFFFFF #FFFFFF #FFFFFF;font:bold " value="Get Directions" TYPE="SUBMIT">' +
                       '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
                       '"/>';
                    // The info window version with the "to here" form open
                    from_htmls[i] = "<b>" + name + "</b>" + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
                       '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
                       '<input type="text" SIZE=40 name="daddr" id="daddr" value="" /><br><br>' +
                       '<INPUT style="background-color: #E66F26;color:#FFFFFF;border-color: #FFFFFF #FFFFFF #FFFFFF #FFFFFF;font:bold" value="Get Directions" TYPE="SUBMIT">' +
                       '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                       '"/>';

                    html = "<b>" + name + "</b>" + "<br/>" +
                           "<b>" + "Address: " + "</b>" + address + "<br /><br />" + html + "<br/>" + 'Directions:  <a href="javascript:tohere(' + i + ')">To here<\/a> - <a href="javascript:fromhere(' + i + ')">From here<\/a>';

                    GEvent.addListener(marker, "click", function () {
                        marker.openInfoWindowHtml(html);

                    });
                    gmarkers.push(marker);
                    htmls[i] = html;
                });
    }
    else if ((interlong != "") && (interlat != "")) {
        var i = gmarkers.length;
        var interlatlng = new GLatLng(interlong, interlat);

        if (icon != "")
            var marker = new GMarker(interlatlng, { icon: icon, title: name });
        else
            var marker = new GMarker(interlatlng, { title: name });

        map.addOverlay(marker);

        // The info window version with the "to here" form open
        to_htmls[i] = "<b>" + name + "</b>" + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
                       '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
                       '<input type="text" SIZE=40 name="saddr" id="saddr" value="" /><br><br>' +
                       '<INPUT style="background-color: #E66F26;color:#FFFFFF;border-color: #FFFFFF #FFFFFF #FFFFFF #FFFFFF;font:bold " value="Get Directions" TYPE="SUBMIT">' +
                       '<input type="hidden" name="daddr" value="' + interlatlng.lat() + ',' + interlatlng.lng() +
                       '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = "<b>" + name + "</b>" + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
                       '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
                       '<input type="text" SIZE=40 name="daddr" id="daddr" value="" /><br><br>' +
                       '<INPUT style="background-color: #E66F26;color:#FFFFFF;border-color: #FFFFFF #FFFFFF #FFFFFF #FFFFFF;font:bold" value="Get Directions" TYPE="SUBMIT">' +
                       '<input type="hidden" name="saddr" value="' + interlatlng.lat() + ',' + interlatlng.lng() +
                       '"/>';

        html = "<b>" + name + "</b>" + "<br/>" +
                          html + "<br/>" + 'Directions:  <a href="javascript:tohere(' + i + ')">To here<\/a> - <a href="javascript:fromhere(' + i + ')">From here<\/a>';

        GEvent.addListener(marker, "click", function () {
            marker.openInfoWindowHtml(html);

        });
        gmarkers.push(marker);
        htmls[i] = html;

    }

}

// functions that open the directions forms
function tohere(i) {
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}

function getBuildingIcon() {
    var icon2 = new GIcon();
    icon2.image = "/_layouts/images/FremantlePorts.Internet/"
                + "buildingicon.PNG";
    icon2.iconAnchor = new GPoint(16, 16);
    icon2.infoWindowAnchor = new GPoint(16, 0);
    icon2.iconSize = new GSize(30, 30);
    icon2.shadowSize = new GSize(59, 30);

    return icon2;
}

function getTouristsAttIcon() {
    var icon2 = new GIcon();
    icon2.image = "/_layouts/images/FremantlePorts.Internet/"
                + "touristicons.PNG";
    icon2.iconAnchor = new GPoint(16, 16);
    icon2.infoWindowAnchor = new GPoint(16, 0);
    icon2.iconSize = new GSize(30, 30);
    icon2.shadowSize = new GSize(59, 30);

    return icon2;
}

function getBerthsJettiesIcon() {
    var icon2 = new GIcon();
    icon2.image = "/_layouts/images/FremantlePorts.Internet/"
                + "Berthsicon.PNG";
    icon2.iconAnchor = new GPoint(16, 16);
    icon2.infoWindowAnchor = new GPoint(16, 0);
    icon2.iconSize = new GSize(30, 30);
    icon2.shadowSize = new GSize(59, 30);

    return icon2;
}

function getGatesIcon() {
    var icon2 = new GIcon();
    icon2.image = "/_layouts/images/FremantlePorts.Internet/"
                + "gatesicon.PNG";
    icon2.iconAnchor = new GPoint(16, 16);
    icon2.infoWindowAnchor = new GPoint(16, 0);
    icon2.iconSize = new GSize(30, 30);
    icon2.shadowSize = new GSize(59, 30);

    return icon2;
}

function getParkingIcon() {
    var icon2 = new GIcon();
    icon2.image = "/_layouts/images/FremantlePorts.Internet/"
                + "parkingicons.PNG";
    icon2.iconAnchor = new GPoint(16, 16);
    icon2.infoWindowAnchor = new GPoint(16, 0);
    icon2.iconSize = new GSize(30, 30);
    icon2.shadowSize = new GSize(59, 30);

    return icon2;
}



/* End Ports General Google Maps */

/*Start Waves And Currents Google Maps */

function WavesAndCurrentsWPinitialize() {
    var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi?key=" + MapKey + "&callback=loadWavesAndCurentsMaps";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadWavesAndCurentsMaps() {
    google.load("maps", "2", { "callback": loadWavesAndCurrentsMapApi });
}

function loadWavesAndCurrentsMapApi() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("WavesAndCurrentsMap"));
        var latlng = new GLatLng(-32.0264, 115.7595)

        map.setCenter(latlng, 10);
        map.setUIToDefault();
        geocoder = new GClientGeocoder();


        var innerHarImgLoc = $("[id$=WavesAndCurrentsPageUrl1]").val();
        var outerHarImgLoc = $("[id$=WavesAndCurrentsPageUrl2]").val();
        var rottnestImgLoc = $("[id$=WavesAndCurrentsPageUrl3]").val();

        var latlng1 = new GLatLng(-32.0536, 115.7387);
        var marker1 = new GMarker(latlng1, { title: "Inner Harbour" });
        GEvent.addListener(marker1, "click", function () {
            window.location = innerHarImgLoc;
        });
        map.addOverlay(marker1);

        latlng1 = new GLatLng(-31.988, 115.703);
        marker1 = new GMarker(latlng1, { title: "Wave Rider Buoy - Cottesloe" });
        GEvent.addListener(marker1, "click", function () {
            window.location = outerHarImgLoc;
        });

        map.addOverlay(marker1);

        latlng1 = new GLatLng(-32.034, 115.490);
        marker1 = new GMarker(latlng1, { title: "Wave Buoy - Off Rottnest" });
        GEvent.addListener(marker1, "click", function () {
            window.location = rottnestImgLoc;
        });

        map.addOverlay(marker1);
    }
}

/* End Waves And Currents */

/* Start Webcam Maps */


function WebcamsMapWPinitialize() {
    var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi?key=" + MapKey + "&callback=loadWebCamsMaps";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadWebCamsMaps() {
    google.load("maps", "2", { "callback": loadWebCamsMapApi });
}

function loadWebCamsMapApi() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("WebcamsWPMap"));
        var latlng = new GLatLng(-32.0480, 115.743290)

        map.setCenter(latlng, 15);
        map.setUIToDefault();
        geocoder = new GClientGeocoder();

        var temarrTitle = $("[id$=webcamsTitle]").val().split("#$%@^@");
        var temarrMapLogitude = $("[id$=webcamsLogitutude]").val().split("#$%@^@");
        var temarrLatitude = $("[id$=webcamsLatitutude]").val().split("#$%@^@");
        var temarrPageUrls = $("[id$=webcamsUrls]").val().split("#$%@^@");
        var temarrWebCamNumber = $("[id$=webcamNumber]").val().split("#$%@^@");

        if (temarrMapLogitude != null) {
            for (var a = 0; a < temarrMapLogitude.length; a++) {
                var webcammarker = createWebCamMarker(temarrTitle[a], temarrMapLogitude[a], temarrLatitude[a], temarrPageUrls[a], temarrWebCamNumber[a]);
                map.addOverlay(webcammarker);
            }
        }
    }
}

function createWebCamMarker(name, longitude, latitude, purl, webcamNum) {
    var latlng1 = new GLatLng(longitude, latitude);
    var marker1 = new GMarker(latlng1, { icon: getWebCamIcon(webcamNum), title: name });
    GEvent.addListener(marker1, "click", function () {
        window.location = purl;
    });
    return marker1;
}

function getWebCamIcon(webcamNum) {
    var icon2 = new GIcon();
    //    var isWebCam = $("[id$=isWebCam]").val()
    //    if (isWebCam == "True")
    //        icon2.image = "/_layouts/images/FremantlePorts.Internet/"
    //                + "camera" + webcamNum + ".png";
    //    else
    //        icon2.image = "/_layouts/images/FremantlePorts.Internet/"
    //                + "TruckCamView" + webcamNum + ".png";
    icon2.image = "/_layouts/images/FremantlePorts.Internet/"
                    + "cameraImage.png";
    icon2.iconAnchor = new GPoint(16, 16);
    icon2.infoWindowAnchor = new GPoint(16, 0);
    icon2.iconSize = new GSize(32, 32);
    icon2.shadowSize = new GSize(59, 32);

    return icon2;
}

var spinnerVisible = false;

//function showProgress() {
//    if (!spinnerVisible) {
//        $("div#spinner").fadeIn("fast");
//        spinnerVisible = true;
//        
//    }
//}

//function hideProgress() {
//    if (spinnerVisible) {
//        var spinner = $("div#spinner");
//        spinner.stop();
//        spinner.fadeOut("fast");
//        spinnerVisible = false;
//    }
//} 

/* End Webcam Maps */

/* cookie handling for font size */
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

/* font resizing */

var fontSize;
var changed = false;
var oldSize = 1;
function resizeText(scale, force) {
    if (fontSize == null) {
        // try to get from the cookie
        cookieSize = readCookie('fpaInternetFont');
        if (fontSize == null) fontSize = 1;
        fontSize = parseInt(cookieSize);
    }

    //decide whether to increase the size. -1 means small, 0 means normal, 1 means large
    if (scale != null) {
        changed = true;
        if (scale < 0) {
            if (fontSize > 8) fontSize = fontSize - 1; else fontSize = 8;
        }
        else if (scale > 0) {
            if (fontSize < 12) fontSize = fontSize + 1; else fontSize = 12;
        }
        createCookie('fpaInternetFont', fontSize, 0);
    }
    if (oldSize != fontSize) {
        $(".mid_content").css("font-size", (fontSize / 10) + "em");
        oldSize = fontSize;
    }
}


/* Dolphin Marker Dialog */

function DialogPageRedirect(prevURL) {
    window.location = prevURL;
}

function ConfirmDolphinMarkerPopup() {
    alert("Dolphin Markings have been added successfully, Dolphin sightings will be updated shortly");
    parent.$.fancybox.close();
}

function replaceAnchorTag(newHref) {
    $("#DolphinContent a[href='/_layouts/FremantlePorts.Internet/AddDolphinMarker.aspx']").attr('href', newHref);
}

function CloseFancyBoxPopup() {
    parent.$.fancybox.close();
}


/* SharePoint window resizing, stripped and modified from core.js, because it is not loaded for anonymous sites */
function FPGetViewportHeight() {
    if (typeof (window.innerHeight) != 'undefined')
        viewportHeight = window.innerHeight;
    else
        viewportHeight = document.documentElement.clientHeight;
    return viewportHeight;
}
function FPGetViewportWidth() {
    if (typeof (window.innerWidth) != 'undefined')
        viewportWidth = window.innerWidth;
    else
        viewportWidth = document.documentElement.clientWidth;
    return viewportWidth;
}
var g_fpviewportHeight = null, g_fpviewportWidth = null, g_fpwpadderHeight = 0, g_fpsetWidth, g_fpsetWidthInited = false, g_fpworkspaceResizedHandlers = [], g_fpsetScrollPos = false;
var g_fpfrl = false;
function FPFixRibbonAndWorkspaceDimensionsForResize() {
    if (g_fpfrl)
        return;
    var vph = FPGetViewportHeight();
    var vpw = FPGetViewportWidth();
    if (g_fpviewportHeight == vph
		&& g_fpviewportWidth == vpw) {
        return;
    }
    g_fpviewportHeight = vph;
    g_fpviewportWidth = vpw;
    window.setTimeout(FPFixRibbonAndWorkspaceDimensions, 0);
}
function FPFixRibbonAndWorkspaceDimensions() {
    g_fpfrl = true;
    var elmRibbon = GetCachedElement("s4-ribbonrow");
    var elmWorkspace = GetCachedElement("s4-workspace");
    var elmTitleArea = GetCachedElement("s4-titlerow");
    var elmBodyTable = GetCachedElement("s4-bodyContainer");
    if (!elmRibbon ||
	   !elmWorkspace ||
	   !elmBodyTable) {
        return;
    }
    if (!g_fpsetWidthInited) {
        var setWidth = true;
        if (elmWorkspace.className.indexOf("s4-nosetwidth") > -1)
            setWidth = false;
        g_fpsetWidth = setWidth;
        g_fpsetWidthInited = true;
    }
    else {
        var setWidth = g_fpsetWidth;
    }
    var baseRibbonHeight = RibbonIsMinimized() ? 44 : 135;
    var ribbonHeight = baseRibbonHeight + g_fpwpadderHeight;
    if (GetCurrentEltStyle(elmRibbon, "visibility") == "hidden") {
        ribbonHeight = 0;
    }
    elmRibbon.style.height = ribbonHeight + "px";
    var vph = g_fpviewportHeight;
    if (null === vph) {
        vph = FPGetViewportHeight();
        g_fpviewportHeight = vph;
    }
    var newWorkspaceHeight = vph - elmRibbon.offsetHeight - AbsTop(elmRibbon);
    if (newWorkspaceHeight < 0)
        newWorkspaceHeight = 0;
    elmWorkspace.style.height = newWorkspaceHeight + "px";
    if (setWidth) {
        elmWorkspace.style.width = document.documentElement.clientWidth + "px";
        if (elmBodyTable.offsetWidth < elmWorkspace.clientWidth)
            elmBodyTable.style.width = elmWorkspace.clientWidth + "px";
        if (elmTitleArea) {
            elmTitleArea.style.width = Math.max(elmBodyTable.offsetWidth - 1, 0) + "px";
            elmTitleArea.className += " ms-titlerowborder";
        }
    }
    var isIE7 = browseris.ie && browseris.iever == 7 && !browseris.ie8standard;
    if (!g_fpsetScrollPos) {
        if (browseris.firefox && browseris.firefox36up)
            window.scroll(0, 0);
        if (window.location.search.match("[?&]IsDlg=1")) {
            if (!isIE7 || elmWorkspace.scrollHeight < elmWorkspace.clientHeight)
                elmWorkspace.style.overflowY = "auto";
        }
        var scrollElem = document.getElementById("_maintainWorkspaceScrollPosition");
        if (scrollElem != null && scrollElem.value != null) {
            elmWorkspace.scrollTop = scrollElem.value;
        }
        g_fpsetScrollPos = true;
    }
    var handlers = [].concat(g_fpworkspaceResizedHandlers);
    for (var i = 0, wLen = handlers.length; i < wLen; i++) {
        handlers[i]();
    }
    g_fpfrl = false;

    resizeWorkspace();
}

