﻿// Google Map code
// Coded by Rod Howarth (http://rodhowarth.com), Shari Cahill and Andrew Oneill

//center of map
var centerLatitude = -27.47795364
var centerLongitude = 153.02852690
var centerPoint = new GLatLng(centerLatitude, centerLongitude);

//gardens point center
var gpLatitude;
var gpLongitude;

var gpTopLeftLong;
var gpTopLeftLat;
var gpBottomLeftLong;
var gpBottomLeftLong;

//kelvin grove center
var kgLatitude = -27.446934231502196; 
var kgLongitude = 153.010014295578;

var kgTopLeftLong;
var kgTopLeftLat;
var kgBottomLeftLong;
var kgBottomLeftLong;

//urban village center
var uvLatitude = -27.44527731593883; 
var uvLongitude = 153.02167654037476;

var uvTopLeftLong;
var uvTopLeftLat;
var uvBottomLeftLong;
var uvBottomLeftLong;

//location to sprout info windows from.
var infoMarkerLoc = new GLatLng(-27.480043698907274, 153.02632212638855);
var kgInfoMarkerLoc = new GLatLng(-27.44908242552985, 153.00771196884155);
var uvInfoMarkerLoc = new GLatLng(-27.447412240299437, 153.01994919776917);

//info marker
var infoMarker;         
//zoom level of map
var startZoom = 17
//map object
var map;
//me marker object
var meMarker;
//markers array
var markersArray = new Array();
var markerInFocus;
var markerInFocusImage;
var curCampus = 1;

var firstLoad = true;

var iconWidth = 19;
var iconHeight = 32;

/// function for adding marker to map
function AddMarker(latitude, longitude, machineID, type) {

    // Create marker icon
    var imageIcon = new GIcon(G_DEFAULT_ICON);
    imageIcon.image = "images/MapIcons/" + type + ".png";
    imageIcon.iconSize = new GSize(iconWidth, iconHeight);
    imageIcon.shadowSize = new GSize (0, 0);
	// Set up GMarkerOptions object
	markerOptions = { icon:imageIcon };

    var marker = new GMarker(new GLatLng(latitude, longitude), markerOptions);
  
    markersArray[machineID] = marker;
    //add event listner
    GEvent.addListener(marker, 'click', function() { DisplayMachineInfo(machineID, marker); });               
    map.addOverlay(marker);
}

///Method to add the icon for user to drag
function addMeIcon() {
    //create new icon
    var meIcon = new GIcon(G_DEFAULT_ICON);
    meIcon.shadowSize = new GSize (0, 0);
    meIcon.image = "images/cool.png";
    meIcon.iconSize = new GSize (20,20);

    //set marker options, remove autopan so cant drag off map
    markerOptions = {icon:meIcon, draggable:true, autoPan:false};

    //create marker
    meMarker = new GMarker(new GLatLng(centerLatitude, centerLongitude), markerOptions);

    //Add event handlers
    GEvent.addListener(meMarker, 'dragstart', function() { meMarker.closeInfoWindow(); });
    GEvent.addListener(meMarker, 'dragend', LocateMeOnMap);
  
    //add to map
    map.addOverlay(meMarker);

    //create the window asking user to set it, don't make it autopan map
    meMarker.openInfoWindowHtml('Drag this icon to your current<br />  location', {suppressMapPan:true} );

}

///Event handler for when marker is placed
function LocateMeOnMap(latlng) {
    //get the coodrinates
    var latitude = latlng.lat();
    var longitude = latlng.lng();

    //get the textual reference
    var mapSpan = document.getElementById("blockLocation");

        //procedure for displaying block
        function resultProc(result) {
        //set text reference
        mapSpan.innerHTML = result + '';

     //Regenerate the machines to re-order listing.
     // but only if it is the first time youve moved it (ie you havent selected machines yet)
        if (markersArray.length !=0 ) {
            window.setTimeout(RegenerateMachines, 1000);
        } else {
        //thank the user and tell them what to do next
        DisplayInfoWindow('You selected ' + result + ', Thanks! <br /> Now select what type of product you <br /> are after, ' +
                            'the machines that stock that<br />  type of product will be displayed on the map.');
        }
        }

    //get the block they are in
    MachinesService.GetBlock(longitude, latitude, resultProc);
    

}

//function for looping through JSON result from ajax
function PopulateMachines(result) {
    markersArray = new Array();
    markerInFocus = null;
    markerInFocusImage = null;

    map.clearOverlays();
    map.addOverlay(infoMarker);
    map.addOverlay(meMarker);
     // parse the result as json
     var jResult = eval('(' + result + ')');

        // loop through all the machines
         for (var i = 0; i < jResult.Machines.length; i++) {
         //get current machine
          var curMachine = jResult.Machines[i].Machine;
          
          //create a marker for machine
          AddMarker(curMachine.Lat, curMachine.Long, curMachine.MachineID, curMachine.MachineType);
          
         }

    //show the machines near them
   ShowReccomendedMachines(jResult);

}
     
function ShowReccomendedMachines(jResult){
    var output = "<span id='machinesHeader'><b>Closest Machines</b></span> <br/> <br/>";

    // limit it to 5 machiens displayed
    var machineLimit = 5;
    
    if (jResult.Machines.length < 5) {
    machineLimit = jResult.Machines.length;
    }
    

    // loop through all the machines, should be sorted in order
     for (var i = 0; i < machineLimit; i++) {
     //get current machine
      var curMachine = jResult.Machines[i].Machine;
         output += "<div style='float:left; margin-right: 5px;'><img src='images/MapIcons/" + curMachine.MachineType + ".png' /></div> "; 
        output += "<a href='javascript:DisplayMachineInfo(" + curMachine.MachineID + ")'>" + curMachine.MachineType + " Machine</a><br />";
        output +=  curMachine.BlockName + " - " + curMachine.Floor + "<div class='clear' /><br />";
       
     }
    //get the container div
     var machineDetailsContainer = document.getElementById("detailsContent");
    
     //set the content
      machineDetailsContainer.innerHTML = output;
      
      //animate
      if (jResult.Machines.length !=0) {
        AnimateMachinesHeader();
      }
      

}     

///function to add sone animation to the machines nearby
function AnimateMachinesHeader() {
    var machinesHeader = document.getElementById('machinesHeader');
    var animatedOnce = false;
    var i = 8;
    increaseSize(i);
    function increaseSize(size){
        machinesHeader.style.fontSize = '' + size + 'px'; 
        
        if (i < 17) {
        i++;
         window.setTimeout(function(){ increaseSize(i); }, 1);
        } else {
        
         decreaseSize(i);
        }
      
    }
    
    function decreaseSize(size){
        machinesHeader.style.fontSize = '' + size + 'px'; 

        if (i > 14) {
        i--;
         window.setTimeout(function(){ decreaseSize(i); }, 1);
        } else {
        if (animatedOnce == false) {
        i = 8;
        increaseSize(i);
        }
        
        animatedOnce = true;
        
        }
    }
    
   
    
    
}
     
     
//function for adding TPhoto background image to map     
function AddBackground() {

    //gardens point
    //create new tphoto object
    photo = new TPhoto();
    photo.id = 'qutPhoto';
    photo.src = 'images/Overlays/gpOverlay.jpg';
    photo.percentOpacity = 100;

    //set anchors
    photo.anchorTopLeft = new GLatLng(-27.47502267, 153.025238513);
    photo.anchorBottomRight = new GLatLng(-27.480690,153.0317831);

    //add to map
    map.addTPhoto(photo);
    
    
    //kelvin grove
    //create new tphoto object
    photo = new TPhoto();
    photo.id = 'kgPhoto';
    photo.src = 'images/Overlays/kgOverlay.jpg';
    photo.percentOpacity = 100;

    //set anchors
    photo.anchorTopLeft = new GLatLng(-27.444515556568664, 153.0065814754486);
    photo.anchorBottomRight = new GLatLng(-27.44932380315464, 153.0132007598877);

    //add to map
    map.addTPhoto(photo);
    
    //KGUV
    //create new tphoto object
    photo = new TPhoto();
    photo.id = 'uvPhoto';
    photo.src = 'images/Overlays/uvOverlay.jpg';
    photo.percentOpacity = 100;

    //set anchors
    photo.anchorTopLeft = new GLatLng(-27.442527390370508, 153.0184329914093);
    photo.anchorBottomRight = new GLatLng(-27.447857620512906, 153.02490936050415);

    //add to map
    map.addTPhoto(photo);
}     

//function to create a clippy style marker
function CreateInfoMarker() {
    

    // Create marker icon
    var infoIcon = new GIcon(G_DEFAULT_ICON);
    infoIcon.image = "images/MapIcons/infoIcon.png";
    //infoIcon.shadowSize = new GSize (0, 0);
    infoIcon.iconSize = new GSize (60,60);
    // Set up GMarkerOptions object
    markerOptions = { icon:infoIcon };

    infoMarker = new GMarker(infoMarkerLoc, markerOptions);
    
    GEvent.addListener(infoMarker, 'click', function() { DisplayInfoWindow("Drag the smilie icon to your location, <br /> " +
                                                         "and then select the type of machine you are looking for. <br />" +
                                                         "A list of the closest machines will be displayed, click on any <br />" +
                                                         "to see information about the machine and how to find it."); });   
    map.addOverlay(infoMarker);
} 


//method to display the info window clippy style down the bottom
function DisplayInfoWindow(html){

    var infoWindowLoc = new GLatLng(infoMarker.getLatLng().lat(), infoMarker.getLatLng().lng() + 0.0004)
    //opens it at the infowindow loc which is a little bit off the icon to look better
    map.openInfoWindowHtml(infoWindowLoc, html, {suppressMapPan:true});

}  

//initialization function   
function init() {
    //check for browser compatibility
    if (GBrowserIsCompatible()) {
        //create new map
        map = new GMap2(document.getElementById("map"));   
        map.disableDragging();
       /// map.enableScrollWheelZoom();
        //set center
        var location = new GLatLng(centerLatitude, centerLongitude);
        map.setCenter(location, startZoom);
       
        //add tphoto background
        AddBackground();
               
        //create the info marker
        CreateInfoMarker();
      
        //add the me icon
        addMeIcon();
        
        //change campus
        ChangeCampus();
                
        //generate the machines
        RegenerateMachines();

    }

}

function ChangeCampus() {
     var selectedCampus;
     
     //select campus
     if (document.getElementById('rdbGP').checked) {
        selectedCampus = 1;
     }
     
     if (document.getElementById('rdbKG').checked) {
        selectedCampus = 2;
     }
     
     if (document.getElementById('rdbUV').checked) {
     selectedCampus = 3;
     }


    //check that its not the one selected
    if (selectedCampus != curCampus) {
        
        if (selectedCampus == 1) {
            //center on gardens point
             var location = new GLatLng(centerLatitude, centerLongitude);
             map.setCenter(location, startZoom);
             curCampus = 1;
             
             //change info icon and me icon
             infoMarker.setLatLng(infoMarkerLoc);
             meMarker.setLatLng(location);
             
        } 
        
        if (selectedCampus ==2) {
            //center on kelvin grove
            var KGlocation = new GLatLng(kgLatitude, kgLongitude);
            map.setCenter(KGlocation, startZoom);
            curCampus = 2;
            
            //change info icon and me icon
             infoMarker.setLatLng(kgInfoMarkerLoc);
             meMarker.setLatLng(KGlocation);            
        } 
        
        if (selectedCampus ==3) {
              //center on kelvin grove
            var UVlocation = new GLatLng(uvLatitude, uvLongitude);
            map.setCenter(UVlocation, startZoom);
            curCampus = 3;
            
            //change info icon and me icon
             infoMarker.setLatLng(uvInfoMarkerLoc);
             meMarker.setLatLng(UVlocation);  
        
        }  
        
        LocateMeOnMap(meMarker.getLatLng());
        RegenerateMachines();
    
    }

}

/// Method to change the image of a machien to be the machine in focus
function ChangeImage(machineID, image) {
   
   //see if a marker had already had its image changed
    if (markerInFocus != null) {
        // yes, so change its image back to what it was before (markerInFocusImage)
        markerInFocus.setImage(markerInFocusImage);
    }

    //get the new machineID from the array
    var marker = markersArray[machineID];
    
     //save the original image to be the markerInFocusImage
    markerInFocusImage = marker.getIcon().image;
    
    //set the marker to be in focus 
    markerInFocus = marker;
    
    //set the image 
    marker.setImage(image);

}

//function for displaying machine information
function DisplayMachineInfo(machineID, marker) {


    //get the container div
     var machineDetailsContainer = document.getElementById("detailsDiv");
     //make it visible
     machineDetailsContainer.style.display = 'block';
    
     window.setTimeout(function() {ChangeImage(machineID, "images/MapIcons/selectedIcon.png")}, 100);
    
     //get the content div
     var machineDetailsDiv = document.getElementById("detailsContent");

           //function to display machine info
         function SucceededCallback(result) {
         
             var formattedDetails;
             //parse json
             var jResult = eval('(' + result + ')');

            var returnedMachine = jResult.Machines[0].Machine;
                  
             //formattedDetails = "<p class='machineName'> " + returnedMachine.MachineNo + "<br /> ";
             formattedDetails = "<p class='machineName'> " + returnedMachine.MachineType + " Machine<br /> ";
             formattedDetails += "<img class='smallImage' alt='" + returnedMachine.MachineNo + "' src='"; 
             formattedDetails +=  returnedMachine.ImageLoc + "' /></p>";
             formattedDetails += "<a style='color: black' href='feedback.aspx?mID=";
             formattedDetails +=  machineID + "'>Submit feedback on this machine</a>";
             formattedDetails += "<br />";
             formattedDetails += "<b>Location:- </b>" + returnedMachine.BlockName + " Level " + returnedMachine.Floor + "<br />";
             formattedDetails += "<b>How to find it:- </b> <br />" + returnedMachine.Description + "<br />";        
             formattedDetails += "Shown as <img src='images/MapIcons/SelectedIconSmall.png' style='height: 20px' /> on the map.<br /> "; 
             
             DisplayInfoWindow(formattedDetails);

            
         }
      
     // call web service to retrieve machine details
     MachinesService.GetMachineDetails(machineID, SucceededCallback);
     
}




//function to show the selected categories on map
// this function gets called by an eventhandler function created in default.aspx.cs file as a registered script
function ShowCategories(catIDs) {

    if (catIDs.length > 0 ){
        firstLoad = false;
    }

    if (firstLoad != true) {

        //close all info windows
        map.closeInfoWindow();
        
        //get the lat long of current position
        var meLatLng = meMarker.getLatLng();
 
        //get campus
        var campusID;
        if (document.getElementById('rdbGP').checked) {
            campusID = 1;
        } else {
            campusID = 2;    
        }
        
        //get all machines in categoories
        MachinesService.GetMachinesInCategory(catIDs, meLatLng.lng(), meLatLng.lat(), curCampus, PopulateMachines);
     
     
    }
    firstLoad = false;
}


window.onload = init;
window.onunload = GUnload;

