/* NOTES
Different map data and map sidebar content is created dynamically based on the tab selection.
*/

// map object
var map;
var directions;
var directionsPanel;
var building_overlay =  {
    "url": "http://www.adelaide.edu.au/campuses/northtce/googleapp/kml/building_overlay.kml",
    "name": "Buildings Overlay"
};

var defaultHTML = '<div id="mapcontrols"><label><input type="checkbox" id="overlaybuilding" onClick="show_buildings_overlay(this.checked);"/> overlay main buildings</label><label><input type="checkbox" id="maptype" onClick="maptype_toggle(this.checked);"/> satellite view </label></div><div id="map"></div><div id="sidebar"</div>';


$(document).ready(function(){
    SetupMap();
    useful_facilities_content();

    $(".w1").click(function(){
        tabSelect(this.id);
        return false;
    });
    // load building data for second tab in advance - speeds things up.
    LoadBuildingData();
});

// tab change styling
function tabSelect(id) {
    var $this = $("#"+id);
    $(".w1").removeClass('current');
    $this.addClass('current');

    // controls which controls are loaded in sidebar and which data to display.
    switch (id) {
    case "facilities_services":
        $("#mapcontainer").empty().append(defaultHTML);
        SetupMap();
        useful_facilities_content();
        break;

    case "find_building":
        $("#mapcontainer").empty().append(defaultHTML);
        SetupMap();
        find_building_content();
        break;

    case "virtual_tours":
        $("#mapcontainer").empty().append(defaultHTML);
        SetupMap();
        virtual_tours_content();
        break;

    case "printable_maps":
        HTMLpageLoad('/campuses/northtce/printmaps/index.html');
        break;

    case "get_directions":
        directionsetup();
        break;

    case "campus_history":
        HTMLpageLoad('/campuses/northtce/history/index.html');
        break;
    }
}

function HTMLpageLoad(file) {
    $.ajax({ url: file,
             success: function(data) {
                 data = data.replace(/<\/?html[^>]*>/ig, "");
                 $('#mapcontainer').empty().html(data);
             }
           });
}

function SetupMap() {
    //setup map
    // map = new google.maps.Map2(document.getElementById("map"));
    map = new GMap2(document.getElementById("map"))
    centre_map();
    map.setMapType(G_NORMAL_MAP);
    map.addControl(new GLargeMapControl());
    // setup custom control checkboxes for building overlay and map view
    show_buildings_overlay(true);
    $("#overlaybuilding").attr('checked','checked');

    // directions stuff
    directionsPanel = document.getElementById("sidebar");
    directions = new GDirections(map, directionsPanel);
    //error handler
    GEvent.addListener(directions, "error", handleErrors);
}


// toggles map type satelite or normal
function maptype_toggle(checked) {
    if (checked){ map.setMapType(G_HYBRID_MAP);}
    else {
        map.setMapType(G_NORMAL_MAP);
    }
}

// clears all overlays then adda campus image back in.
function cleanup_overlays() {
    map.clearOverlays();
    show_buildings_overlay(true);
}


// toggles the main building overlay
function show_buildings_overlay(checked) {
    if (checked) {
        // see layers.js for the building_overlay definition.
        var url = building_overlay.url + "?nocache=" + (new Date()).valueOf();
        var geoXml = new GGeoXml(url);
        // adds the geoxml object to the layer
        building_overlay.geoXml = geoXml;
        //add the layer
        map.addOverlay(geoXml);
    } else {
        map.removeOverlay(building_overlay.geoXml);
    }
}


function centre_map() {
    map.setCenter(new google.maps.LatLng(-34.9197078505854, 138.6043632030487), 17);
};

// directions fucntions

function directionsetup() {
    $("#mapcontainer").empty().append(defaultHTML);
    SetupMap();
    cleanup_overlays();
    var $directionHTML = '<div class="search-info"><h2>Get Directions</h2><h3>start address:</h3><input id="street" size="40" class="searchinput" name="street_address" type="text" size="30" value="" maxlength="255"/><input type="image" alt="get directions" title="get directions" src="/global/images/search_icon_btn.gif" value="directions" name="directions" onClick="overlayDirections();"/><h3>end address:</h3>University of Adelaide, North Terrace Campus';
    $("#sidebar").empty().append($directionHTML);
}


function overlayDirections() {
    var fromAddress = document.getElementById("street").value;
    // var fromAddress = "6 edmund ave, unley SA 5061";
    var toAddress = "230 North Terrace, Adelaide SA 5000";
    $("#sidebar").empty();
    directions.load("from: " + fromAddress + " to: " + toAddress);

    $("#sidebar").append("<strong><a href='#' onClick='directionsetup();'>Start Again</a></strong>");
}


/*
* Display error to user
*/
function handleErrors() {
    if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        $("#sidebar").empty().append("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
        $("#sidebar").empty().append("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
        $("#sidebar").empty().append("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_KEY)
        $("#sidebar").empty().append("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
        $("#sidebar").empty().append("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
    else  $("#sidebar").empty().append("An unknown error occurred.");

    $("#sidebar").append("<p><strong>Tip: </strong>Try separating address with commas: street, town, country</p>");
    $("#sidebar").append("<p><strong><a href='#' onClick='directionsetup();'>Start Again</a></strong></p>");
}



