﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
// The above line is for intellisense support in VS2010

/* Logic for index.html */

google.load("earth", "1");

// Globals
var ge;
var isInit = false;     // whether or not we have initialised the map to VIC

function init() {
    google.earth.createInstance('map3d', initCB, failureCB);
}

function initCB(instance) {
    ge = instance;
    ge.getWindow().setVisibility(true);

    // add a navigation control
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);

    // add some layers
    //ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
    //ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
    ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, true);

    // init to VIC
    initToVic();
}

function failureCB(errorCode) {
    alert("ERROR: " + errorCode);
}

function initToVic() {
    // fly to VIC
    var la = ge.createLookAt('');

    la.set(-37, 144.8,
                0, // altitude
                ge.ALTITUDE_RELATIVE_TO_GROUND,
                0, // heading
                0, // straight-down tilt
                900000 // range (inverse of zoom)
            );

    ge.getView().setAbstractView(la);

    isInit = true;
}

function showLabels(cb) {
    ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, cb.checked);

    if (cb.checked)
        gaTrackEvent('Options', 'GE show', 'Labels');
}

function showRoads(cb) {
    ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, cb.checked);

    if (cb.checked)
        gaTrackEvent('Options', 'GE show', 'Roads');
}

function showScale(cb) {
    ge.getOptions().setScaleLegendVisibility(cb.checked);

    if (cb.checked)
        gaTrackEvent('Options', 'GE show', 'Scale');
}

function showStatus(cb) {
    ge.getOptions().setStatusBarVisibility(cb.checked);

    if (cb.checked)
        gaTrackEvent('Options', 'GE show', 'Status');
}

function showOverview(cb) {
    ge.getOptions().setOverviewMapVisibility(cb.checked);

    if (cb.checked)
        gaTrackEvent('Options', 'GE show', 'Overview');
}

function showGrid(cb) {
    ge.getOptions().setGridVisibility(cb.checked);

    if (cb.checked)
        gaTrackEvent('Options', 'GE show', 'Grid');
}

var kmlObjects = {};

function toggleKml(file, chkBox) {
    // remove the old KML object if it exists
    if (kmlObjects[chkBox.id]) {
        ge.getFeatures().removeChild(kmlObjects[chkBox.id]);
        kmlObjects[chkBox.id] = null;
    }

    // if the checkbox is checked, fetch the KML and show it on Earth
    if (chkBox.checked)
        loadKml(file, chkBox);
    else
        setMapTools();
}

function loadKml(file, chkBox) {
    $('#loadingAni').show();

    var kmlUrl = file;

    // fetch the KML
    google.earth.fetchKml(ge, kmlUrl, function (kmlObject) {
        // NOTE: we still have access to the 'file' variable (via JS closures)
        var n = $(chkBox).next().text();    // name = <label> text
        var cat = $(chkBox).parent().parent().attr('id');   // category

        if (kmlObject) {
            // set desc if applicable
            if (!kmlObject.getDescription() && $(chkBox).next().attr('title'))
                kmlObject.setDescription($(chkBox).next().attr('title'));

            // set default opacity to 75% for maps            
            if (cat == 'map')
                kmlObject.setOpacity(0.75);

            // save in array
            kmlObjects[chkBox.id] = kmlObject;

            // show it on Earth                    
            ge.getFeatures().appendChild(kmlObject);

            // Fly in to view if applicable
            if (kmlObject.getAbstractView())
                ge.getView().setAbstractView(kmlObject.getAbstractView());

            gaTrackEvent(cat, 'Load success', n + ' (' + chkBox.id + ')');
        } else {
            // bad KML
            kmlObjects[chkBox.id] = null;

            // wrap alerts in API callbacks and event handlers
            // in a setTimeout to prevent deadlock in some browsers
            setTimeout(function () {
                alert('Bad or null KML.');
            }, 0);

            // uncheck the box
            chkBox.checked = '';

            gaTrackEvent(cat, 'Load failure', n + ' (' + chkBox.id + ') - ' + kmlUrl);
        }

        $('#loadingAni').hide();
        setMapTools();
    });
}

// Show tools icon for loaded maps
function setMapTools() {
    if ($('#map li input:checked').length > 0)
        $('#mapSettings').show();
    else
        $('#mapSettings').hide();
}

function loadTour(file, name) {
    $('#loadingAni').show();
    $('#tourName').text(name);

    google.earth.fetchKml(ge, file, fetchCallback);

    function fetchCallback(fetchedKml) {
        // Alert if no KML was found at the specified URL.
        if (!fetchedKml) {
            setTimeout(function () {
                alert('Bad or null KML');
            }, 0);
            return;
        }

        // Add the fetched KML into this Earth instance.
        ge.getFeatures().appendChild(fetchedKml);
        $('#loadingAni').hide();

        // Walk through the KML to find the tour object & load it
        walkKmlDom(fetchedKml, function () {
            if (this.getType() == 'KmlTour') {
                ge.getTourPlayer().setTour(this);
                ge.getTourPlayer().play();
                $('#controls').show();
                return false;
            }
        });
    }

    gaTrackEvent('Tours', 'Load', name);
}

// Tour control functions
function exitTour() {
    ge.getTourPlayer().setTour(null);
    $("#controls").hide();
    initToVic();    // reset view

    // unload any features that may have been loaded with tour
    if (ge.getFeatures().hasChildNodes()) {
        for (var i = 0; i < ge.getFeatures().getChildNodes().getLength(); i++) {
            var f = ge.getFeatures().getChildNodes().item(i);
            var keep = false;

            // search thru loaded objects to work out if we want unload it or not
            for (var key in kmlObjects) {
                if (kmlObjects[key] === f) {
                    keep = true;
                    break;
                }
            }

            if (!keep)
                ge.getFeatures().removeChild(f);
        }
    }
}

google.setOnLoadCallback(init);

maps = function () {
    var uid;
	$.ajaxSetup({cache:false});
    function init() {
        getcookie();
        $.getJSON("ajax.php", { method: "resources", uid: uid }, function (data) {
            $.each(data.results, function (index, value) {
                if (value.type == 'tour') {
                    $("#" + value.type).append('<li><a href="javascript:loadTour(\'' + value.link + '\',\'' + value.name + '\');" title="' + value.description + '">' + value.name + '</a></li>');
                }
                else {
                    $("#" + value.type).append('<li><input type="checkbox" id="' + value.id + '" onclick="toggleKml(\'' + value.link + '\',this);" /><label for="' + value.id + '" title="' + value.description + '">' + value.name + '</label></li>');
                }
            });
            $(".box_content ul").each(function () {
                if ($(this).children().size() > 2) {
                    $(this).children(":gt(1)").hide();
                    $(this).append('<li class="disclose">See more &gt;&gt;</li>');
                }
            });
            $(".disclose").click(maps.seemore);
        });


    }
    function getcookie() {
        var re = /uid=([0-9a-f]+)/;
        if (re.test(document.cookie)) {
            uid = document.cookie.match(re)[1];
        }
        else {
            uid = new Date().getTime().toString(16);
            var never = new Date(2020, 1, 1).toGMTString();
            document.cookie = "uid=" + uid + "; domain=vicjourneys.com; expires=" + never + "; path=/";
        }
    }
    function seemore() {
        $(this).siblings().slideDown('fast');
        $(this).text("<< See less");
        $(this).unbind();
        $(this).click(maps.seeless);
    }
    function seeless() {

        $(this).text("See more >>");
        $(this).unbind();
        $(this).click(maps.seemore);
        $(this).siblings(':gt(1)').slideUp('fast');
    }

    return {
        init: init,
        seemore: seemore,
        seeless: seeless
    };

} ();

function loadMapsDialog() {
    $('#map li input:checked').each(function () {
        var id = $(this).attr('id');
        var ko = kmlObjects[id];    // ko is KmlFeature

        // extract the name
        var n = $(this).next().text();  // the <label> text

        if (ko) {
            $('#mapDialog').append('<div class="mdi" data="' + id + '"><div class="mdo">Opacity: <span>' + Math.floor(ko.getOpacity() * 100) + '%</span><div class="slider" id="mdis_' + id + '"></div></div>Map: <strong>' + n + '</strong><br/><input type="checkbox" id="mdi_' + id + '" /><label for="mdi_' + id + '">Unload?</label></div>');
            $('#mdis_' + id).slider({
                range: "min",
                min: 0,
                max: 100,
                value: ko.getOpacity() * 100,
                slide: function (event, ui) {
                    $(this).prev().text(ui.value + '%');
                }
            });
        }
    });
}

function applyMapDialogOptions() {
    $('#mapDialog div.mdi').each(function () {
        var id = $(this).attr('data');
        var ul = ($(this).children('input:checked').length > 0);    // unload?
        var op = $('#mdis_' + id).slider('option', 'value') / 100;     // opacity value

        var ko = kmlObjects[id];
        if (ko) {
            ge.getFeatures().removeChild(ko);

            if (ul) {
                kmlObjects[id] = null;

                // uncheck the item in main page
                $('#' + id).attr('checked', false);
                setMapTools();
            } else {
                // if not unload then we reload with new opacity setting
                ko.setOpacity(op);
                kmlObjects[id] = ko;
                ge.getFeatures().appendChild(ko);
            }
        }
    });
}

function gaTrackEvent(cat, action, label) {
    /// <summary>
    ///     Google Analytics event tracking
    /// </summary>
    /// <param name="cat" type="String">
    ///     Event category
    /// </param>
    /// <param name="action" type="String">
    ///     Event action
    /// </param>
    /// <param name="label" type="String">
    ///     Event label
    /// </param>
    if (_gaq) {
        _gaq.push(['_trackEvent', cat, action, label]);
    }
}

$(document).ready(function () {
    maps.init();

    $('#geViewPort').hover(
        function () {
            $('#geOptions').fadeIn();
        },
        function () {
            $('#geOptions').fadeOut();
        }
    );

    $('#mapDialog').dialog({
        autoOpen: false,
        width: 650,
        modal: true,
        buttons: {
            "Cancel": function () {
                $(this).dialog('close');
            },
            "Apply": function () {
                applyMapDialogOptions();
                $(this).dialog('close');
            }
        },
        open: function (event, ui) {
            $('#map3d').hide();
            loadMapsDialog();
        },
        close: function (event, ui) {
            $('#map3d').show();
            $(this).empty();
        }
    });

    $('#mapSettings').click(function () {
        $('#mapDialog').dialog('open');
        gaTrackEvent('Options', 'Open', 'Opacity dialog');
        return false;
    });

});
